diff --git a/.gitattributes b/.gitattributes index daba532231649930039d0a50f7487d670603016f..272dcdf705c84418712bb149584449a065507d35 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4445,3 +4445,5 @@ tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/dataset.cpyt tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/bc_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/bc_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b9396d8a0bb38ced76e55df01be803b8f3b287d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/bc_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7212991d6b5331aca35c5517d5836d0229117ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/base_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/base_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..552f1ff4d25bc6649ae1b55ab3e28bf3dc71975d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/base_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06eaf6dd6fc2b28147db527d3b5348801ffc813d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_context.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86c8cb0720ecebe9944684c66f22eb71b94f8dae Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner_group.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner_group.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eed35e36a3681c2826ea5c5ccc5f3001f7267613 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner_group.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d08708258df5e2489920755349ac06d9e717b47 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_multi_agent_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_multi_agent_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cada1d7a0fa15b933a491e1427fe906c43e7a668 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_multi_agent_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d20bdf03d39d6a3f4fa6d48a1394625a5add0575 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env_runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..028f700ccaeefed8981897302d1892660c5cb7ab Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env_runner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..475673b759c9f6d701424d955851347d98977544 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5fce1cd7e76ccc16f30a194e79b53a2670fd5eeffd12846f185ac2b5e302619 +size 105683 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_client.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3dc8a624a7eb99542468d834441736d6c85ba64 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_client.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_server_input.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_server_input.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..742c7937f281f27b0582510e3ff613b813510c6e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_server_input.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..735ac596ad1a9d505dbd884f01219ea7e16e92f5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_env_runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_env_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1df1de54bf02686a946dcb4c769c8a384b64afd6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_env_runner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18863f25753cbc1bba6ae05026f5fa152be7c2d4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/tcp_client_inference_env_runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/tcp_client_inference_env_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e84b4700012e0760eabb6a2f77e073b41f0a01d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/tcp_client_inference_env_runner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/vector_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/vector_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55dbfb43b4d7da0a6be539d8008bc95fd5019867 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/vector_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..343adb18b3c5477fe4c47a0c279cf729e1df1657 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__init__.py @@ -0,0 +1,12 @@ +from ray.rllib.env.external.rllink import ( + get_rllink_message, + send_rllink_message, + RLlink, +) + + +__all__ = [ + "get_rllink_message", + "send_rllink_message", + "RLlink", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9d12cbdf3e6638ba51c2785c9afa1e958c41c58 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/env_runner_server_for_external_inference.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/env_runner_server_for_external_inference.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb7bf987d1a382ca955d562978f932816966ab77 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/env_runner_server_for_external_inference.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/rllink.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/rllink.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8523f20dfdc0004a9563c6016fe651416b3796d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/rllink.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/env_runner_server_for_external_inference.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/env_runner_server_for_external_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..36bb2723c27b8cfc9e9f659d681432b07fd4d927 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/env_runner_server_for_external_inference.py @@ -0,0 +1,368 @@ +from collections import defaultdict +import pickle +import socket +import threading +import time +from typing import Collection, DefaultDict, List, Optional, Union + +from ray.rllib.core import ( + COMPONENT_RL_MODULE, + DEFAULT_AGENT_ID, + DEFAULT_MODULE_ID, +) +from ray.rllib.env import INPUT_ENV_SPACES +from ray.rllib.env.env_runner import EnvRunner +from ray.rllib.env.single_agent_env_runner import SingleAgentEnvRunner +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.env.external.rllink import ( + get_rllink_message, + send_rllink_message, + RLlink, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + EPISODE_DURATION_SEC_MEAN, + EPISODE_LEN_MAX, + EPISODE_LEN_MEAN, + EPISODE_LEN_MIN, + EPISODE_RETURN_MAX, + EPISODE_RETURN_MEAN, + EPISODE_RETURN_MIN, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.typing import EpisodeID, StateDict +from ray.util.annotations import DeveloperAPI + +torch, _ = try_import_torch() + + +@DeveloperAPI +class EnvRunnerServerForExternalInference(EnvRunner, Checkpointable): + """An EnvRunner communicating with an external env through a TCP socket. + + This implementation assumes: + - Only one external client ever connects to this env runner. + - The external client owns the connector pipelines (env-to-module and module-to-env) + as well as the RLModule and thus performs inference locally. Samples are sent in + bulk as lists of RLlib episodes once a certain number of timesteps has been executed + on the client's side. + - A copy of the RLModule is kept at all times on this EnvRunner, but is never used + for inference, only as a weights container. + TODO (sven): The above might be inefficient as we have to store basically two + models, one in this EnvRunner, one in the env (as ONNX). + - As a consequence, there are no environment and no connectors on this env runner. + The external env is responsible for generating all the data to create episodes. + """ + + @override(EnvRunner) + def __init__(self, *, config, **kwargs): + """ + Initializes an EnvRunnerServerForExternalInference instance. + + Args: + config: The AlgorithmConfig to use for setup. + + Keyword Args: + port: The base port number. The server socket is then actually bound to + `port` + self.worker_index. + """ + super().__init__(config=config, **kwargs) + + self.worker_index: int = kwargs.get("worker_index", 0) + + self._weights_seq_no = 0 + + # Build the module from its spec. + module_spec = self.config.get_rl_module_spec( + spaces=self.get_spaces(), inference_only=True + ) + self.module = module_spec.build() + + self.host = "localhost" + self.port = int(self.config.env_config.get("port", 5555)) + self.worker_index + self.server_socket = None + self.client_socket = None + self.address = None + + self.metrics = MetricsLogger() + + self._episode_chunks_to_return: Optional[List[SingleAgentEpisode]] = None + self._done_episodes_for_metrics: List[SingleAgentEpisode] = [] + self._ongoing_episodes_for_metrics: DefaultDict[ + EpisodeID, List[SingleAgentEpisode] + ] = defaultdict(list) + + self._sample_lock = threading.Lock() + self._on_policy_lock = threading.Lock() + self._blocked_on_state = False + + # Start a background thread for client communication. + self.thread = threading.Thread( + target=self._client_message_listener, daemon=True + ) + self.thread.start() + + @override(EnvRunner) + def assert_healthy(self): + """Checks that the server socket is open and listening.""" + assert ( + self.server_socket is not None + ), "Server socket is None (not connected, not listening)." + + @override(EnvRunner) + def sample(self, **kwargs): + """Waits for the client to send episodes.""" + while True: + with self._sample_lock: + if self._episode_chunks_to_return is not None: + num_env_steps = 0 + num_episodes_completed = 0 + for eps in self._episode_chunks_to_return: + if eps.is_done: + self._done_episodes_for_metrics.append(eps) + num_episodes_completed += 1 + else: + self._ongoing_episodes_for_metrics[eps.id_].append(eps) + num_env_steps += len(eps) + + ret = self._episode_chunks_to_return + self._episode_chunks_to_return = None + + SingleAgentEnvRunner._increase_sampled_metrics( + self, num_env_steps, num_episodes_completed + ) + + return ret + time.sleep(0.01) + + @override(EnvRunner) + def get_metrics(self): + # TODO (sven): We should probably make this a utility function to be called + # from within Single/MultiAgentEnvRunner and other EnvRunner subclasses, as + # needed. + # Compute per-episode metrics (only on already completed episodes). + for eps in self._done_episodes_for_metrics: + assert eps.is_done + episode_length = len(eps) + episode_return = eps.get_return() + episode_duration_s = eps.get_duration_s() + # Don't forget about the already returned chunks of this episode. + if eps.id_ in self._ongoing_episodes_for_metrics: + for eps2 in self._ongoing_episodes_for_metrics[eps.id_]: + episode_length += len(eps2) + episode_return += eps2.get_return() + episode_duration_s += eps2.get_duration_s() + del self._ongoing_episodes_for_metrics[eps.id_] + + self._log_episode_metrics( + episode_length, episode_return, episode_duration_s + ) + + # Now that we have logged everything, clear cache of done episodes. + self._done_episodes_for_metrics.clear() + + # Return reduced metrics. + return self.metrics.reduce() + + def get_spaces(self): + return { + INPUT_ENV_SPACES: (self.config.observation_space, self.config.action_space), + DEFAULT_MODULE_ID: ( + self.config.observation_space, + self.config.action_space, + ), + } + + @override(EnvRunner) + def stop(self): + """Closes the client and server sockets.""" + self._close_sockets_if_necessary() + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args + {"config": self.config}, # **kwargs + ) + + @override(Checkpointable) + def get_checkpointable_components(self): + return [ + (COMPONENT_RL_MODULE, self.module), + ] + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + return { + COMPONENT_RL_MODULE: self.module.get_state(), + WEIGHTS_SEQ_NO: self._weights_seq_no, + } + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + # Update the RLModule state. + if COMPONENT_RL_MODULE in state: + # A missing value for WEIGHTS_SEQ_NO or a value of 0 means: Force the + # update. + weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0) + + # Only update the weigths, if this is the first synchronization or + # if the weights of this `EnvRunner` lacks behind the actual ones. + if weights_seq_no == 0 or self._weights_seq_no < weights_seq_no: + rl_module_state = state[COMPONENT_RL_MODULE] + if ( + isinstance(rl_module_state, dict) + and DEFAULT_MODULE_ID in rl_module_state + ): + rl_module_state = rl_module_state[DEFAULT_MODULE_ID] + self.module.set_state(rl_module_state) + + # Update our weights_seq_no, if the new one is > 0. + if weights_seq_no > 0: + self._weights_seq_no = weights_seq_no + + if self._blocked_on_state is True: + self._send_set_state_message() + self._blocked_on_state = False + + def _client_message_listener(self): + """Entry point for the listener thread.""" + + # Set up the server socket and bind to the specified host and port. + self._recycle_sockets() + + # Enter an endless message receival- and processing loop. + while True: + # As long as we are blocked on a new state, sleep a bit and continue. + # Do NOT process any incoming messages (until we send out the new state + # back to the client). + if self._blocked_on_state is True: + time.sleep(0.01) + continue + + try: + # Blocking call to get next message. + msg_type, msg_body = get_rllink_message(self.client_socket) + + # Process the message received based on its type. + # Initial handshake. + if msg_type == RLlink.PING: + self._send_pong_message() + + # Episode data from the client. + elif msg_type in [ + RLlink.EPISODES, + RLlink.EPISODES_AND_GET_STATE, + ]: + self._process_episodes_message(msg_type, msg_body) + + # Client requests the state (model weights). + elif msg_type == RLlink.GET_STATE: + self._send_set_state_message() + + # Clients requests config information. + elif msg_type == RLlink.GET_CONFIG: + self._send_set_config_message() + + except ConnectionError as e: + print(f"Messaging/connection error {e}! Recycling sockets ...") + self._recycle_sockets(5.0) + continue + + def _recycle_sockets(self, sleep: float = 0.0): + # Close all old sockets, if they exist. + self._close_sockets_if_necessary() + + time.sleep(sleep) + + # Start listening on the configured port. + self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + # Allow reuse of the address. + self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.server_socket.bind((self.host, self.port)) + # Listen for a single connection. + self.server_socket.listen(1) + print(f"Waiting for client to connect to port {self.port}...") + + self.client_socket, self.address = self.server_socket.accept() + print(f"Connected to client at {self.address}") + + def _close_sockets_if_necessary(self): + if self.client_socket: + self.client_socket.close() + if self.server_socket: + self.server_socket.close() + + def _send_pong_message(self): + send_rllink_message(self.client_socket, {"type": RLlink.PONG.name}) + + def _process_episodes_message(self, msg_type, msg_body): + # On-policy training -> we have to block until we get a new `set_state` call + # (b/c the learning step is done and we can send new weights back to all + # clients). + if msg_type == RLlink.EPISODES_AND_GET_STATE: + self._blocked_on_state = True + + episodes = [] + for episode_state in msg_body["episodes"]: + episode = SingleAgentEpisode.from_state(episode_state) + episodes.append(episode.to_numpy()) + + # Push episodes into the to-be-returned list (for `sample()` requests). + with self._sample_lock: + if isinstance(self._episode_chunks_to_return, list): + self._episode_chunks_to_return.extend(episodes) + else: + self._episode_chunks_to_return = episodes + + def _send_set_state_message(self): + send_rllink_message( + self.client_socket, + { + "type": RLlink.SET_STATE.name, + "state": self.get_state(inference_only=True), + }, + ) + + def _send_set_config_message(self): + send_rllink_message( + self.client_socket, + { + "type": RLlink.SET_CONFIG.name, + # TODO (sven): We need AlgorithmConfig to be a `Checkpointable` with a + # msgpack'able state. + "config": pickle.dumps(self.config), + }, + ) + + def _log_episode_metrics(self, length, ret, sec): + # Log general episode metrics. + # To mimic the old API stack behavior, we'll use `window` here for + # these particular stats (instead of the default EMA). + win = self.config.metrics_num_episodes_for_smoothing + self.metrics.log_value(EPISODE_LEN_MEAN, length, window=win) + self.metrics.log_value(EPISODE_RETURN_MEAN, ret, window=win) + self.metrics.log_value(EPISODE_DURATION_SEC_MEAN, sec, window=win) + # Per-agent returns. + self.metrics.log_value( + ("agent_episode_returns_mean", DEFAULT_AGENT_ID), ret, window=win + ) + # Per-RLModule returns. + self.metrics.log_value( + ("module_episode_returns_mean", DEFAULT_MODULE_ID), ret, window=win + ) + + # For some metrics, log min/max as well. + self.metrics.log_value(EPISODE_LEN_MIN, length, reduce="min", window=win) + self.metrics.log_value(EPISODE_RETURN_MIN, ret, reduce="min", window=win) + self.metrics.log_value(EPISODE_LEN_MAX, length, reduce="max", window=win) + self.metrics.log_value(EPISODE_RETURN_MAX, ret, reduce="max", window=win) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/rllink.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/rllink.py new file mode 100644 index 0000000000000000000000000000000000000000..dfb72bda97b61e978c16a92c384f72c674099a6c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/rllink.py @@ -0,0 +1,109 @@ +from enum import Enum +from packaging.version import Version + +from ray.rllib.utils.checkpoints import try_import_msgpack +from ray.util.annotations import DeveloperAPI + + +msgpack = None + + +@DeveloperAPI +class RLlink(Enum): + PROTOCOL_VERSION = Version("0.0.1") + + # Requests: Client (external env) -> Server (RLlib). + # ---- + # Ping command (initial handshake). + PING = "PING" + # List of episodes (similar to what an EnvRunner.sample() call would return). + EPISODES = "EPISODES" + # Request state (e.g. model weights). + GET_STATE = "GET_STATE" + # Request Algorithm config. + GET_CONFIG = "GET_CONFIG" + # Send episodes and request the next state update right after that. + # Clients sending this message should wait for a SET_STATE message as an immediate + # response. Useful for external samplers that must collect on-policy data. + EPISODES_AND_GET_STATE = "EPISODES_AND_GET_STATE" + + # Responses: Server (RLlib) -> Client (external env). + # ---- + # Pong response (initial handshake). + PONG = "PONG" + # Set state (e.g. model weights). + SET_STATE = "SET_STATE" + # Set Algorithm config. + SET_CONFIG = "SET_CONFIG" + + # @OldAPIStack (to be deprecated soon). + ACTION_SPACE = "ACTION_SPACE" + OBSERVATION_SPACE = "OBSERVATION_SPACE" + GET_WORKER_ARGS = "GET_WORKER_ARGS" + GET_WEIGHTS = "GET_WEIGHTS" + REPORT_SAMPLES = "REPORT_SAMPLES" + START_EPISODE = "START_EPISODE" + GET_ACTION = "GET_ACTION" + LOG_ACTION = "LOG_ACTION" + LOG_RETURNS = "LOG_RETURNS" + END_EPISODE = "END_EPISODE" + + def __str__(self): + return self.name + + +@DeveloperAPI +def send_rllink_message(sock_, message: dict): + """Sends a message to the client with a length header.""" + global msgpack + if msgpack is None: + msgpack = try_import_msgpack(error=True) + + body = msgpack.packb(message, use_bin_type=True) # .encode("utf-8") + header = str(len(body)).zfill(8).encode("utf-8") + try: + sock_.sendall(header + body) + except Exception as e: + raise ConnectionError( + f"Error sending message {message} to server on socket {sock_}! " + f"Original error was: {e}" + ) + + +@DeveloperAPI +def get_rllink_message(sock_): + """Receives a message from the client following the length-header protocol.""" + global msgpack + if msgpack is None: + msgpack = try_import_msgpack(error=True) + + try: + # Read the length header (8 bytes) + header = _get_num_bytes(sock_, 8) + msg_length = int(header.decode("utf-8")) + # Read the message body + body = _get_num_bytes(sock_, msg_length) + # Decode JSON. + message = msgpack.unpackb(body, raw=False) # .loads(body.decode("utf-8")) + # Check for proper protocol. + if "type" not in message: + raise ConnectionError( + "Protocol Error! Message from peer does not contain `type` field." + ) + return RLlink(message.pop("type")), message + except Exception as e: + raise ConnectionError( + f"Error receiving message from peer on socket {sock_}! " + f"Original error was: {e}" + ) + + +def _get_num_bytes(sock_, num_bytes): + """Helper function to receive a specific number of bytes.""" + data = b"" + while len(data) < num_bytes: + packet = sock_.recv(num_bytes - len(data)) + if not packet: + raise ConnectionError(f"No data received from socket {sock_}!") + data += packet + return data diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..09dfbe227e5a6c29bdfa7096758d529ddcb72d55 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__init__.py @@ -0,0 +1,124 @@ +import logging +from typing import Type, Union + +import gymnasium as gym + +from ray.rllib.env.env_context import EnvContext +from ray.rllib.utils.error import ( + ERR_MSG_INVALID_ENV_DESCRIPTOR, + EnvError, +) +from ray.util.annotations import PublicAPI + + +logger = logging.getLogger(__name__) + + +@PublicAPI +def try_import_pyspiel(error: bool = False): + """Tries importing pyspiel and returns the module (or None). + + Args: + error: Whether to raise an error if pyspiel cannot be imported. + + Returns: + The pyspiel module. + + Raises: + ImportError: If error=True and pyspiel is not installed. + """ + try: + import pyspiel + + return pyspiel + except ImportError: + if error: + raise ImportError( + "Could not import pyspiel! Pygame is not a dependency of RLlib " + "and RLlib requires you to install pygame separately: " + "`pip install pygame`." + ) + return None + + +@PublicAPI +def try_import_open_spiel(error: bool = False): + """Tries importing open_spiel and returns the module (or None). + + Args: + error: Whether to raise an error if open_spiel cannot be imported. + + Returns: + The open_spiel module. + + Raises: + ImportError: If error=True and open_spiel is not installed. + """ + try: + import open_spiel + + return open_spiel + except ImportError: + if error: + raise ImportError( + "Could not import open_spiel! open_spiel is not a dependency of RLlib " + "and RLlib requires you to install open_spiel separately: " + "`pip install open_spiel`." + ) + return None + + +def _gym_env_creator( + env_context: EnvContext, + env_descriptor: Union[str, Type[gym.Env]], +) -> gym.Env: + """Tries to create a gym env given an EnvContext object and descriptor. + + Note: This function tries to construct the env from a string descriptor + only using possibly installed RL env packages (such as gym, pybullet_envs, + etc). These packages are no installation requirements for RLlib. In case + you would like to support more such env packages, add the necessary imports + and construction logic below. + + Args: + env_context: The env context object to configure the env. + Note that this is a config dict, plus the properties: + `worker_index`, `vector_index`, and `remote`. + env_descriptor: The env descriptor as a gym-registered string, e.g. CartPole-v1, + ALE/MsPacman-v5, or CartPoleContinuousBulletEnv-v0. + Alternatively, the gym.Env subclass to use. + + Returns: + The actual gym environment object. + + Raises: + gym.error.Error: If the env cannot be constructed. + """ + # Allow for PyBullet or envs to be used as well (via string). This allows + # for doing things like `env=CartPoleContinuousBulletEnv-v0`. + try: + import pybullet_envs + + pybullet_envs.getList() + except (AttributeError, ModuleNotFoundError, ImportError): + pass + + # If env descriptor is a str, starting with "ale_py:ALE/", for now, register all ALE + # envs from ale_py. + if isinstance(env_descriptor, str) and env_descriptor.startswith("ale_py:ALE/"): + import ale_py + + gym.register_envs(ale_py) + + # Try creating a gym env. If this fails we can output a + # decent error message. + try: + # If class provided, call constructor directly. + if isinstance(env_descriptor, type): + env = env_descriptor(env_context) + else: + env = gym.make(env_descriptor, **env_context) + except gym.error.Error: + raise EnvError(ERR_MSG_INVALID_ENV_DESCRIPTOR.format(env_descriptor)) + + return env diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..277e0c5f309eeace66229e41c4b3c3273fe100b9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/external_env_protocol.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/external_env_protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd730f0c091c67060520996d9127b9b6ff532269 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/external_env_protocol.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/infinite_lookback_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/infinite_lookback_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f964ef7b05660652cac7d7b82bddf545049960b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/infinite_lookback_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/external_env_protocol.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/external_env_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..7fedebedcd264d23a0c0f123575f55cf5d10e21d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/external_env_protocol.py @@ -0,0 +1,8 @@ +from ray.rllib.env.external.rllink import RLlink # noqa +from ray.rllib.utils.deprecation import deprecation_warning + +deprecation_warning( + old="ray.rllib.env.utils.external_env_protocol", + new="ray.rllib.env.external.rllink", + error=False, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..76004f0200fa390b1bdcf2ce5362f5709817db40 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py @@ -0,0 +1,721 @@ +from typing import Any, Dict, List, Optional, Union + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.utils.numpy import LARGE_INTEGER, one_hot, one_hot_multidiscrete +from ray.rllib.utils.serialization import gym_space_from_dict, gym_space_to_dict +from ray.rllib.utils.spaces.space_utils import ( + batch, + from_jsonable_if_needed, + get_dummy_batch_for_space, + get_base_struct_from_space, + to_jsonable_if_needed, +) +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class InfiniteLookbackBuffer: + @property + def space(self): + return self._space + + @space.setter + def space(self, value): + self._space = value + self.space_struct = get_base_struct_from_space(value) + + def __init__( + self, + data: Optional[Union[List, np.ndarray]] = None, + lookback: int = 0, + space: Optional[gym.Space] = None, + ): + self.data = data if data is not None else [] + self.lookback = min(lookback, len(self.data)) + self.finalized = not isinstance(self.data, list) + self.space_struct = None + self.space = space + + def __eq__( + self, + other: "InfiniteLookbackBuffer", + ) -> bool: + """Compares two `InfiniteLookbackBuffers. + + Args: + other: Another object. If another `LookbackBuffer` instance all + their attributes are compared. + + Returns: + `True`, if `other` is an `InfiniteLookbackBuffer` instance and all + attributes are identical. Otherwise, returns `False`. + """ + if isinstance(other, InfiniteLookbackBuffer): + if ( + self.data == other.data + and self.lookback == other.lookback + and self.finalized == other.finalized + and self.space_struct == other.space_struct + and self.space == other.space + ): + return True + return False + + def get_state(self) -> Dict[str, Any]: + """Returns the pickable state of a buffer. + + The data in the buffer is stored into a dictionary. Note that + buffers can also be generated from pickable states (see + `InfiniteLookbackBuffer.from_state`) + + Returns: + A dict containing all the data and metadata from the buffer. + """ + return { + "data": to_jsonable_if_needed(self.data, self.space) + if self.space + else self.data, + "lookback": self.lookback, + "finalized": self.finalized, + "space": gym_space_to_dict(self.space) if self.space else self.space, + } + + @staticmethod + def from_state(state: Dict[str, Any]) -> None: + """Creates a new `InfiniteLookbackBuffer` from a state dict. + + Args: + state: The state dict, as returned by `self.get_state`. + + Returns: + A new `InfiniteLookbackBuffer` instance with the data and metadata + from the state dict. + """ + buffer = InfiniteLookbackBuffer() + buffer.lookback = state["lookback"] + buffer.finalized = state["finalized"] + buffer.space = gym_space_from_dict(state["space"]) if state["space"] else None + buffer.space_struct = ( + get_base_struct_from_space(buffer.space) if buffer.space else None + ) + buffer.data = ( + from_jsonable_if_needed(state["data"], buffer.space) + if buffer.space + else state["data"] + ) + + return buffer + + def append(self, item) -> None: + """Appends the given item to the end of this buffer.""" + if self.finalized: + self.data = tree.map_structure( + lambda d, i: np.concatenate([d, [i]], axis=0), self.data, item + ) + else: + self.data.append(item) + + def extend(self, items) -> None: + """Appends all items in `items` to the end of this buffer.""" + if self.finalized: + # TODO (sven): When extending with a list of structs, we should + # probably rather do: `tree.map_structure(..., self.data, + # tree.map_structure(lambda *s: np.array(*s), *items)`)?? + self.data = tree.map_structure( + lambda d, i: np.concatenate([d, i], axis=0), + self.data, + # Note, we could have dictionaries here. + np.array(items) if isinstance(items, list) else items, + ) + else: + for item in items: + self.append(item) + + def concat(self, other: "InfiniteLookbackBuffer") -> None: + """Concatenates the data of `other` (w/o its lookback) to `self`. + + Args: + other: The other InfiniteLookbackBuffer to be concatenated to self. + """ + self.data.extend(other.get()) + + def pop(self, index: int = -1) -> None: + """Removes the item at `index` from this buffer, but does NOT return it. + + Args: + index: The index to pop out of this buffer (w/o returning it from this + method). + """ + if self.finalized: + self.data = tree.map_structure( + lambda s: np.delete(s, index, axis=0), self.data + ) + else: + self.data.pop(index) + + def finalize(self) -> None: + """Finalizes this buffer by converting internal data lists into numpy arrays. + + Thereby, if the individual items in the list are nested structures, the + resulting buffer content will be a nested struct of np.ndarrays (leafs). + """ + if not self.finalized: + self.data = batch(self.data) + self.finalized = True + + def get( + self, + indices: Optional[Union[int, slice, List[int]]] = None, + *, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + one_hot_discrete: bool = False, + _ignore_last_ts: bool = False, + _add_last_ts_value: Optional[Any] = None, + ) -> Any: + """Returns data, based on the given args, from this buffer. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual data stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual data in a batch of size len(indices). + A slice object is interpreted as a range of data to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, a buffer with data [4, 5, 6, 7, 8, 9], + where [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will + respond to `get(-1, neg_index_as_lookback=True)` with `6` and to + `get(slice(-2, 1), neg_index_as_lookback=True)` with `[5, 6, 7]`. + fill: An optional float value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the buffer's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, a buffer with data [10, 11, 12, 13, 14] and lookback + buffer size of 2 (meaning `10` and `11` are part of the lookback buffer) + will respond to `get(slice(-7, -2), fill=0.0)` + with `[0.0, 0.0, 10, 11, 12]`. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) space + that are Discrete or MultiDiscrete. Note that if `fill=0` and the + requested `indices` are out of the range of our data, the returned + one-hot vectors will actually be zero-hot (all slots zero). + _ignore_last_ts: Whether to ignore the last record in our internal + `self.data` when getting the provided indices. + _add_last_ts_value: Whether to add the value of this arg to the end of + the internal `self.data` buffer (just for the duration of this get + operation, not permanently). + """ + if indices is None: + data = self._get_all_data( + one_hot_discrete=one_hot_discrete, + _ignore_last_ts=_ignore_last_ts, + ) + elif isinstance(indices, slice): + data = self._get_slice( + indices, + fill=fill, + neg_index_as_lookback=neg_index_as_lookback, + one_hot_discrete=one_hot_discrete, + _ignore_last_ts=_ignore_last_ts, + _add_last_ts_value=_add_last_ts_value, + ) + elif isinstance(indices, list): + data = [ + self._get_int_index( + idx, + fill=fill, + neg_index_as_lookback=neg_index_as_lookback, + one_hot_discrete=one_hot_discrete, + _ignore_last_ts=_ignore_last_ts, + _add_last_ts_value=_add_last_ts_value, + ) + for idx in indices + ] + if self.finalized: + data = batch(data) + else: + assert isinstance(indices, int) + data = self._get_int_index( + indices, + fill=fill, + neg_index_as_lookback=neg_index_as_lookback, + one_hot_discrete=one_hot_discrete, + _ignore_last_ts=_ignore_last_ts, + _add_last_ts_value=_add_last_ts_value, + ) + + return data + + def __add__( + self, other: Union[List, "InfiniteLookbackBuffer", int, float, complex] + ) -> "InfiniteLookbackBuffer": + """Adds another InfiniteLookbackBuffer object or list to the end of this one. + + Args: + other: Another `InfiniteLookbackBuffer` or a `list` or a number. + If a `InfiniteLookbackBuffer` its data (w/o its lookback buffer) gets + concatenated to self's data. If a `list`, we concat it to self's data. + If a number, we add this number to each element of self (if possible). + + Returns: + A new `InfiniteLookbackBuffer` instance `self.data` containing + concatenated data from `self` and `other` (or adding `other` to each element + in self's data). + """ + + if self.finalized: + raise RuntimeError(f"Cannot `add` to a finalized {type(self).__name__}.") + else: + # If `other` is an int, simply add it to all our values (if possible) and + # use the result as the underlying data for the returned buffer. + if isinstance(other, (int, float, complex)): + data = [ + (d + other) if isinstance(d, (int, float, complex)) else d + for d in self.data + ] + # If `other` is a InfiniteLookbackBuffer itself, do NOT include its + # lookback buffer anymore. We assume that `other`'s lookback buffer i + # already at the end of `self`. + elif isinstance(other, InfiniteLookbackBuffer): + data = self.data + other.data[other.lookback :] + # `other` is a list, simply concat the two lists and use the result as + # the underlying data for the returned buffer. + else: + data = self.data + other + + return InfiniteLookbackBuffer( + data=data, + lookback=self.lookback, + space=self.space, + ) + + def __getitem__(self, item): + """Support squared bracket syntax, e.g. buffer[:5].""" + return self.get(item) + + def __setitem__(self, key, value): + self.set(new_data=value, at_indices=key) + + def set( + self, + new_data, + *, + at_indices: Optional[Union[int, slice, List[int]]] = None, + neg_index_as_lookback: bool = False, + ) -> None: + """Overwrites all or some of the data in this buffer with the provided data. + + Args: + new_data: The new data to overwrite existing records with. + at_indices: A single int is interpreted as an index, at which to overwrite + the individual record stored at this index with `new_data`. + A list of ints is interpreted as a list of indices, which to overwrite + with `new_data`, which must be a batch of size `len(at_indices)`. + A slice object is interpreted as a range, which to overwrite with + `new_data`. Thereby, negative indices by default are interpreted as + "before the end" unless the `neg_index_as_lookback=True` option is + used, in which case negative indices are interpreted as + "before ts=0", meaning going back into the lookback buffer. + neg_index_as_lookback: If True, negative values in `at_indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, a buffer with data [4, 5, 6, 7, 8, 9], + where [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will + handle a call `set(99, at_indices=-1, neg_index_as_lookback=True)` + with `6` being replaced by 99 and to `set([98, 99, 100], + at_indices=slice(-2, 1), neg_index_as_lookback=True)` with + `[5, 6, 7]` being replaced by `[98, 99, 100]`. + """ + # `at_indices` is None -> Override all our data (excluding the lookback buffer). + if at_indices is None: + self._set_all_data(new_data) + + elif isinstance(at_indices, slice): + self._set_slice( + new_data, + slice_=at_indices, + neg_index_as_lookback=neg_index_as_lookback, + ) + elif isinstance(at_indices, list): + for i, idx in enumerate(at_indices): + self._set_int_index( + new_data[i], + idx=idx, + neg_index_as_lookback=neg_index_as_lookback, + ) + else: + assert isinstance(at_indices, int) + self._set_int_index( + new_data, + idx=at_indices, + neg_index_as_lookback=neg_index_as_lookback, + ) + + def __len__(self): + """Return the length of our data, excluding the lookback buffer.""" + len_ = self.len_incl_lookback() + # Only count the data after the lookback. + return max(len_ - self.lookback, 0) + + def len_incl_lookback(self): + if self.finalized: + return len(tree.flatten(self.data)[0]) + else: + return len(self.data) + + def __repr__(self): + return ( + f"{type(self).__name__}({self.data[:self.lookback]} <- " + f"lookback({self.lookback}) | {self.data[self.lookback:]})" + ) + + def _get_all_data(self, one_hot_discrete=False, _ignore_last_ts=False): + data = self[: (None if not _ignore_last_ts else -1)] + if one_hot_discrete: + data = self._one_hot(data, space_struct=self.space_struct) + return data + + def _set_all_data(self, new_data): + self._set_slice(new_data, slice(0, None)) + + def _get_slice( + self, + slice_, + fill=None, + neg_index_as_lookback=False, + one_hot_discrete=False, + _ignore_last_ts=False, + _add_last_ts_value=None, + ): + data_to_use = self.data + if _ignore_last_ts: + if self.finalized: + data_to_use = tree.map_structure(lambda s: s[:-1], self.data) + else: + data_to_use = self.data[:-1] + if _add_last_ts_value is not None: + if self.finalized: + data_to_use = tree.map_structure( + lambda s, t: np.append(s, t), + data_to_use.copy(), + _add_last_ts_value, + ) + else: + data_to_use = np.append(data_to_use.copy(), _add_last_ts_value) + + slice_, slice_len, fill_left_count, fill_right_count = self._interpret_slice( + slice_, + neg_index_as_lookback, + len_self_plus_lookback=( + self.len_incl_lookback() + + int(_add_last_ts_value is not None) + - int(_ignore_last_ts) + ), + ) + + # Perform the actual slice. + data_slice = None + if slice_len > 0: + if self.finalized: + data_slice = tree.map_structure(lambda s: s[slice_], data_to_use) + else: + data_slice = data_to_use[slice_] + + if one_hot_discrete: + data_slice = self._one_hot(data_slice, space_struct=self.space_struct) + + # Data is shorter than the range requested -> Fill the rest with `fill` data. + if fill is not None and (fill_right_count > 0 or fill_left_count > 0): + if self.finalized: + if fill_left_count: + if self.space is None: + fill_batch = np.array([fill] * fill_left_count) + else: + fill_batch = get_dummy_batch_for_space( + self.space, + fill_value=fill, + batch_size=fill_left_count, + one_hot_discrete=one_hot_discrete, + ) + if data_slice is not None: + data_slice = tree.map_structure( + lambda s0, s: np.concatenate([s0, s]), + fill_batch, + data_slice, + ) + else: + data_slice = fill_batch + if fill_right_count: + if self.space is None: + fill_batch = np.array([fill] * fill_right_count) + else: + fill_batch = get_dummy_batch_for_space( + self.space, + fill_value=fill, + batch_size=fill_right_count, + one_hot_discrete=one_hot_discrete, + ) + if data_slice is not None: + data_slice = tree.map_structure( + lambda s0, s: np.concatenate([s, s0]), + fill_batch, + data_slice, + ) + else: + data_slice = fill_batch + + else: + if self.space is None: + fill_batch = [fill] + else: + fill_batch = [ + get_dummy_batch_for_space( + self.space, + fill_value=fill, + batch_size=0, + one_hot_discrete=one_hot_discrete, + ) + ] + data_slice = ( + fill_batch * fill_left_count + + (data_slice if data_slice is not None else []) + + fill_batch * fill_right_count + ) + + if data_slice is None: + if self.finalized: + return tree.map_structure(lambda s: s[slice_], data_to_use) + else: + return data_to_use[slice_] + return data_slice + + def _set_slice( + self, + new_data, + slice_, + neg_index_as_lookback=False, + ): + slice_, _, _, _ = self._interpret_slice(slice_, neg_index_as_lookback) + + # Check, whether the setting to new_data changes the length of self + # (it shouldn't). If it does, raise an error. + try: + if self.finalized: + + def __set(s, n): + if self.space: + assert self.space.contains(n[0]) + assert len(s[slice_]) == len(n) + s[slice_] = n + + tree.map_structure(__set, self.data, new_data) + else: + assert len(self.data[slice_]) == len(new_data) + self.data[slice_] = new_data + except AssertionError: + raise IndexError( + f"Cannot `set()` value via at_indices={slice_} (option " + f"neg_index_as_lookback={neg_index_as_lookback})! Slice of data " + "does NOT have the same size as `new_data`." + ) + + def _get_int_index( + self, + idx: int, + fill=None, + neg_index_as_lookback=False, + one_hot_discrete=False, + _ignore_last_ts=False, + _add_last_ts_value=None, + ): + data_to_use = self.data + if _ignore_last_ts: + if self.finalized: + data_to_use = tree.map_structure(lambda s: s[:-1], self.data) + else: + data_to_use = self.data[:-1] + if _add_last_ts_value is not None: + if self.finalized: + data_to_use = tree.map_structure( + lambda s, last: np.append(s, last), data_to_use, _add_last_ts_value + ) + else: + data_to_use = data_to_use.copy() + data_to_use.append(_add_last_ts_value) + + # If index >= 0 -> Ignore lookback buffer. + # Otherwise, include lookback buffer. + if idx >= 0 or neg_index_as_lookback: + idx = self.lookback + idx + # Negative indices mean: Go to left into lookback buffer starting from idx=0. + # But if we pass the lookback buffer, the index should be invalid and we will + # have to fill, if required. Invalidate the index by setting it to one larger + # than max. + if neg_index_as_lookback and idx < 0: + idx = len(self) + self.lookback - (_ignore_last_ts is True) + + try: + if self.finalized: + data = tree.map_structure(lambda s: s[idx], data_to_use) + else: + data = data_to_use[idx] + # Out of range index -> If `fill`, use a fill dummy (B=0), if not, error out. + except IndexError as e: + if fill is not None: + if self.space is None: + return fill + return get_dummy_batch_for_space( + self.space, + fill_value=fill, + batch_size=0, + one_hot_discrete=one_hot_discrete, + ) + else: + raise e + + # Convert discrete/multi-discrete components to one-hot vectors, if required. + if one_hot_discrete: + data = self._one_hot(data, self.space_struct) + return data + + def _set_int_index(self, new_data, idx, neg_index_as_lookback): + actual_idx = idx + # If index >= 0 -> Ignore lookback buffer. + # Otherwise, include lookback buffer. + if actual_idx >= 0 or neg_index_as_lookback: + actual_idx = self.lookback + actual_idx + # Negative indices mean: Go to left into lookback buffer starting from idx=0. + # But if we pass the lookback buffer, the index should be invalid and we will + # have to fill, if required. Invalidate the index by setting it to one larger + # than max. + if neg_index_as_lookback and actual_idx < 0: + actual_idx = len(self) + self.lookback + + try: + if self.finalized: + + def __set(s, n): + if self.space: + assert self.space.contains(n), n + s[actual_idx] = n + + tree.map_structure(__set, self.data, new_data) + else: + self.data[actual_idx] = new_data + except IndexError: + raise IndexError( + f"Cannot `set()` value at index {idx} (option " + f"neg_index_as_lookback={neg_index_as_lookback})! Out of range " + f"of buffer data." + ) + + def _interpret_slice( + self, + slice_, + neg_index_as_lookback, + len_self_plus_lookback=None, + ): + if len_self_plus_lookback is None: + len_self_plus_lookback = len(self) + self.lookback + + # Re-interpret slice bounds as absolute positions (>=0) within our + # internal data. + start = slice_.start + stop = slice_.stop + + # Start is None -> Exclude lookback buffer. + if start is None: + start = self.lookback + # Start is negative. + elif start < 0: + # `neg_index_as_lookback=True` -> User wants to index into the lookback + # range. + if neg_index_as_lookback: + start = self.lookback + start + # Interpret index as counting "from end". + else: + start = len_self_plus_lookback + start + # Start is 0 or positive -> timestep right after lookback is interpreted as 0. + else: + start = self.lookback + start + + # Stop is None -> Set stop to very last index + 1 of our internal data. + if stop is None: + stop = len_self_plus_lookback + # Stop is negative. + elif stop < 0: + # `neg_index_as_lookback=True` -> User wants to index into the lookback + # range. Set to 0 (beginning of lookback buffer) if result is a negative + # index. + if neg_index_as_lookback: + stop = self.lookback + stop + # Interpret index as counting "from end". Set to 0 (beginning of actual + # episode) if result is a negative index. + else: + stop = len_self_plus_lookback + stop + # Stop is positive -> Add lookback range to it. + else: + stop = self.lookback + stop + + fill_left_count = fill_right_count = 0 + # Both start and stop are on left side. + if start < 0 and stop < 0: + fill_left_count = abs(start - stop) + fill_right_count = 0 + start = stop = 0 + # Both start and stop are on right side. + elif start >= len_self_plus_lookback and stop >= len_self_plus_lookback: + fill_right_count = abs(start - stop) + fill_left_count = 0 + start = stop = len_self_plus_lookback + # Set to 0 (beginning of actual episode) if result is a negative index. + elif start < 0: + fill_left_count = -start + start = 0 + elif stop >= len_self_plus_lookback: + fill_right_count = stop - len_self_plus_lookback + stop = len_self_plus_lookback + # Only `stop` might be < 0, when slice has negative step and start is > 0. + elif stop < 0: + if start >= len_self_plus_lookback: + fill_left_count = start - len_self_plus_lookback + 1 + start = len_self_plus_lookback - 1 + fill_right_count = -stop - 1 + stop = -LARGE_INTEGER + + assert start >= 0 and (stop >= 0 or stop == -LARGE_INTEGER), (start, stop) + + step = slice_.step if slice_.step is not None else 1 + slice_ = slice(start, stop, step) + slice_len = max(0, (stop - start + (step - (1 if step > 0 else -1))) // step) + return slice_, slice_len, fill_left_count, fill_right_count + + def _one_hot(self, data, space_struct): + if space_struct is None: + raise ValueError( + f"Cannot `one_hot` data in `{type(self).__name__}` if a " + "gym.Space was NOT provided during construction!" + ) + + def _convert(dat_, space): + if isinstance(space, gym.spaces.Discrete): + return one_hot(dat_, depth=space.n) + elif isinstance(space, gym.spaces.MultiDiscrete): + return one_hot_multidiscrete(dat_, depths=space.nvec) + return dat_ + + if isinstance(data, list): + data = [ + tree.map_structure(_convert, dslice, space_struct) for dslice in data + ] + else: + data = tree.map_structure(_convert, data, space_struct) + return data diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3de974795514f5807c6c54b5a82beaeb918a7ee5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/registration.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/registration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd59906503a2ed410c643320084b0921cf0109ec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/registration.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/sync_vector_multi_agent_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/sync_vector_multi_agent_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57330f2b62550eb5f902d2f73d6c2df8783fd4f1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/sync_vector_multi_agent_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/vector_multi_agent_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/vector_multi_agent_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d7ff0c875a8fcb978d70c8b8f8eb623966467ac Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/vector_multi_agent_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/registration.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/registration.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d4a4f59886076204966b1c278ea779d3f610fd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/registration.py @@ -0,0 +1,91 @@ +import copy +import gymnasium as gym +import logging + +from gymnasium.envs.registration import VectorizeMode +from typing import Any, Dict, Optional + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.env.vector.sync_vector_multi_agent_env import SyncVectorMultiAgentEnv +from ray.rllib.env.vector.vector_multi_agent_env import VectorMultiAgentEnv + +logger = logging.getLogger(__file__) + + +def make_vec( + id: str, + num_envs: int = 1, + vectorization_mode: Optional[VectorizeMode] = None, + vector_kwargs: Optional[Dict[str, Any]] = None, + # TODO (simon): Add wrappers? + **kwargs, +) -> VectorMultiAgentEnv: + + if vector_kwargs is None: + vector_kwargs = {} + + if vectorization_mode is None: + vectorization_mode = "sync" + + # Create an `gymnasium.envs.registration.EnvSpec` to properly + # initialize the sub-environments. + if isinstance(id, gym.envs.registration.EnvSpec): + env_spec = id + elif isinstance(id, str): + env_spec = gym.envs.registration._find_spec(id) + else: + raise ValueError(f"Invalid id type: {type(id)}. Expected `str` or `EnvSpec`.") + + env_spec = copy.deepcopy(env_spec) + env_spec_kwargs = env_spec.kwargs + env_spec.kwargs = dict() + + num_envs = env_spec.kwargs.get("num_envs", num_envs) + vectorization_mode = env_spec_kwargs.pop("vectorization_mode", vectorization_mode) + vector_kwargs = env_spec_kwargs.pop("vector_kwargs", vector_kwargs) + env_spec_kwargs.update(kwargs) + + # Specify the vectorization mode. + if vectorization_mode is None: + vectorization_mode = VectorizeMode.SYNC + else: + try: + vectorization_mode = VectorizeMode(vectorization_mode) + except ValueError: + raise ValueError( + f"Invalid vectorization mode: {vectorization_mode!r}, " + f"valid modes: {[mode.value for mode in VectorizeMode]}." + ) + assert isinstance(vectorization_mode, VectorizeMode) + + def create_single_env() -> MultiAgentEnv: + single_env = gym.make(env_spec, **env_spec_kwargs.copy()) + + return single_env + + # Check, the vectorization mode. + if vectorization_mode == VectorizeMode.SYNC: + # Create the synchronized vector environemnt. + env = SyncVectorMultiAgentEnv( + env_fns=(create_single_env for _ in range(num_envs)), + **vector_kwargs, + ) + # Other modes are not implemented, yet. + else: + raise ValueError( + "For `MultiAgentEnv` only synchronous environment vectorization " + "is implemented. Use `gym_env_vectorize_mode='sync'`." + ) + + # Add all creation specifications to the environment. + copied_id_spec = copy.deepcopy(env_spec) + copied_id_spec.kwargs = env_spec_kwargs.copy() + if num_envs != 1: + copied_id_spec.kwargs["num_envs"] = num_envs + copied_id_spec.kwargs["vectorization_mode"] = vectorization_mode.value + if len(vector_kwargs) > 0: + copied_id_spec.kwargs["vector_kwargs"] = vector_kwargs + env.unwrapped.spec = copied_id_spec + + # Return the `VectorMultiAgentEnv`. + return env diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/sync_vector_multi_agent_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/sync_vector_multi_agent_env.py new file mode 100644 index 0000000000000000000000000000000000000000..d1133ebf0d94cdbdca86e7c5f66d660635dcc554 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/sync_vector_multi_agent_env.py @@ -0,0 +1,215 @@ +import gymnasium as gym +import numpy as np + +from copy import deepcopy +from gymnasium.core import ActType, RenderFrame +from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.env.vector.vector_multi_agent_env import ArrayType, VectorMultiAgentEnv +from ray.rllib.utils.typing import AgentID + + +class SyncVectorMultiAgentEnv(VectorMultiAgentEnv): + def __init__( + self, + env_fns: Union[ + Iterator[Callable[[], MultiAgentEnv]], Sequence[Callable[[], MultiAgentEnv]] + ], + copy: bool = True, + autoreset_mode: str = "next_step", + ): + super().__init__() + + self.env_fns = env_fns + self.copy = copy + self.autoreset_mode = autoreset_mode + + # Initialize all sub-environments. + self.envs = [env_fn() for env_fn in self.env_fns] + + self.num_envs = len(self.envs) + self.metadata = self.envs[0].metadata + self.metadata["autoreset_mode"] = self.autoreset_mode + self.render_mode = self.envs[0].render_mode + + if self.envs[0].unwrapped.observation_spaces is not None: + self.single_observation_spaces = self.envs[0].unwrapped.observation_spaces + elif self.envs[0].unwrapped.observation_space is not None: + self.single_observation_spaces = dict( + self.envs[0].unwrapped.observation_space + ) + else: + self.single_observation_spaces = { + aid: self.envs[0].unwrapped.get_observation_space(aid) + for aid in self.envs[0].unwrapped.possible_agents + } + self.single_observation_space = gym.spaces.Dict(self.single_observation_spaces) + + if self.envs[0].unwrapped.action_spaces is not None: + self.single_action_spaces = self.envs[0].unwrapped.action_spaces + elif self.envs[0].unwrapped.action_space is not None: + self.single_action_spaces = dict(self.envs[0].unwrapped.action_space) + else: + self.single_action_spaces = { + aid: self.envs[0].unwrapped.get_action_space(aid) + for aid in self.envs[0].unwrapped.possible_agents + } + self.single_action_space = gym.spaces.Dict(self.single_action_spaces) + + # TODO (simon): Decide if we want to include a spaces check here. + + # Note, if `single_observation_spaces` are not defined, this will + # raise an error. + self._observations = self.create_empty_array( + self.single_observation_spaces, + n=self.num_envs, + ) + self._rewards = [{} for _ in range(self.num_envs)] + self._terminations = [{} for _ in range(self.num_envs)] + self._truncations = [{} for _ in range(self.num_envs)] + self._infos = [{} for _ in range(self.num_envs)] + + def reset( + self, *, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None + ) -> Tuple[ArrayType, ArrayType]: + + # Check the `seed`. + if seed is None: + seed = [None for _ in range(self.num_envs)] + elif isinstance(seed, int): + seed = [seed + i for i in range(self.num_envs)] + # If `seed` is a sequence, check if length is correct. + else: + assert len(seed) == self.num_envs, ( + f"If seeds are passed as a list the length must match num_envs={self.num_envs} " + f"but got length={len(seed)}.", + ) + + # Set auto-reset to `False` for all sub-environments. This will be + # set to `True` during `VectorMultiAgentEnv.step`. + self._autoreset_envs = np.zeros((self.num_envs,), dtype=np.bool_) + + # Force reset on all sub-environments. + for i, (env, single_seed) in enumerate(zip(self.envs, seed)): + self._observations[i], self._infos[i] = env.reset( + seed=single_seed, options=options + ) + + return ( + deepcopy(self._observations) if self.copy else self._observations, + self._infos, + ) + + def step( + self, actions: List[Dict[AgentID, ActType]] + ) -> Tuple[ArrayType, ArrayType, ArrayType, ArrayType, ArrayType]: + + for i, action in enumerate(actions): + # Note, this will be a feature coming in `gymnasium`s next release. + if self.autoreset_mode == "next_step": + # Auto-reset environments that terminated or truncated. + if self._autoreset_envs[i]: + self._observations[i], self._infos[i] = self.envs[i].reset() + + self._rewards[i] = { + aid: 0.0 for aid in self.envs[i].unwrapped.possible_agents + } + self._terminations[i] = { + aid: False for aid in self.envs[i].unwrapped.possible_agents + } + self._truncations[i] = { + aid: False for aid in self.envs[i].unwrapped.possible_agents + } + # Note, this needs to be added for `MultiAgentEpisode`s to work. + self._terminations[i].update({"__all__": False}) + self._truncations[i].update({"__all__": False}) + # Otherwise make a regular step. + else: + ( + self._observations[i], + self._rewards[i], + self._terminations[i], + self._truncations[i], + self._infos[i], + ) = self.envs[i].step(action) + # Other autoreset modes are not implemented, yet. + else: + raise ValueError(f"Unexpected autoreset mode: {self.autoreset_mode}") + + # Is any sub-environment terminated or truncated? + self._autoreset_envs = np.logical_or( + np.array([t["__all__"] for t in self._terminations]), + # Note, some environments just return `terminated`. + np.array([t.get("__all__", False) for t in self._truncations]), + ) + + return ( + deepcopy(self._observations) if self.copy else self._observations, + np.copy(self._rewards), + np.copy(self._terminations), + np.copy(self._truncations), + np.copy(self._infos), + ) + + def render(self) -> Optional[Tuple[RenderFrame, ...]]: + """Returns the rendered frames from all environments.""" + return tuple(env.render() for env in self.envs) + + def call(self, name: str, *args: Any, **kwargs: Any) -> tuple[Any, ...]: + """Calls a sub-environment method with name and applies args and kwargs. + + Args: + name: The method name + *args: The method args + **kwargs: The method kwargs + + Returns: + Tuple of results + """ + results = [] + for env in self.envs: + function = env.get_wrapper_attr(name) + + if callable(function): + results.append(function(*args, **kwargs)) + else: + results.append(function) + + return tuple(results) + + def get_attr(self, name: str) -> tuple[Any, ...]: + """Get a property from each parallel environment. + + Args: + name: Name of the property to get from each individual environment. + + Returns: + The property with name + """ + return self.call(name) + + def close_extras(self, **kwargs): + """Close all environments.""" + if hasattr(self, "envs"): + [env.close() for env in self.envs] + + @property + def np_random_seed(self) -> Tuple[int, ...]: + """Returns a tuple of random seeds for the wrapped envs.""" + return self.get_attr("np_random_seed") + + @property + def np_random(self) -> Tuple[np.random.Generator, ...]: + """Returns a tuple of numpy random generators for the wrapped envs.""" + return self.get_attr("np_random") + + # TODO (simon): Move to space_utils. + def create_empty_array( + self, space: Dict[str, gym.Space], n: int = 1 + ) -> List[Dict[str, gym.Space]]: + + return [ + {aid: agent_space.sample() for aid, agent_space in space.items()} + for _ in range(n) + ] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/vector_multi_agent_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/vector_multi_agent_env.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b22d12dafcec5574c1838cf20c3cb0ac45a6d5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/vector_multi_agent_env.py @@ -0,0 +1,88 @@ +from typing import Any, Dict, List, Optional, Tuple, TypeVar + +import gymnasium as gym +from gymnasium.core import RenderFrame +from gymnasium.envs.registration import EnvSpec +from gymnasium.utils import seeding +import numpy as np + + +ArrayType = TypeVar("ArrayType") + + +class VectorMultiAgentEnv: + + metadata: Dict[str, Any] = {} + spec: Optional[EnvSpec] = None + render_mode: Optional[str] = None + closed: bool = False + + envs: Optional[List] = None + + # TODO (simon, sven): We could think about enabling here different + # spaces for different envs (e.g. different high/lows). In this + # case we would need here actually "batched" spaces and not a + # single on that holds for all sub-envs. + single_observation_spaces: Optional[Dict[str, gym.Space]] = None + single_action_spaces: Optional[Dict[str, gym.Space]] = None + # Note, the proper `gym` spaces are needed for the connector pipeline. + single_observation_space: Optional[gym.spaces.Dict] = None + single_action_space: Optional[gym.spaces.Dict] = None + + num_envs: int + + _np_random: Optional[np.random.Generator] = None + _np_random_seed: Optional[int] = None + + # @OldAPIStack, use `observation_spaces` and `action_spaces`, instead. + observation_space: Optional[gym.Space] = None + action_space: Optional[gym.Space] = None + + # TODO (simon): Add docstrings, when final design is clear. + def reset( + self, *, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None + ) -> Tuple[ArrayType, ArrayType]: + # Set random generators with the provided seeds. + if seed is not None: + self._np_random, self._np_random_seed = seeding.np_random(seed) + + def step( + self, actions: ArrayType + ) -> Tuple[ArrayType, ArrayType, ArrayType, ArrayType, ArrayType]: + raise NotImplementedError(f"{self.__str__()} step function is not implemented.") + + def render(self) -> Optional[Tuple[RenderFrame, ...]]: + raise NotImplementedError( + f"{self.__str__()} render function is not implemented." + ) + + def close(self, **kwargs: Any): + + # If already closed, there is nothing more to do. + if self.closed: + return + + # Otherwise close environments gracefully. + self.close_extras(**kwargs) + self.closed = True + + def close_extras(self, **kwargs: Any): + # Users must not implement this. + pass + + @property + def unwrapped(self): + return self + + def __del__(self): + # Close environemnts, if necessary when deleting instances. + if not getattr(self, "closed", True): + self.close() + + def __repr__(self): + if self.spec is None: + return f"{self.__class__.__name__}(num_envs={self.num_envs})" + else: + return ( + f"{self.__class__.__name__}({self.spec.id}, num_envs={self.num_envs})" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a63bdcbc91104c569185e1b78be9586d5cdac7fb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/atari_wrappers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/atari_wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bc3575cbc4f583be7ae732193a6ef7877d81f52 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/atari_wrappers.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_control_wrapper.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_control_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c43bf7da451b67b6c33140e6cb550524fe6dac0b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_control_wrapper.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_env_wrapper.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_env_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12cd6fe8ff3e39abc95362e0846149cc02071735 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_env_wrapper.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/group_agents_wrapper.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/group_agents_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f29acc865f8a8e2c6446f3293d8e6d70b1c62f66 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/group_agents_wrapper.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/multi_agent_env_compatibility.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/multi_agent_env_compatibility.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75445c7fae2a61069444f0c6aeda9c313d85e13c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/multi_agent_env_compatibility.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/open_spiel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/open_spiel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5867aa412abf35a377b5255798bd97629c84a7fe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/open_spiel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/pettingzoo_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/pettingzoo_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34de9c7bdb70866eedeec09f27eaaa960ef8ea74 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/pettingzoo_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/unity3d_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/unity3d_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebf4450bf1335a50301339e34e1c8f679d3efed8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/unity3d_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/atari_wrappers.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/atari_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..018b93564165f8debaf8410f83a13a477de2f5ac --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/atari_wrappers.py @@ -0,0 +1,411 @@ +from collections import deque +import gymnasium as gym +from gymnasium import spaces +import numpy as np +from typing import Optional, Union + +from ray.rllib.utils.annotations import PublicAPI +from ray.rllib.utils.images import rgb2gray, resize + + +@PublicAPI +def is_atari(env: Union[gym.Env, str]) -> bool: + """Returns, whether a given env object or env descriptor (str) is an Atari env. + + Args: + env: The gym.Env object or a string descriptor of the env (for example, + "ale_py:ALE/Pong-v5"). + + Returns: + Whether `env` is an Atari environment. + """ + # If a gym.Env, check proper spaces as well as occurrence of the "Atari 0: + # for Qbert sometimes we stay in lives == 0 condtion for a few fr + # so its important to keep lives > 0, so that we only reset once + # the environment advertises `terminated`. + terminated = True + self.lives = lives + return obs, reward, terminated, truncated, info + + def reset(self, **kwargs): + """Reset only when lives are exhausted. + This way all states are still reachable even though lives are episodic, + and the learner need not know about any of this behind-the-scenes. + """ + if self.was_real_terminated: + obs, info = self.env.reset(**kwargs) + else: + # no-op step to advance from terminal/lost life state + obs, _, _, _, info = self.env.step(0) + self.lives = self.env.unwrapped.ale.lives() + return obs, info + + +@PublicAPI +class FireResetEnv(gym.Wrapper): + def __init__(self, env): + """Take action on reset. + + For environments that are fixed until firing.""" + gym.Wrapper.__init__(self, env) + assert env.unwrapped.get_action_meanings()[1] == "FIRE" + assert len(env.unwrapped.get_action_meanings()) >= 3 + + def reset(self, **kwargs): + self.env.reset(**kwargs) + obs, _, terminated, truncated, _ = self.env.step(1) + if terminated or truncated: + self.env.reset(**kwargs) + obs, _, terminated, truncated, info = self.env.step(2) + if terminated or truncated: + self.env.reset(**kwargs) + return obs, info + + def step(self, ac): + return self.env.step(ac) + + +@PublicAPI +class FrameStack(gym.Wrapper): + def __init__(self, env, k): + """Stack k last frames.""" + gym.Wrapper.__init__(self, env) + self.k = k + self.frames = deque([], maxlen=k) + shp = env.observation_space.shape + self.observation_space = spaces.Box( + low=np.repeat(env.observation_space.low, repeats=k, axis=-1), + high=np.repeat(env.observation_space.high, repeats=k, axis=-1), + shape=(shp[0], shp[1], shp[2] * k), + dtype=env.observation_space.dtype, + ) + + def reset(self, *, seed=None, options=None): + ob, infos = self.env.reset(seed=seed, options=options) + for _ in range(self.k): + self.frames.append(ob) + return self._get_ob(), infos + + def step(self, action): + ob, reward, terminated, truncated, info = self.env.step(action) + self.frames.append(ob) + return self._get_ob(), reward, terminated, truncated, info + + def _get_ob(self): + assert len(self.frames) == self.k + return np.concatenate(self.frames, axis=2) + + +@PublicAPI +class FrameStackTrajectoryView(gym.ObservationWrapper): + def __init__(self, env): + """No stacking. Trajectory View API takes care of this.""" + gym.Wrapper.__init__(self, env) + shp = env.observation_space.shape + assert shp[2] == 1 + self.observation_space = spaces.Box( + low=0, high=255, shape=(shp[0], shp[1]), dtype=env.observation_space.dtype + ) + + def observation(self, observation): + return np.squeeze(observation, axis=-1) + + +@PublicAPI +class MaxAndSkipEnv(gym.Wrapper): + def __init__(self, env, skip=4): + """Return only every `skip`-th frame""" + gym.Wrapper.__init__(self, env) + # most recent raw observations (for max pooling across time steps) + self._obs_buffer = np.zeros( + (2,) + env.observation_space.shape, dtype=env.observation_space.dtype + ) + self._skip = skip + + def step(self, action): + """Repeat action, sum reward, and max over last observations.""" + total_reward = 0.0 + terminated = truncated = info = None + for i in range(self._skip): + obs, reward, terminated, truncated, info = self.env.step(action) + if i == self._skip - 2: + self._obs_buffer[0] = obs + if i == self._skip - 1: + self._obs_buffer[1] = obs + total_reward += reward + if terminated or truncated: + break + # Note that the observation on the terminated|truncated=True frame + # doesn't matter + max_frame = self._obs_buffer.max(axis=0) + + return max_frame, total_reward, terminated, truncated, info + + def reset(self, **kwargs): + return self.env.reset(**kwargs) + + +@PublicAPI +class MonitorEnv(gym.Wrapper): + def __init__(self, env=None): + """Record episodes stats prior to EpisodicLifeEnv, etc.""" + gym.Wrapper.__init__(self, env) + self._current_reward = None + self._num_steps = None + self._total_steps = None + self._episode_rewards = [] + self._episode_lengths = [] + self._num_episodes = 0 + self._num_returned = 0 + + def reset(self, **kwargs): + obs, info = self.env.reset(**kwargs) + + if self._total_steps is None: + self._total_steps = sum(self._episode_lengths) + + if self._current_reward is not None: + self._episode_rewards.append(self._current_reward) + self._episode_lengths.append(self._num_steps) + self._num_episodes += 1 + + self._current_reward = 0 + self._num_steps = 0 + + return obs, info + + def step(self, action): + obs, rew, terminated, truncated, info = self.env.step(action) + self._current_reward += rew + self._num_steps += 1 + self._total_steps += 1 + return obs, rew, terminated, truncated, info + + def get_episode_rewards(self): + return self._episode_rewards + + def get_episode_lengths(self): + return self._episode_lengths + + def get_total_steps(self): + return self._total_steps + + def next_episode_results(self): + for i in range(self._num_returned, len(self._episode_rewards)): + yield (self._episode_rewards[i], self._episode_lengths[i]) + self._num_returned = len(self._episode_rewards) + + +@PublicAPI +class NoopResetEnv(gym.Wrapper): + def __init__(self, env, noop_max=30): + """Sample initial states by taking random number of no-ops on reset. + No-op is assumed to be action 0. + """ + gym.Wrapper.__init__(self, env) + self.noop_max = noop_max + self.override_num_noops = None + self.noop_action = 0 + assert env.unwrapped.get_action_meanings()[0] == "NOOP" + + def reset(self, **kwargs): + """Do no-op action for a number of steps in [1, noop_max].""" + self.env.reset(**kwargs) + if self.override_num_noops is not None: + noops = self.override_num_noops + else: + # This environment now uses the pcg64 random number generator which + # does not have `randint` as an attribute only has `integers`. + try: + noops = self.unwrapped.np_random.integers(1, self.noop_max + 1) + # Also still support older versions. + except AttributeError: + noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) + assert noops > 0 + obs = None + for _ in range(noops): + obs, _, terminated, truncated, info = self.env.step(self.noop_action) + if terminated or truncated: + obs, info = self.env.reset(**kwargs) + return obs, info + + def step(self, ac): + return self.env.step(ac) + + +@PublicAPI +class NormalizedImageEnv(gym.ObservationWrapper): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.observation_space = gym.spaces.Box( + -1.0, + 1.0, + shape=self.observation_space.shape, + dtype=np.float32, + ) + + # Divide by scale and center around 0.0, such that observations are in the range + # of -1.0 and 1.0. + def observation(self, observation): + return (observation.astype(np.float32) / 128.0) - 1.0 + + +@PublicAPI +class GrayScaleAndResize(gym.ObservationWrapper): + def __init__(self, env, dim, grayscale: bool = True): + """Warp frames to the specified size (dim x dim).""" + gym.ObservationWrapper.__init__(self, env) + self.width = dim + self.height = dim + self.grayscale = grayscale + self.observation_space = spaces.Box( + low=0, + high=255, + shape=(self.height, self.width, 1 if grayscale else 3), + dtype=np.uint8, + ) + + def observation(self, frame): + if self.grayscale: + frame = rgb2gray(frame) + frame = resize(frame, height=self.height, width=self.width) + return frame[:, :, None] + else: + return resize(frame, height=self.height, width=self.width) + + +WarpFrame = GrayScaleAndResize + + +@PublicAPI +def wrap_atari_for_new_api_stack( + env: gym.Env, + dim: int = 64, + frameskip: int = 4, + framestack: Optional[int] = None, + grayscale: bool = True, + # TODO (sven): Add option to NOT grayscale, in which case framestack must be None + # (b/c we are using the 3 color channels already as stacking frames). +) -> gym.Env: + """Wraps `env` for new-API-stack-friendly RLlib Atari experiments. + + Note that we assume reward clipping is done outside the wrapper. + + Args: + env: The env object to wrap. + dim: Dimension to resize observations to (dim x dim). + frameskip: Whether to skip n frames and max over them (keep brightest pixels). + framestack: Whether to stack the last n (grayscaled) frames. Note that this + step happens after(!) a possible frameskip step, meaning that if + frameskip=4 and framestack=2, we would perform the following over this + trajectory: + actual env timesteps: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -> ... + frameskip: ( max ) ( max ) ( max ) ( max ) + framestack: ( stack ) (stack ) + + Returns: + The wrapped gym.Env. + """ + # Time limit. + env = gym.wrappers.TimeLimit(env, max_episode_steps=108000) + # Grayscale + resize. + env = WarpFrame(env, dim=dim, grayscale=grayscale) + # Normalize the image. + env = NormalizedImageEnv(env) + # Frameskip: Take max over these n frames. + if frameskip > 1: + assert env.spec is not None + env = MaxAndSkipEnv(env, skip=frameskip) + # Send n noop actions into env after reset to increase variance in the + # "start states" of the trajectories. These dummy steps are NOT included in the + # sampled data used for learning. + env = NoopResetEnv(env, noop_max=30) + # Each life is one episode. + env = EpisodicLifeEnv(env) + # Some envs only start playing after pressing fire. Unblock those. + if "FIRE" in env.unwrapped.get_action_meanings(): + env = FireResetEnv(env) + # Framestack. + if framestack: + env = FrameStack(env, k=framestack) + return env + + +@PublicAPI +def wrap_deepmind(env, dim=84, framestack=True, noframeskip=False): + """Configure environment for DeepMind-style Atari. + + Note that we assume reward clipping is done outside the wrapper. + + Args: + env: The env object to wrap. + dim: Dimension to resize observations to (dim x dim). + framestack: Whether to framestack observations. + """ + env = MonitorEnv(env) + env = NoopResetEnv(env, noop_max=30) + if env.spec is not None and noframeskip is True: + env = MaxAndSkipEnv(env, skip=4) + env = EpisodicLifeEnv(env) + if "FIRE" in env.unwrapped.get_action_meanings(): + env = FireResetEnv(env) + env = WarpFrame(env, dim) + # env = ClipRewardEnv(env) # reward clipping is handled by policy eval + # 4x image framestacking. + if framestack is True: + env = FrameStack(env, 4) + return env diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/dm_control_wrapper.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/dm_control_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..431e34a19037a2606edfa65a692c7f049f62f6e9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/dm_control_wrapper.py @@ -0,0 +1,237 @@ +""" +DeepMind Control Suite Wrapper directly sourced from: +https://github.com/denisyarats/dmc2gym + +MIT License + +Copyright (c) 2020 Denis Yarats + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" +import gymnasium as gym + +try: + from dm_env import specs +except ImportError: + specs = None +try: + # Suppress MuJoCo warning (dm_control uses absl logging). + import absl.logging + + absl.logging.set_verbosity("error") + from dm_control import suite +except (ImportError, OSError): + suite = None +import numpy as np + +from ray.rllib.utils.annotations import DeveloperAPI, PublicAPI + + +def _spec_to_box(spec): + def extract_min_max(s): + assert s.dtype == np.float64 or s.dtype == np.float32 + dim = np.int_(np.prod(s.shape)) + if type(s) is specs.Array: + bound = np.inf * np.ones(dim, dtype=np.float32) + return -bound, bound + elif type(s) is specs.BoundedArray: + zeros = np.zeros(dim, dtype=np.float32) + return s.minimum + zeros, s.maximum + zeros + + mins, maxs = [], [] + for s in spec: + mn, mx = extract_min_max(s) + mins.append(mn) + maxs.append(mx) + low = np.concatenate(mins, axis=0) + high = np.concatenate(maxs, axis=0) + assert low.shape == high.shape + return gym.spaces.Box(low, high, dtype=np.float32) + + +def _flatten_obs(obs): + obs_pieces = [] + for v in obs.values(): + flat = np.array([v]) if np.isscalar(v) else v.ravel() + obs_pieces.append(flat) + return np.concatenate(obs_pieces, axis=0) + + +@PublicAPI +class DMCEnv(gym.Env): + def __init__( + self, + domain_name, + task_name, + task_kwargs=None, + visualize_reward=False, + from_pixels=False, + height=64, + width=64, + camera_id=0, + frame_skip=2, + environment_kwargs=None, + channels_first=True, + preprocess=True, + ): + self._from_pixels = from_pixels + self._height = height + self._width = width + self._camera_id = camera_id + self._frame_skip = frame_skip + self._channels_first = channels_first + self.preprocess = preprocess + + if specs is None: + raise RuntimeError( + ( + "The `specs` module from `dm_env` was not imported. Make sure " + "`dm_env` is installed and visible in the current python " + "environment." + ) + ) + if suite is None: + raise RuntimeError( + ( + "The `suite` module from `dm_control` was not imported. Make " + "sure `dm_control` is installed and visible in the current " + "python enviornment." + ) + ) + + # create task + self._env = suite.load( + domain_name=domain_name, + task_name=task_name, + task_kwargs=task_kwargs, + visualize_reward=visualize_reward, + environment_kwargs=environment_kwargs, + ) + + # true and normalized action spaces + self._true_action_space = _spec_to_box([self._env.action_spec()]) + self._norm_action_space = gym.spaces.Box( + low=-1.0, high=1.0, shape=self._true_action_space.shape, dtype=np.float32 + ) + + # create observation space + if from_pixels: + shape = [3, height, width] if channels_first else [height, width, 3] + self._observation_space = gym.spaces.Box( + low=0, high=255, shape=shape, dtype=np.uint8 + ) + if preprocess: + self._observation_space = gym.spaces.Box( + low=-0.5, high=0.5, shape=shape, dtype=np.float32 + ) + else: + self._observation_space = _spec_to_box( + self._env.observation_spec().values() + ) + + self._state_space = _spec_to_box(self._env.observation_spec().values()) + + self.current_state = None + + def __getattr__(self, name): + return getattr(self._env, name) + + def _get_obs(self, time_step): + if self._from_pixels: + obs = self.render( + height=self._height, width=self._width, camera_id=self._camera_id + ) + if self._channels_first: + obs = obs.transpose(2, 0, 1).copy() + if self.preprocess: + obs = obs / 255.0 - 0.5 + else: + obs = _flatten_obs(time_step.observation) + return obs.astype(np.float32) + + def _convert_action(self, action): + action = action.astype(np.float64) + true_delta = self._true_action_space.high - self._true_action_space.low + norm_delta = self._norm_action_space.high - self._norm_action_space.low + action = (action - self._norm_action_space.low) / norm_delta + action = action * true_delta + self._true_action_space.low + action = action.astype(np.float32) + return action + + @property + def observation_space(self): + return self._observation_space + + @property + def state_space(self): + return self._state_space + + @property + def action_space(self): + return self._norm_action_space + + def step(self, action): + assert self._norm_action_space.contains(action) + action = self._convert_action(action) + assert self._true_action_space.contains(action) + reward = 0.0 + extra = {"internal_state": self._env.physics.get_state().copy()} + + terminated = truncated = False + for _ in range(self._frame_skip): + time_step = self._env.step(action) + reward += time_step.reward or 0.0 + terminated = False + truncated = time_step.last() + if terminated or truncated: + break + obs = self._get_obs(time_step) + self.current_state = _flatten_obs(time_step.observation) + extra["discount"] = time_step.discount + return obs, reward, terminated, truncated, extra + + def reset(self, *, seed=None, options=None): + time_step = self._env.reset() + self.current_state = _flatten_obs(time_step.observation) + obs = self._get_obs(time_step) + return obs, {} + + def render(self, mode="rgb_array", height=None, width=None, camera_id=0): + assert mode == "rgb_array", "only support for rgb_array mode" + height = height or self._height + width = width or self._width + camera_id = camera_id or self._camera_id + return self._env.physics.render(height=height, width=width, camera_id=camera_id) + + +@DeveloperAPI +class ActionClip(gym.ActionWrapper): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._low = -1.0 + self._high = 1.0 + self.action_space = gym.spaces.Box( + self._low, + self._high, + self.action_space.shape, + self.action_space.dtype, + ) + + def action(self, action): + return np.clip(action, self._low, self._high) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/dm_env_wrapper.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/dm_env_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..435251df216b2159a27ad2f28981c5d85b5ab0d0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/dm_env_wrapper.py @@ -0,0 +1,98 @@ +import gymnasium as gym +from gymnasium import spaces + +import numpy as np + +try: + from dm_env import specs +except ImportError: + specs = None + +from ray.rllib.utils.annotations import PublicAPI + + +def _convert_spec_to_space(spec): + if isinstance(spec, dict): + return spaces.Dict({k: _convert_spec_to_space(v) for k, v in spec.items()}) + if isinstance(spec, specs.DiscreteArray): + return spaces.Discrete(spec.num_values) + elif isinstance(spec, specs.BoundedArray): + return spaces.Box( + low=np.asscalar(spec.minimum), + high=np.asscalar(spec.maximum), + shape=spec.shape, + dtype=spec.dtype, + ) + elif isinstance(spec, specs.Array): + return spaces.Box( + low=-float("inf"), high=float("inf"), shape=spec.shape, dtype=spec.dtype + ) + + raise NotImplementedError( + ( + "Could not convert `Array` spec of type {} to Gym space. " + "Attempted to convert: {}" + ).format(type(spec), spec) + ) + + +@PublicAPI +class DMEnv(gym.Env): + """A `gym.Env` wrapper for the `dm_env` API.""" + + metadata = {"render.modes": ["rgb_array"]} + + def __init__(self, dm_env): + super(DMEnv, self).__init__() + self._env = dm_env + self._prev_obs = None + + if specs is None: + raise RuntimeError( + ( + "The `specs` module from `dm_env` was not imported. Make sure " + "`dm_env` is installed and visible in the current python " + "environment." + ) + ) + + def step(self, action): + ts = self._env.step(action) + + reward = ts.reward + if reward is None: + reward = 0.0 + + return ts.observation, reward, ts.last(), False, {"discount": ts.discount} + + def reset(self, *, seed=None, options=None): + ts = self._env.reset() + return ts.observation, {} + + def render(self, mode="rgb_array"): + if self._prev_obs is None: + raise ValueError( + "Environment not started. Make sure to reset before rendering." + ) + + if mode == "rgb_array": + return self._prev_obs + else: + raise NotImplementedError("Render mode '{}' is not supported.".format(mode)) + + @property + def action_space(self): + spec = self._env.action_spec() + return _convert_spec_to_space(spec) + + @property + def observation_space(self): + spec = self._env.observation_spec() + return _convert_spec_to_space(spec) + + @property + def reward_range(self): + spec = self._env.reward_spec() + if isinstance(spec, specs.BoundedArray): + return spec.minimum, spec.maximum + return -float("inf"), float("inf") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/group_agents_wrapper.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/group_agents_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bb592a79d0ae39870926dac2d6406cfbb7e78f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/group_agents_wrapper.py @@ -0,0 +1,157 @@ +from collections import OrderedDict +import gymnasium as gym +from typing import Dict, List, Optional + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.typing import AgentID + +# info key for the individual rewards of an agent, for example: +# info: { +# group_1: { +# _group_rewards: [5, -1, 1], # 3 agents in this group +# } +# } +GROUP_REWARDS = "_group_rewards" + +# info key for the individual infos of an agent, for example: +# info: { +# group_1: { +# _group_infos: [{"foo": ...}, {}], # 2 agents in this group +# } +# } +GROUP_INFO = "_group_info" + + +@DeveloperAPI +class GroupAgentsWrapper(MultiAgentEnv): + """Wraps a MultiAgentEnv environment with agents grouped as specified. + + See multi_agent_env.py for the specification of groups. + + This API is experimental. + """ + + def __init__( + self, + env: MultiAgentEnv, + groups: Dict[str, List[AgentID]], + obs_space: Optional[gym.Space] = None, + act_space: Optional[gym.Space] = None, + ): + """Wrap an existing MultiAgentEnv to group agent ID together. + + See `MultiAgentEnv.with_agent_groups()` for more detailed usage info. + + Args: + env: The env to wrap and whose agent IDs to group into new agents. + groups: Mapping from group id to a list of the agent ids + of group members. If an agent id is not present in any group + value, it will be left ungrouped. The group id becomes a new agent ID + in the final environment. + obs_space: Optional observation space for the grouped + env. Must be a tuple space. If not provided, will infer this to be a + Tuple of n individual agents spaces (n=num agents in a group). + act_space: Optional action space for the grouped env. + Must be a tuple space. If not provided, will infer this to be a Tuple + of n individual agents spaces (n=num agents in a group). + """ + super().__init__() + self.env = env + self.groups = groups + self.agent_id_to_group = {} + for group_id, agent_ids in groups.items(): + for agent_id in agent_ids: + if agent_id in self.agent_id_to_group: + raise ValueError( + "Agent id {} is in multiple groups".format(agent_id) + ) + self.agent_id_to_group[agent_id] = group_id + if obs_space is not None: + self.observation_space = obs_space + if act_space is not None: + self.action_space = act_space + for group_id in groups.keys(): + self._agent_ids.add(group_id) + + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + obs, info = self.env.reset(seed=seed, options=options) + + return ( + self._group_items(obs), + self._group_items( + info, + agg_fn=lambda gvals: {GROUP_INFO: list(gvals.values())}, + ), + ) + + def step(self, action_dict): + # Ungroup and send actions. + action_dict = self._ungroup_items(action_dict) + obs, rewards, terminateds, truncateds, infos = self.env.step(action_dict) + + # Apply grouping transforms to the env outputs + obs = self._group_items(obs) + rewards = self._group_items(rewards, agg_fn=lambda gvals: list(gvals.values())) + # Only if all of the agents are terminated, the group is terminated as well. + terminateds = self._group_items( + terminateds, agg_fn=lambda gvals: all(gvals.values()) + ) + # If all of the agents are truncated, the group is truncated as well. + truncateds = self._group_items( + truncateds, + agg_fn=lambda gvals: all(gvals.values()), + ) + infos = self._group_items( + infos, agg_fn=lambda gvals: {GROUP_INFO: list(gvals.values())} + ) + + # Aggregate rewards, but preserve the original values in infos. + for agent_id, rew in rewards.items(): + if isinstance(rew, list): + rewards[agent_id] = sum(rew) + if agent_id not in infos: + infos[agent_id] = {} + infos[agent_id][GROUP_REWARDS] = rew + + return obs, rewards, terminateds, truncateds, infos + + def _ungroup_items(self, items): + out = {} + for agent_id, value in items.items(): + if agent_id in self.groups: + assert len(value) == len(self.groups[agent_id]), ( + agent_id, + value, + self.groups, + ) + for a, v in zip(self.groups[agent_id], value): + out[a] = v + else: + out[agent_id] = value + return out + + def _group_items(self, items, agg_fn=None): + if agg_fn is None: + agg_fn = lambda gvals: list(gvals.values()) # noqa: E731 + + grouped_items = {} + for agent_id, item in items.items(): + if agent_id in self.agent_id_to_group: + group_id = self.agent_id_to_group[agent_id] + if group_id in grouped_items: + continue # already added + group_out = OrderedDict() + for a in self.groups[group_id]: + if a in items: + group_out[a] = items[a] + else: + raise ValueError( + "Missing member of group {}: {}: {}".format( + group_id, a, items + ) + ) + grouped_items[group_id] = agg_fn(group_out) + else: + grouped_items[agent_id] = item + return grouped_items diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/multi_agent_env_compatibility.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/multi_agent_env_compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8efeda08346e5486f5a51b1fc69b614a7fffab --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/multi_agent_env_compatibility.py @@ -0,0 +1,73 @@ +from typing import Optional, Tuple + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.utils.typing import MultiAgentDict + + +class MultiAgentEnvCompatibility(MultiAgentEnv): + """A wrapper converting MultiAgentEnv from old gym API to the new one. + + "Old API" refers to step() method returning (observation, reward, done, info), + and reset() only retuning the observation. + "New API" refers to step() method returning (observation, reward, terminated, + truncated, info) and reset() returning (observation, info). + + Known limitations: + - Environments that use `self.np_random` might not work as expected. + """ + + def __init__(self, old_env, render_mode: Optional[str] = None): + """A wrapper which converts old-style envs to valid modern envs. + + Some information may be lost in the conversion, so we recommend updating your + environment. + + Args: + old_env: The old MultiAgentEnv to wrap. Implemented with the old API. + render_mode: The render mode to use when rendering the environment, + passed automatically to `env.render()`. + """ + super().__init__() + + self.metadata = getattr(old_env, "metadata", {"render_modes": []}) + self.render_mode = render_mode + self.reward_range = getattr(old_env, "reward_range", None) + self.spec = getattr(old_env, "spec", None) + self.env = old_env + + self.observation_space = old_env.observation_space + self.action_space = old_env.action_space + + def reset( + self, *, seed: Optional[int] = None, options: Optional[dict] = None + ) -> Tuple[MultiAgentDict, MultiAgentDict]: + # Use old `seed()` method. + if seed is not None: + self.env.seed(seed) + # Options are ignored + + if self.render_mode == "human": + self.render() + + obs = self.env.reset() + infos = {k: {} for k in obs.keys()} + return obs, infos + + def step( + self, action + ) -> Tuple[ + MultiAgentDict, MultiAgentDict, MultiAgentDict, MultiAgentDict, MultiAgentDict + ]: + obs, rewards, terminateds, infos = self.env.step(action) + + # Truncated should always be False by default. + truncateds = {k: False for k in terminateds.keys()} + + return obs, rewards, terminateds, truncateds, infos + + def render(self): + # Use the old `render()` API, where we have to pass in the mode to each call. + return self.env.render(mode=self.render_mode) + + def close(self): + self.env.close() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/open_spiel.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/open_spiel.py new file mode 100644 index 0000000000000000000000000000000000000000..abc051c6577000450710f65a1e503d60456f8105 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/open_spiel.py @@ -0,0 +1,130 @@ +from typing import Optional + +import numpy as np +import gymnasium as gym + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.env.utils import try_import_pyspiel + +pyspiel = try_import_pyspiel(error=True) + + +class OpenSpielEnv(MultiAgentEnv): + def __init__(self, env): + super().__init__() + self.env = env + self.agents = self.possible_agents = list(range(self.env.num_players())) + # Store the open-spiel game type. + self.type = self.env.get_type() + # Stores the current open-spiel game state. + self.state = None + + self.observation_space = gym.spaces.Dict( + { + aid: gym.spaces.Box( + float("-inf"), + float("inf"), + (self.env.observation_tensor_size(),), + dtype=np.float32, + ) + for aid in self.possible_agents + } + ) + self.action_space = gym.spaces.Dict( + { + aid: gym.spaces.Discrete(self.env.num_distinct_actions()) + for aid in self.possible_agents + } + ) + + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + self.state = self.env.new_initial_state() + return self._get_obs(), {} + + def step(self, action): + # Before applying action(s), there could be chance nodes. + # E.g. if env has to figure out, which agent's action should get + # resolved first in a simultaneous node. + self._solve_chance_nodes() + penalties = {} + + # Sequential game: + if str(self.type.dynamics) == "Dynamics.SEQUENTIAL": + curr_player = self.state.current_player() + assert curr_player in action + try: + self.state.apply_action(action[curr_player]) + # TODO: (sven) resolve this hack by publishing legal actions + # with each step. + except pyspiel.SpielError: + self.state.apply_action(np.random.choice(self.state.legal_actions())) + penalties[curr_player] = -0.1 + + # Compile rewards dict. + rewards = dict(enumerate(self.state.returns())) + # Simultaneous game. + else: + assert self.state.current_player() == -2 + # Apparently, this works, even if one or more actions are invalid. + self.state.apply_actions([action[ag] for ag in range(self.num_agents)]) + + # Now that we have applied all actions, get the next obs. + obs = self._get_obs() + + # Compile rewards dict and add the accumulated penalties + # (for taking invalid actions). + rewards = dict(enumerate(self.state.returns())) + for ag, penalty in penalties.items(): + rewards[ag] += penalty + + # Are we done? + is_terminated = self.state.is_terminal() + terminateds = dict( + {ag: is_terminated for ag in range(self.num_agents)}, + **{"__all__": is_terminated} + ) + truncateds = dict( + {ag: False for ag in range(self.num_agents)}, **{"__all__": False} + ) + + return obs, rewards, terminateds, truncateds, {} + + def render(self, mode=None) -> None: + if mode == "human": + print(self.state) + + def _get_obs(self): + # Before calculating an observation, there could be chance nodes + # (that may have an effect on the actual observations). + # E.g. After reset, figure out initial (random) positions of the + # agents. + self._solve_chance_nodes() + + if self.state.is_terminal(): + return {} + + # Sequential game: + if str(self.type.dynamics) == "Dynamics.SEQUENTIAL": + curr_player = self.state.current_player() + return { + curr_player: np.reshape(self.state.observation_tensor(), [-1]).astype( + np.float32 + ) + } + # Simultaneous game. + else: + assert self.state.current_player() == -2 + return { + ag: np.reshape(self.state.observation_tensor(ag), [-1]).astype( + np.float32 + ) + for ag in range(self.num_agents) + } + + def _solve_chance_nodes(self): + # Chance node(s): Sample a (non-player) action and apply. + while self.state.is_chance_node(): + assert self.state.current_player() == -1 + actions, probs = zip(*self.state.chance_outcomes()) + action = np.random.choice(actions, p=probs) + self.state.apply_action(action) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/pettingzoo_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/pettingzoo_env.py new file mode 100644 index 0000000000000000000000000000000000000000..5f77668cd73330d9ebfe9be67a6abac6d2222325 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/pettingzoo_env.py @@ -0,0 +1,230 @@ +from typing import Optional + +import gymnasium as gym + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.utils.annotations import PublicAPI + + +@PublicAPI +class PettingZooEnv(MultiAgentEnv): + """An interface to the PettingZoo MARL environment library. + + See: https://github.com/Farama-Foundation/PettingZoo + + Inherits from MultiAgentEnv and exposes a given AEC + (actor-environment-cycle) game from the PettingZoo project via the + MultiAgentEnv public API. + + Note that the wrapper has the following important limitation: + + Environments are positive sum games (-> Agents are expected to cooperate + to maximize reward). This isn't a hard restriction, it just that + standard algorithms aren't expected to work well in highly competitive + games. + + Also note that the earlier existing restriction of all agents having the same + observation- and action spaces has been lifted. Different agents can now have + different spaces and the entire environment's e.g. `self.action_space` is a Dict + mapping agent IDs to individual agents' spaces. Same for `self.observation_space`. + + .. testcode:: + :skipif: True + + from pettingzoo.butterfly import prison_v3 + from ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnv + env = PettingZooEnv(prison_v3.env()) + obs, infos = env.reset() + # only returns the observation for the agent which should be stepping + print(obs) + + .. testoutput:: + + { + 'prisoner_0': array([[[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + ..., + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]], dtype=uint8) + } + + .. testcode:: + :skipif: True + + obs, rewards, terminateds, truncateds, infos = env.step({ + "prisoner_0": 1 + }) + # only returns the observation, reward, info, etc, for + # the agent who's turn is next. + print(obs) + + .. testoutput:: + + { + 'prisoner_1': array([[[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + ..., + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]], dtype=uint8) + } + + .. testcode:: + :skipif: True + + print(rewards) + + .. testoutput:: + + { + 'prisoner_1': 0 + } + + .. testcode:: + :skipif: True + + print(terminateds) + + .. testoutput:: + + { + 'prisoner_1': False, '__all__': False + } + + .. testcode:: + :skipif: True + + print(truncateds) + + .. testoutput:: + + { + 'prisoner_1': False, '__all__': False + } + + .. testcode:: + :skipif: True + + print(infos) + + .. testoutput:: + + { + 'prisoner_1': {'map_tuple': (1, 0)} + } + """ + + def __init__(self, env): + super().__init__() + self.env = env + env.reset() + + self._agent_ids = set(self.env.agents) + + # If these important attributes are not set, try to infer them. + if not self.agents: + self.agents = list(self._agent_ids) + if not self.possible_agents: + self.possible_agents = self.agents.copy() + + # Set these attributes for sampling in `VectorMultiAgentEnv`s. + self.observation_spaces = { + aid: self.env.observation_space(aid) for aid in self._agent_ids + } + self.action_spaces = { + aid: self.env.action_space(aid) for aid in self._agent_ids + } + + self.observation_space = gym.spaces.Dict(self.observation_spaces) + self.action_space = gym.spaces.Dict(self.action_spaces) + + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + info = self.env.reset(seed=seed, options=options) + return ( + {self.env.agent_selection: self.env.observe(self.env.agent_selection)}, + info or {}, + ) + + def step(self, action): + self.env.step(action[self.env.agent_selection]) + obs_d = {} + rew_d = {} + terminated_d = {} + truncated_d = {} + info_d = {} + while self.env.agents: + obs, rew, terminated, truncated, info = self.env.last() + agent_id = self.env.agent_selection + obs_d[agent_id] = obs + rew_d[agent_id] = rew + terminated_d[agent_id] = terminated + truncated_d[agent_id] = truncated + info_d[agent_id] = info + if ( + self.env.terminations[self.env.agent_selection] + or self.env.truncations[self.env.agent_selection] + ): + self.env.step(None) + else: + break + + all_gone = not self.env.agents + terminated_d["__all__"] = all_gone and all(terminated_d.values()) + truncated_d["__all__"] = all_gone and all(truncated_d.values()) + + return obs_d, rew_d, terminated_d, truncated_d, info_d + + def close(self): + self.env.close() + + def render(self): + return self.env.render(self.render_mode) + + @property + def get_sub_environments(self): + return self.env.unwrapped + + +@PublicAPI +class ParallelPettingZooEnv(MultiAgentEnv): + def __init__(self, env): + super().__init__() + self.par_env = env + self.par_env.reset() + self._agent_ids = set(self.par_env.agents) + + # If these important attributes are not set, try to infer them. + if not self.agents: + self.agents = list(self._agent_ids) + if not self.possible_agents: + self.possible_agents = self.agents.copy() + + self.observation_space = gym.spaces.Dict( + {aid: self.par_env.observation_space(aid) for aid in self._agent_ids} + ) + self.action_space = gym.spaces.Dict( + {aid: self.par_env.action_space(aid) for aid in self._agent_ids} + ) + + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + obs, info = self.par_env.reset(seed=seed, options=options) + return obs, info or {} + + def step(self, action_dict): + obss, rews, terminateds, truncateds, infos = self.par_env.step(action_dict) + terminateds["__all__"] = all(terminateds.values()) + truncateds["__all__"] = all(truncateds.values()) + return obss, rews, terminateds, truncateds, infos + + def close(self): + self.par_env.close() + + def render(self): + return self.par_env.render(self.render_mode) + + @property + def get_sub_environments(self): + return self.par_env.unwrapped diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/unity3d_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/unity3d_env.py new file mode 100644 index 0000000000000000000000000000000000000000..82babd666741378b7fbab807edef020d364e903e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/unity3d_env.py @@ -0,0 +1,318 @@ +from gymnasium.spaces import Box, MultiDiscrete, Tuple as TupleSpace +import logging +import numpy as np +import random +import time +from typing import Callable, Optional, Tuple + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import MultiAgentDict, PolicyID, AgentID + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class Unity3DEnv(MultiAgentEnv): + # Default base port when connecting directly to the Editor + _BASE_PORT_EDITOR = 5004 + # Default base port when connecting to a compiled environment + _BASE_PORT_ENVIRONMENT = 5005 + # The worker_id for each environment instance + _WORKER_ID = 0 + + def __init__( + self, + file_name: str = None, + port: Optional[int] = None, + seed: int = 0, + no_graphics: bool = False, + timeout_wait: int = 300, + episode_horizon: int = 1000, + ): + super().__init__() + + if file_name is None: + print( + "No game binary provided, will use a running Unity editor " + "instead.\nMake sure you are pressing the Play (|>) button in " + "your editor to start." + ) + + import mlagents_envs + from mlagents_envs.environment import UnityEnvironment + + # Try connecting to the Unity3D game instance. If a port is blocked + port_ = None + while True: + # Sleep for random time to allow for concurrent startup of many + # environments (num_env_runners >> 1). Otherwise, would lead to port + # conflicts sometimes. + if port_ is not None: + time.sleep(random.randint(1, 10)) + port_ = port or ( + self._BASE_PORT_ENVIRONMENT if file_name else self._BASE_PORT_EDITOR + ) + # cache the worker_id and + # increase it for the next environment + worker_id_ = Unity3DEnv._WORKER_ID if file_name else 0 + Unity3DEnv._WORKER_ID += 1 + try: + self.unity_env = UnityEnvironment( + file_name=file_name, + worker_id=worker_id_, + base_port=port_, + seed=seed, + no_graphics=no_graphics, + timeout_wait=timeout_wait, + ) + print("Created UnityEnvironment for port {}".format(port_ + worker_id_)) + except mlagents_envs.exception.UnityWorkerInUseException: + pass + else: + break + + # ML-Agents API version. + self.api_version = self.unity_env.API_VERSION.split(".") + self.api_version = [int(s) for s in self.api_version] + + # Reset entire env every this number of step calls. + self.episode_horizon = episode_horizon + # Keep track of how many times we have called `step` so far. + self.episode_timesteps = 0 + + def step( + self, action_dict: MultiAgentDict + ) -> Tuple[ + MultiAgentDict, MultiAgentDict, MultiAgentDict, MultiAgentDict, MultiAgentDict + ]: + from mlagents_envs.base_env import ActionTuple + + # Set only the required actions (from the DecisionSteps) in Unity3D. + all_agents = [] + for behavior_name in self.unity_env.behavior_specs: + # New ML-Agents API: Set all agents actions at the same time + # via an ActionTuple. Since API v1.4.0. + if self.api_version[0] > 1 or ( + self.api_version[0] == 1 and self.api_version[1] >= 4 + ): + actions = [] + for agent_id in self.unity_env.get_steps(behavior_name)[0].agent_id: + key = behavior_name + "_{}".format(agent_id) + all_agents.append(key) + actions.append(action_dict[key]) + if actions: + if actions[0].dtype == np.float32: + action_tuple = ActionTuple(continuous=np.array(actions)) + else: + action_tuple = ActionTuple(discrete=np.array(actions)) + self.unity_env.set_actions(behavior_name, action_tuple) + # Old behavior: Do not use an ActionTuple and set each agent's + # action individually. + else: + for agent_id in self.unity_env.get_steps(behavior_name)[ + 0 + ].agent_id_to_index.keys(): + key = behavior_name + "_{}".format(agent_id) + all_agents.append(key) + self.unity_env.set_action_for_agent( + behavior_name, agent_id, action_dict[key] + ) + # Do the step. + self.unity_env.step() + + obs, rewards, terminateds, truncateds, infos = self._get_step_results() + + # Global horizon reached? -> Return __all__ truncated=True, so user + # can reset. Set all agents' individual `truncated` to True as well. + self.episode_timesteps += 1 + if self.episode_timesteps > self.episode_horizon: + return ( + obs, + rewards, + terminateds, + dict({"__all__": True}, **{agent_id: True for agent_id in all_agents}), + infos, + ) + + return obs, rewards, terminateds, truncateds, infos + + def reset( + self, *, seed=None, options=None + ) -> Tuple[MultiAgentDict, MultiAgentDict]: + """Resets the entire Unity3D scene (a single multi-agent episode).""" + self.episode_timesteps = 0 + self.unity_env.reset() + obs, _, _, _, infos = self._get_step_results() + return obs, infos + + def _get_step_results(self): + obs = {} + rewards = {} + infos = {} + for behavior_name in self.unity_env.behavior_specs: + decision_steps, terminal_steps = self.unity_env.get_steps(behavior_name) + # Important: Only update those sub-envs that are currently + # available within _env_state. + # Loop through all envs ("agents") and fill in, whatever + # information we have. + for agent_id, idx in decision_steps.agent_id_to_index.items(): + key = behavior_name + "_{}".format(agent_id) + os = tuple(o[idx] for o in decision_steps.obs) + os = os[0] if len(os) == 1 else os + obs[key] = os + rewards[key] = ( + decision_steps.reward[idx] + decision_steps.group_reward[idx] + ) + for agent_id, idx in terminal_steps.agent_id_to_index.items(): + key = behavior_name + "_{}".format(agent_id) + # Only overwrite rewards (last reward in episode), b/c obs + # here is the last obs (which doesn't matter anyways). + # Unless key does not exist in obs. + if key not in obs: + os = tuple(o[idx] for o in terminal_steps.obs) + obs[key] = os = os[0] if len(os) == 1 else os + rewards[key] = ( + terminal_steps.reward[idx] + terminal_steps.group_reward[idx] + ) + + # Only use dones if all agents are done, then we should do a reset. + return obs, rewards, {"__all__": False}, {"__all__": False}, infos + + @staticmethod + def get_policy_configs_for_game( + game_name: str, + ) -> Tuple[dict, Callable[[AgentID], PolicyID]]: + + # The RLlib server must know about the Spaces that the Client will be + # using inside Unity3D, up-front. + obs_spaces = { + # 3DBall. + "3DBall": Box(float("-inf"), float("inf"), (8,)), + # 3DBallHard. + "3DBallHard": Box(float("-inf"), float("inf"), (45,)), + # GridFoodCollector + "GridFoodCollector": Box(float("-inf"), float("inf"), (40, 40, 6)), + # Pyramids. + "Pyramids": TupleSpace( + [ + Box(float("-inf"), float("inf"), (56,)), + Box(float("-inf"), float("inf"), (56,)), + Box(float("-inf"), float("inf"), (56,)), + Box(float("-inf"), float("inf"), (4,)), + ] + ), + # SoccerTwos. + "SoccerPlayer": TupleSpace( + [ + Box(-1.0, 1.0, (264,)), + Box(-1.0, 1.0, (72,)), + ] + ), + # SoccerStrikersVsGoalie. + "Goalie": Box(float("-inf"), float("inf"), (738,)), + "Striker": TupleSpace( + [ + Box(float("-inf"), float("inf"), (231,)), + Box(float("-inf"), float("inf"), (63,)), + ] + ), + # Sorter. + "Sorter": TupleSpace( + [ + Box( + float("-inf"), + float("inf"), + ( + 20, + 23, + ), + ), + Box(float("-inf"), float("inf"), (10,)), + Box(float("-inf"), float("inf"), (8,)), + ] + ), + # Tennis. + "Tennis": Box(float("-inf"), float("inf"), (27,)), + # VisualHallway. + "VisualHallway": Box(float("-inf"), float("inf"), (84, 84, 3)), + # Walker. + "Walker": Box(float("-inf"), float("inf"), (212,)), + # FoodCollector. + "FoodCollector": TupleSpace( + [ + Box(float("-inf"), float("inf"), (49,)), + Box(float("-inf"), float("inf"), (4,)), + ] + ), + } + action_spaces = { + # 3DBall. + "3DBall": Box(-1.0, 1.0, (2,), dtype=np.float32), + # 3DBallHard. + "3DBallHard": Box(-1.0, 1.0, (2,), dtype=np.float32), + # GridFoodCollector. + "GridFoodCollector": MultiDiscrete([3, 3, 3, 2]), + # Pyramids. + "Pyramids": MultiDiscrete([5]), + # SoccerStrikersVsGoalie. + "Goalie": MultiDiscrete([3, 3, 3]), + "Striker": MultiDiscrete([3, 3, 3]), + # SoccerTwos. + "SoccerPlayer": MultiDiscrete([3, 3, 3]), + # Sorter. + "Sorter": MultiDiscrete([3, 3, 3]), + # Tennis. + "Tennis": Box(-1.0, 1.0, (3,)), + # VisualHallway. + "VisualHallway": MultiDiscrete([5]), + # Walker. + "Walker": Box(-1.0, 1.0, (39,)), + # FoodCollector. + "FoodCollector": MultiDiscrete([3, 3, 3, 2]), + } + + # Policies (Unity: "behaviors") and agent-to-policy mapping fns. + if game_name == "SoccerStrikersVsGoalie": + policies = { + "Goalie": PolicySpec( + observation_space=obs_spaces["Goalie"], + action_space=action_spaces["Goalie"], + ), + "Striker": PolicySpec( + observation_space=obs_spaces["Striker"], + action_space=action_spaces["Striker"], + ), + } + + def policy_mapping_fn(agent_id, episode, worker, **kwargs): + return "Striker" if "Striker" in agent_id else "Goalie" + + elif game_name == "SoccerTwos": + policies = { + "PurplePlayer": PolicySpec( + observation_space=obs_spaces["SoccerPlayer"], + action_space=action_spaces["SoccerPlayer"], + ), + "BluePlayer": PolicySpec( + observation_space=obs_spaces["SoccerPlayer"], + action_space=action_spaces["SoccerPlayer"], + ), + } + + def policy_mapping_fn(agent_id, episode, worker, **kwargs): + return "BluePlayer" if "1_" in agent_id else "PurplePlayer" + + else: + policies = { + game_name: PolicySpec( + observation_space=obs_spaces[game_name], + action_space=action_spaces[game_name], + ), + } + + def policy_mapping_fn(agent_id, episode, worker, **kwargs): + return game_name + + return policies, policy_mapping_fn diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dc503804870c771fdca11ed8bf6c52bb712be01 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/env_runner_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/env_runner_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e5a8daa66bb9222c583e8d2ce8b1d7455128304 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/env_runner_v2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/episode_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/episode_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91585f462d3b6ac94245aae50fd76c613b3625e3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/episode_v2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/metrics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e681dd6bc8d8316ae25d48e019bad56da9cd91c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/metrics.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/observation_function.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/observation_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b93eb83bbaf3f4072a760f8c9927c232ee17b032 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/observation_function.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/postprocessing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/postprocessing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23cd17326e90658f13ba2003df07d9934408fbf4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/postprocessing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/rollout_worker.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/rollout_worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c7e30bae3153540809412dba85fe39dbc4db684 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/rollout_worker.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/sample_batch_builder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/sample_batch_builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ac2f8a70ece3f88e3ddf785a4f08d46bc889f13 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/sample_batch_builder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/sampler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/sampler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99646a0345accb84c6694f39dccf11605c39586b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/sampler.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/worker_set.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/worker_set.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d48b3ed73fad769616ad7ea41741e78ebcb58f69 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__pycache__/worker_set.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb1427e29c18fca9eb93fdaf8cc4913a280eb723 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/agent_collector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/agent_collector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4a208470f7cc81c315b806d6726cef8e701520e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/agent_collector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/sample_collector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/sample_collector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a30b7a8ff14492114e8998e0ca0032b1f026e83 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/sample_collector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/simple_list_collector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/simple_list_collector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9571f9d8a0a931cc9bb429368b5b8cf4c3c21a1a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/__pycache__/simple_list_collector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/agent_collector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/agent_collector.py new file mode 100644 index 0000000000000000000000000000000000000000..1180a7f3784eb043c24bf445d94f7a4d60be2781 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/agent_collector.py @@ -0,0 +1,688 @@ +import copy +import logging +import math +from typing import Any, Dict, List, Optional + +import numpy as np +import tree # pip install dm_tree +from gymnasium.spaces import Space + +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.spaces.space_utils import ( + flatten_to_single_ndarray, + get_dummy_batch_for_space, +) +from ray.rllib.utils.typing import ( + EpisodeID, + EnvID, + TensorType, + ViewRequirementsDict, +) + +logger = logging.getLogger(__name__) + +torch, _ = try_import_torch() + + +def _to_float_np_array(v: List[Any]) -> np.ndarray: + if torch and torch.is_tensor(v[0]): + raise ValueError + arr = np.array(v) + if arr.dtype == np.float64: + return arr.astype(np.float32) # save some memory + return arr + + +def _get_buffered_slice_with_paddings(d, inds): + element_at_t = [] + for index in inds: + if index < len(d): + element_at_t.append(d[index]) + else: + # zero pad similar to the last element. + element_at_t.append(tree.map_structure(np.zeros_like, d[-1])) + return element_at_t + + +@OldAPIStack +class AgentCollector: + """Collects samples for one agent in one trajectory (episode). + + The agent may be part of a multi-agent environment. Samples are stored in + lists including some possible automatic "shift" buffer at the beginning to + be able to save memory when storing things like NEXT_OBS, PREV_REWARDS, + etc.., which are specified using the trajectory view API. + """ + + _next_unroll_id = 0 # disambiguates unrolls within a single episode + + # TODO: @kourosh add different types of padding. e.g. zeros vs. same + def __init__( + self, + view_reqs: ViewRequirementsDict, + *, + max_seq_len: int = 1, + disable_action_flattening: bool = True, + intial_states: Optional[List[TensorType]] = None, + is_policy_recurrent: bool = False, + is_training: bool = True, + _enable_new_api_stack: bool = False, + ): + """Initialize an AgentCollector. + + Args: + view_reqs: A dict of view requirements for the agent. + max_seq_len: The maximum sequence length to store. + disable_action_flattening: If True, don't flatten the action. + intial_states: The initial states from the policy.get_initial_states() + is_policy_recurrent: If True, the policy is recurrent. + is_training: Sets the is_training flag for the buffers. if True, all the + timesteps are stored in the buffers until explicitly build_for_training + () is called. if False, only the content required for the last time + step is stored in the buffers. This will save memory during inference. + You can change the behavior at runtime by calling is_training(mode). + """ + self.max_seq_len = max_seq_len + self.disable_action_flattening = disable_action_flattening + self.view_requirements = view_reqs + # The initial_states can be an np array + self.initial_states = intial_states if intial_states is not None else [] + self.is_policy_recurrent = is_policy_recurrent + self._is_training = is_training + self._enable_new_api_stack = _enable_new_api_stack + + # Determine the size of the buffer we need for data before the actual + # episode starts. This is used for 0-buffering of e.g. prev-actions, + # or internal state inputs. + view_req_shifts = [ + min(vr.shift_arr) + - int((vr.data_col or k) in [SampleBatch.OBS, SampleBatch.INFOS]) + for k, vr in view_reqs.items() + ] + self.shift_before = -min(view_req_shifts) + + # The actual data buffers. Keys are column names, values are lists + # that contain the sub-components (e.g. for complex obs spaces) with + # each sub-component holding a list of per-timestep tensors. + # E.g.: obs-space = Dict(a=Discrete(2), b=Box((2,))) + # buffers["obs"] = [ + # [0, 1], # <- 1st sub-component of observation + # [np.array([.2, .3]), np.array([.0, -.2])] # <- 2nd sub-component + # ] + # NOTE: infos and state_out... are not flattened due to them often + # using custom dict values whose structure may vary from timestep to + # timestep. + self.buffers: Dict[str, List[List[TensorType]]] = {} + # Maps column names to an example data item, which may be deeply + # nested. These are used such that we'll know how to unflatten + # the flattened data inside self.buffers when building the + # SampleBatch. + self.buffer_structs: Dict[str, Any] = {} + # The episode ID for the agent for which we collect data. + self.episode_id = None + # The unroll ID, unique across all rollouts (within a RolloutWorker). + self.unroll_id = None + # The simple timestep count for this agent. Gets increased by one + # each time a (non-initial!) observation is added. + self.agent_steps = 0 + # Keep track of view requirements that have a view on columns that we gain from + # inference and also need for inference. These have dummy values appended in + # buffers to account for the missing value when building for inference + # Example: We have one 'state_in' view requirement that has a view on our + # state_outs at t=[-10, ..., -1]. At any given build_for_inference()-call, + # the buffer must contain eleven values from t=[-10, ..., 0] for us to index + # properly. Since state_out at t=0 is missing, we substitute it with a buffer + # value that should never make it into batches built for training. + self.data_cols_with_dummy_values = set() + + @property + def training(self) -> bool: + return self._is_training + + def is_training(self, is_training: bool) -> None: + self._is_training = is_training + + def is_empty(self) -> bool: + """Returns True if this collector has no data.""" + return not self.buffers or all(len(item) == 0 for item in self.buffers.values()) + + def add_init_obs( + self, + episode_id: EpisodeID, + agent_index: int, + env_id: EnvID, + init_obs: TensorType, + init_infos: Optional[Dict[str, TensorType]] = None, + t: int = -1, + ) -> None: + """Adds an initial observation (after reset) to the Agent's trajectory. + + Args: + episode_id: Unique ID for the episode we are adding the + initial observation for. + agent_index: Unique int index (starting from 0) for the agent + within its episode. Not to be confused with AGENT_ID (Any). + env_id: The environment index (in a vectorized setup). + init_obs: The initial observation tensor (after `env.reset()`). + init_infos: The initial infos dict (after `env.reset()`). + t: The time step (episode length - 1). The initial obs has + ts=-1(!), then an action/reward/next-obs at t=0, etc.. + """ + # Store episode ID + unroll ID, which will be constant throughout this + # AgentCollector's lifecycle. + self.episode_id = episode_id + if self.unroll_id is None: + self.unroll_id = AgentCollector._next_unroll_id + AgentCollector._next_unroll_id += 1 + + # convert init_obs to np.array (in case it is a list) + if isinstance(init_obs, list): + init_obs = np.array(init_obs) + + if SampleBatch.OBS not in self.buffers: + single_row = { + SampleBatch.OBS: init_obs, + SampleBatch.INFOS: init_infos or {}, + SampleBatch.AGENT_INDEX: agent_index, + SampleBatch.ENV_ID: env_id, + SampleBatch.T: t, + SampleBatch.EPS_ID: self.episode_id, + SampleBatch.UNROLL_ID: self.unroll_id, + } + + # TODO (Artur): Remove when PREV_ACTIONS and PREV_REWARDS get deprecated. + # Note (Artur): As long as we have these in our default view requirements, + # we should build buffers with neutral elements instead of building them + # on the first AgentCollector.build_for_inference call if present. + # This prevents us from accidentally building buffers with duplicates of + # the first incoming value. + if SampleBatch.PREV_REWARDS in self.view_requirements: + single_row[SampleBatch.REWARDS] = get_dummy_batch_for_space( + space=self.view_requirements[SampleBatch.REWARDS].space, + batch_size=0, + fill_value=0.0, + ) + if SampleBatch.PREV_ACTIONS in self.view_requirements: + potentially_flattened_batch = get_dummy_batch_for_space( + space=self.view_requirements[SampleBatch.ACTIONS].space, + batch_size=0, + fill_value=0.0, + ) + if not self.disable_action_flattening: + potentially_flattened_batch = flatten_to_single_ndarray( + potentially_flattened_batch + ) + single_row[SampleBatch.ACTIONS] = potentially_flattened_batch + self._build_buffers(single_row) + + # Append data to existing buffers. + flattened = tree.flatten(init_obs) + for i, sub_obs in enumerate(flattened): + self.buffers[SampleBatch.OBS][i].append(sub_obs) + self.buffers[SampleBatch.INFOS][0].append(init_infos or {}) + self.buffers[SampleBatch.AGENT_INDEX][0].append(agent_index) + self.buffers[SampleBatch.ENV_ID][0].append(env_id) + self.buffers[SampleBatch.T][0].append(t) + self.buffers[SampleBatch.EPS_ID][0].append(self.episode_id) + self.buffers[SampleBatch.UNROLL_ID][0].append(self.unroll_id) + + def add_action_reward_next_obs(self, input_values: Dict[str, TensorType]) -> None: + """Adds the given dictionary (row) of values to the Agent's trajectory. + + Args: + values: Data dict (interpreted as a single row) to be added to buffer. + Must contain keys: + SampleBatch.ACTIONS, REWARDS, TERMINATEDS, TRUNCATEDS, and NEXT_OBS. + """ + if self.unroll_id is None: + self.unroll_id = AgentCollector._next_unroll_id + AgentCollector._next_unroll_id += 1 + + # Next obs -> obs. + values = copy.copy(input_values) + assert SampleBatch.OBS not in values + values[SampleBatch.OBS] = values[SampleBatch.NEXT_OBS] + del values[SampleBatch.NEXT_OBS] + + # convert obs to np.array (in case it is a list) + if isinstance(values[SampleBatch.OBS], list): + values[SampleBatch.OBS] = np.array(values[SampleBatch.OBS]) + + # Default to next timestep if not provided in input values + if SampleBatch.T not in input_values: + values[SampleBatch.T] = self.buffers[SampleBatch.T][0][-1] + 1 + + # Make sure EPS_ID/UNROLL_ID stay the same for this agent. + if SampleBatch.EPS_ID in values: + assert values[SampleBatch.EPS_ID] == self.episode_id + del values[SampleBatch.EPS_ID] + self.buffers[SampleBatch.EPS_ID][0].append(self.episode_id) + if SampleBatch.UNROLL_ID in values: + assert values[SampleBatch.UNROLL_ID] == self.unroll_id + del values[SampleBatch.UNROLL_ID] + self.buffers[SampleBatch.UNROLL_ID][0].append(self.unroll_id) + + for k, v in values.items(): + if k not in self.buffers: + if self.training and k.startswith("state_out"): + vr = self.view_requirements[k] + data_col = vr.data_col or k + self._fill_buffer_with_initial_values( + data_col, vr, build_for_inference=False + ) + else: + self._build_buffers({k: v}) + # Do not flatten infos, state_out and (if configured) actions. + # Infos/state-outs may be structs that change from timestep to + # timestep. + should_flatten_action_key = ( + k == SampleBatch.ACTIONS and not self.disable_action_flattening + ) + # Note (Artur) RL Modules's states need no flattening + should_flatten_state_key = ( + k.startswith("state_out") and not self._enable_new_api_stack + ) + if ( + k == SampleBatch.INFOS + or should_flatten_state_key + or should_flatten_action_key + ): + if should_flatten_action_key: + v = flatten_to_single_ndarray(v) + # Briefly remove dummy value to add to buffer + if k in self.data_cols_with_dummy_values: + dummy = self.buffers[k][0].pop(-1) + self.buffers[k][0].append(v) + # Add back dummy value + if k in self.data_cols_with_dummy_values: + self.buffers[k][0].append(dummy) + # Flatten all other columns. + else: + flattened = tree.flatten(v) + for i, sub_list in enumerate(self.buffers[k]): + # Briefly remove dummy value to add to buffer + if k in self.data_cols_with_dummy_values: + dummy = sub_list.pop(-1) + sub_list.append(flattened[i]) + # Add back dummy value + if k in self.data_cols_with_dummy_values: + sub_list.append(dummy) + + # In inference mode, we don't need to keep all of trajectory in memory + # we only need to keep the steps required. We can pop from the beginning to + # create room for new data. + if not self.training: + for k in self.buffers: + for sub_list in self.buffers[k]: + if sub_list: + sub_list.pop(0) + + self.agent_steps += 1 + + def build_for_inference(self) -> SampleBatch: + """During inference, we will build a SampleBatch with a batch size of 1 that + can then be used to run the forward pass of a policy. This data will only + include the enviornment context for running the policy at the last timestep. + + Returns: + A SampleBatch with a batch size of 1. + """ + + batch_data = {} + np_data = {} + for view_col, view_req in self.view_requirements.items(): + # Create the batch of data from the different buffers. + data_col = view_req.data_col or view_col + + # if this view is not for inference, skip it. + if not view_req.used_for_compute_actions: + continue + + if np.any(view_req.shift_arr > 0): + raise ValueError( + f"During inference the agent can only use past observations to " + f"respect causality. However, view_col = {view_col} seems to " + f"depend on future indices {view_req.shift_arr}, while the " + f"used_for_compute_actions flag is set to True. Please fix the " + f"discrepancy. Hint: If you are using a custom model make sure " + f"the view_requirements are initialized properly and is point " + f"only refering to past timesteps during inference." + ) + + # Some columns don't exist yet + # (get created during postprocessing or depend on state_out). + if data_col not in self.buffers: + self._fill_buffer_with_initial_values( + data_col, view_req, build_for_inference=True + ) + self._prepare_for_data_cols_with_dummy_values(data_col) + + # Keep an np-array cache, so we don't have to regenerate the + # np-array for different view_cols using to the same data_col. + self._cache_in_np(np_data, data_col) + + data = [] + for d in np_data[data_col]: + # if shift_arr = [0] the data will be just the last time step + # (len(d) - 1), if shift_arr = [-1] the data will be just the timestep + # before the last one (len(d) - 2) and so on. + element_at_t = d[view_req.shift_arr + len(d) - 1] + if element_at_t.shape[0] == 1: + # We'd normally squeeze here to remove the time dim, but we'll + # simply use the time dim as the batch dim. + data.append(element_at_t) + continue + # add the batch dimension with [None] + data.append(element_at_t[None]) + + # We unflatten even if data is empty here, because the structure might be + # nested with empty leafs and so we still need to reconstruct it. + # This is useful because we spec-check states in RLModules and these + # states can sometimes be nested dicts with empty leafs. + batch_data[view_col] = self._unflatten_as_buffer_struct(data, data_col) + + batch = self._get_sample_batch(batch_data) + return batch + + # TODO: @kouorsh we don't really need view_requirements anymore since it's already + # an attribute of the class + def build_for_training( + self, view_requirements: ViewRequirementsDict + ) -> SampleBatch: + """Builds a SampleBatch from the thus-far collected agent data. + + If the episode/trajectory has no TERMINATED|TRUNCATED=True at the end, will + copy the necessary n timesteps at the end of the trajectory back to the + beginning of the buffers and wait for new samples coming in. + SampleBatches created by this method will be ready for postprocessing + by a Policy. + + Args: + view_requirements: The viewrequirements dict needed to build the + SampleBatch from the raw buffers, which may have data shifts as well as + mappings from view-col to data-col in them. + + Returns: + SampleBatch: The built SampleBatch for this agent, ready to go into + postprocessing. + """ + batch_data = {} + np_data = {} + for view_col, view_req in view_requirements.items(): + # Create the batch of data from the different buffers. + data_col = view_req.data_col or view_col + + if data_col not in self.buffers: + is_state = self._fill_buffer_with_initial_values( + data_col, view_req, build_for_inference=False + ) + + # We need to skip this view_col if it does not exist in the buffers and + # is not an RNN state because it could be the special keys that gets + # added by policy's postprocessing function for training. + if not is_state: + continue + + # OBS and INFOS are already shifted by -1 (the initial obs/info starts one + # ts before all other data columns). + obs_shift = -1 if data_col in [SampleBatch.OBS, SampleBatch.INFOS] else 0 + + # Keep an np-array cache so we don't have to regenerate the + # np-array for different view_cols using to the same data_col. + self._cache_in_np(np_data, data_col) + + # Go through each time-step in the buffer and construct the view + # accordingly. + data = [] + for d in np_data[data_col]: + shifted_data = [] + + # batch_repeat_value determines how many time steps should we skip + # before we repeat indexing the data. + # Example: batch_repeat_value=10, shift_arr = [-3, -2, -1], + # shift_before = 3 + # buffer = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + # resulting_data = [[-3, -2, -1], [7, 8, 9]] + # explanation: For t=0, we output [-3, -2, -1]. We then skip 10 time + # steps ahead and get to t=10. For t=10, we output [7, 8, 9]. We skip + # 10 more time steps and get to t=20. but since t=20 is out of bound we + # stop. + + # count computes the number of time steps that we need to consider. + # if batch_repeat_value = 1, this number should be the length of + # episode so far, which is len(buffer) - shift_before (-1 if this + # value was gained during inference. This is because we keep a dummy + # value at the last position of the buffer that makes it one longer). + count = int( + math.ceil( + ( + len(d) + - int(data_col in self.data_cols_with_dummy_values) + - self.shift_before + ) + / view_req.batch_repeat_value + ) + ) + for i in range(count): + # the indices for time step t + inds = ( + self.shift_before + + obs_shift + + view_req.shift_arr + + (i * view_req.batch_repeat_value) + ) + + # handle the case where the inds are out of bounds from the end. + # if during the indexing any of the indices are out of bounds, we + # need to use padding on the end to fill in the missing indices. + # Create padding first time we encounter data + if max(inds) < len(d): + # Simple case where we can simply pick slices from buffer + element_at_t = d[inds] + else: + # Case in which we have to pad because buffer has insufficient + # length. This branch takes more time than simply picking + # slices we try to avoid it. + element_at_t = _get_buffered_slice_with_paddings(d, inds) + element_at_t = np.stack(element_at_t) + + if element_at_t.shape[0] == 1: + # Remove the T dimension if it is 1. + element_at_t = element_at_t[0] + shifted_data.append(element_at_t) + + # in some multi-agent cases shifted_data may be an empty list. + # In this case we should just create an empty array and return it. + if shifted_data: + shifted_data_np = np.stack(shifted_data, 0) + else: + shifted_data_np = np.array(shifted_data) + data.append(shifted_data_np) + + # We unflatten even if data is empty here, because the structure might be + # nested with empty leafs and so we still need to reconstruct it. + # This is useful because we spec-check states in RLModules and these + # states can sometimes be nested dicts with empty leafs. + batch_data[view_col] = self._unflatten_as_buffer_struct(data, data_col) + + batch = self._get_sample_batch(batch_data) + + # This trajectory is continuing -> Copy data at the end (in the size of + # self.shift_before) to the beginning of buffers and erase everything + # else. + if ( + SampleBatch.TERMINATEDS in self.buffers + and not self.buffers[SampleBatch.TERMINATEDS][0][-1] + and SampleBatch.TRUNCATEDS in self.buffers + and not self.buffers[SampleBatch.TRUNCATEDS][0][-1] + ): + # Copy data to beginning of buffer and cut lists. + if self.shift_before > 0: + for k, data in self.buffers.items(): + # Loop through + for i in range(len(data)): + self.buffers[k][i] = data[i][-self.shift_before :] + self.agent_steps = 0 + + # Reset our unroll_id. + self.unroll_id = None + + return batch + + def _build_buffers(self, single_row: Dict[str, TensorType]) -> None: + """Builds the buffers for sample collection, given an example data row. + + Args: + single_row (Dict[str, TensorType]): A single row (keys=column + names) of data to base the buffers on. + """ + for col, data in single_row.items(): + if col in self.buffers: + continue + + shift = self.shift_before - ( + 1 + if col + in [ + SampleBatch.OBS, + SampleBatch.INFOS, + SampleBatch.EPS_ID, + SampleBatch.AGENT_INDEX, + SampleBatch.ENV_ID, + SampleBatch.T, + SampleBatch.UNROLL_ID, + ] + else 0 + ) + + # Store all data as flattened lists, except INFOS and state-out + # lists. These are monolithic items (infos is a dict that + # should not be further split, same for state-out items, which + # could be custom dicts as well). + should_flatten_action_key = ( + col == SampleBatch.ACTIONS and not self.disable_action_flattening + ) + # Note (Artur) RL Modules's states need no flattening + should_flatten_state_key = ( + col.startswith("state_out") and not self._enable_new_api_stack + ) + if ( + col == SampleBatch.INFOS + or should_flatten_state_key + or should_flatten_action_key + ): + if should_flatten_action_key: + data = flatten_to_single_ndarray(data) + self.buffers[col] = [[data for _ in range(shift)]] + else: + self.buffers[col] = [ + [v for _ in range(shift)] for v in tree.flatten(data) + ] + # Store an example data struct so we know, how to unflatten + # each data col. + self.buffer_structs[col] = data + + def _get_sample_batch(self, batch_data: Dict[str, TensorType]) -> SampleBatch: + """Returns a SampleBatch from the given data dictionary. Also updates the + sequence information based on the max_seq_len.""" + + # Due to possible batch-repeats > 1, columns in the resulting batch + # may not all have the same batch size. + batch = SampleBatch(batch_data, is_training=self.training) + + # Adjust the seq-lens array depending on the incoming agent sequences. + if self.is_policy_recurrent: + seq_lens = [] + max_seq_len = self.max_seq_len + count = batch.count + while count > 0: + seq_lens.append(min(count, max_seq_len)) + count -= max_seq_len + batch["seq_lens"] = np.array(seq_lens) + batch.max_seq_len = max_seq_len + + return batch + + def _cache_in_np(self, cache_dict: Dict[str, List[np.ndarray]], key: str) -> None: + """Caches the numpy version of the key in the buffer dict.""" + if key not in cache_dict: + cache_dict[key] = [_to_float_np_array(d) for d in self.buffers[key]] + + def _unflatten_as_buffer_struct( + self, data: List[np.ndarray], key: str + ) -> np.ndarray: + """Unflattens the given to match the buffer struct format for that key.""" + if key not in self.buffer_structs: + return data[0] + + return tree.unflatten_as(self.buffer_structs[key], data) + + def _fill_buffer_with_initial_values( + self, + data_col: str, + view_requirement: ViewRequirement, + build_for_inference: bool = False, + ) -> bool: + """Fills the buffer with the initial values for the given data column. + for dat_col starting with `state_out`, use the initial states of the policy, + but for other data columns, create a dummy value based on the view requirement + space. + + Args: + data_col: The data column to fill the buffer with. + view_requirement: The view requirement for the view_col. Normally the view + requirement for the data column is used and if it does not exist for + some reason the view requirement for view column is used instead. + build_for_inference: Whether this is getting called for inference or not. + + returns: + is_state: True if the data_col is an RNN state, False otherwise. + """ + try: + space = self.view_requirements[data_col].space + except KeyError: + space = view_requirement.space + + # special treatment for state_out + # add them to the buffer in case they don't exist yet + is_state = True + if data_col.startswith("state_out"): + if self._enable_new_api_stack: + self._build_buffers({data_col: self.initial_states}) + else: + if not self.is_policy_recurrent: + raise ValueError( + f"{data_col} is not available, because the given policy is" + f"not recurrent according to the input model_inital_states." + f"Have you forgotten to return non-empty lists in" + f"policy.get_initial_states()?" + ) + state_ind = int(data_col.split("_")[-1]) + self._build_buffers({data_col: self.initial_states[state_ind]}) + else: + is_state = False + # only create dummy data during inference + if build_for_inference: + if isinstance(space, Space): + # state_out assumes the values do not have a batch dimension + # (i.e. instead of being (1, d) it is of shape (d,). + fill_value = get_dummy_batch_for_space( + space, + batch_size=0, + ) + else: + fill_value = space + + self._build_buffers({data_col: fill_value}) + + return is_state + + def _prepare_for_data_cols_with_dummy_values(self, data_col): + self.data_cols_with_dummy_values.add(data_col) + # For items gained during inference, we append a dummy value here so + # that view requirements viewing these is not shifted by 1 + for b in self.buffers[data_col]: + b.append(b[-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/sample_collector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/sample_collector.py new file mode 100644 index 0000000000000000000000000000000000000000..75dbb5d040a5a11e042a8d0cd18ca640f828eefd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/sample_collector.py @@ -0,0 +1,298 @@ +import logging +from abc import ABCMeta, abstractmethod +from typing import TYPE_CHECKING, Dict, List, Optional, Union + +from ray.rllib.policy.policy_map import PolicyMap +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import AgentID, EnvID, EpisodeID, PolicyID, TensorType + +if TYPE_CHECKING: + from ray.rllib.callbacks.callbacks import RLlibCallback + +logger = logging.getLogger(__name__) + + +# fmt: off +# __sphinx_doc_begin__ +@OldAPIStack +class SampleCollector(metaclass=ABCMeta): + """Collects samples for all policies and agents from a multi-agent env. + + This API is controlled by RolloutWorker objects to store all data + generated by Environments and Policies/Models during rollout and + postprocessing. It's purposes are to a) make data collection and + SampleBatch/input_dict generation from this data faster, b) to unify + the way we collect samples from environments and model (outputs), thereby + allowing for possible user customizations, c) to allow for more complex + inputs fed into different policies (e.g. multi-agent case with inter-agent + communication channel). + """ + + def __init__(self, + policy_map: PolicyMap, + clip_rewards: Union[bool, float], + callbacks: "RLlibCallback", + multiple_episodes_in_batch: bool = True, + rollout_fragment_length: int = 200, + count_steps_by: str = "env_steps"): + """Initializes a SampleCollector instance. + + Args: + policy_map: Maps policy ids to policy instances. + clip_rewards (Union[bool, float]): Whether to clip rewards before + postprocessing (at +/-1.0) or the actual value to +/- clip. + callbacks: RLlib callbacks. + multiple_episodes_in_batch: Whether it's allowed to pack + multiple episodes into the same built batch. + rollout_fragment_length: The + + """ + + self.policy_map = policy_map + self.clip_rewards = clip_rewards + self.callbacks = callbacks + self.multiple_episodes_in_batch = multiple_episodes_in_batch + self.rollout_fragment_length = rollout_fragment_length + self.count_steps_by = count_steps_by + + @abstractmethod + def add_init_obs( + self, + *, + episode, + agent_id: AgentID, + policy_id: PolicyID, + init_obs: TensorType, + init_infos: Optional[Dict[str, TensorType]] = None, + t: int = -1, + ) -> None: + """Adds an initial obs (after reset) to this collector. + + Since the very first observation in an environment is collected w/o + additional data (w/o actions, w/o reward) after env.reset() is called, + this method initializes a new trajectory for a given agent. + `add_init_obs()` has to be called first for each agent/episode-ID + combination. After this, only `add_action_reward_next_obs()` must be + called for that same agent/episode-pair. + + Args: + episode: The Episode, for which we + are adding an Agent's initial observation. + agent_id: Unique id for the agent we are adding + values for. + env_id: The environment index (in a vectorized setup). + policy_id: Unique id for policy controlling the agent. + init_obs: Initial observation (after env.reset()). + init_obs: Initial observation (after env.reset()). + init_infos: Initial infos dict (after env.reset()). + t: The time step (episode length - 1). The initial obs has + ts=-1(!), then an action/reward/next-obs at t=0, etc.. + + .. testcode:: + :skipif: True + + obs, infos = env.reset() + collector.add_init_obs( + episode=my_episode, + agent_id=0, + policy_id="pol0", + t=-1, + init_obs=obs, + init_infos=infos, + ) + obs, r, terminated, truncated, info = env.step(action) + collector.add_action_reward_next_obs(12345, 0, "pol0", False, { + "action": action, "obs": obs, "reward": r, "terminated": terminated, + "truncated": truncated, "info": info + }) + """ + raise NotImplementedError + + @abstractmethod + def add_action_reward_next_obs( + self, + episode_id: EpisodeID, + agent_id: AgentID, + env_id: EnvID, + policy_id: PolicyID, + agent_done: bool, + values: Dict[str, TensorType], + ) -> None: + """Add the given dictionary (row) of values to this collector. + + The incoming data (`values`) must include action, reward, terminated, truncated, + and next_obs information and may include any other information. + For the initial observation (after Env.reset()) of the given agent/ + episode-ID combination, `add_initial_obs()` must be called instead. + + Args: + episode_id: Unique id for the episode we are adding + values for. + agent_id: Unique id for the agent we are adding + values for. + env_id: The environment index (in a vectorized setup). + policy_id: Unique id for policy controlling the agent. + agent_done: Whether the given agent is done (terminated or truncated) with + its trajectory (the multi-agent episode may still be ongoing). + values (Dict[str, TensorType]): Row of values to add for this + agent. This row must contain the keys SampleBatch.ACTION, + REWARD, NEW_OBS, TERMINATED, and TRUNCATED. + + .. testcode:: + :skipif: True + + obs, info = env.reset() + collector.add_init_obs(12345, 0, "pol0", obs) + obs, r, terminated, truncated, info = env.step(action) + collector.add_action_reward_next_obs( + 12345, + 0, + "pol0", + agent_done=False, + values={ + "action": action, "obs": obs, "reward": r, + "terminated": terminated, "truncated": truncated + }, + ) + """ + raise NotImplementedError + + @abstractmethod + def episode_step(self, episode) -> None: + """Increases the episode step counter (across all agents) by one. + + Args: + episode: Episode we are stepping through. + Useful for handling counting b/c it is called once across + all agents that are inside this episode. + """ + raise NotImplementedError + + @abstractmethod + def total_env_steps(self) -> int: + """Returns total number of env-steps taken so far. + + Thereby, a step in an N-agent multi-agent environment counts as only 1 + for this metric. The returned count contains everything that has not + been built yet (and returned as MultiAgentBatches by the + `try_build_truncated_episode_multi_agent_batch` or + `postprocess_episode(build=True)` methods). After such build, this + counter is reset to 0. + + Returns: + int: The number of env-steps taken in total in the environment(s) + so far. + """ + raise NotImplementedError + + @abstractmethod + def total_agent_steps(self) -> int: + """Returns total number of (individual) agent-steps taken so far. + + Thereby, a step in an N-agent multi-agent environment counts as N. + If less than N agents have stepped (because some agents were not + required to send actions), the count will be increased by less than N. + The returned count contains everything that has not been built yet + (and returned as MultiAgentBatches by the + `try_build_truncated_episode_multi_agent_batch` or + `postprocess_episode(build=True)` methods). After such build, this + counter is reset to 0. + + Returns: + int: The number of (individual) agent-steps taken in total in the + environment(s) so far. + """ + raise NotImplementedError + + # TODO(jungong) : Remove this API call once we completely move to + # connector based sample collection. + @abstractmethod + def get_inference_input_dict(self, policy_id: PolicyID) -> \ + Dict[str, TensorType]: + """Returns an input_dict for an (inference) forward pass from our data. + + The input_dict can then be used for action computations inside a + Policy via `Policy.compute_actions_from_input_dict()`. + + Args: + policy_id: The Policy ID to get the input dict for. + + Returns: + Dict[str, TensorType]: The input_dict to be passed into the ModelV2 + for inference/training. + + .. testcode:: + :skipif: True + + obs, r, terminated, truncated, info = env.step(action) + collector.add_action_reward_next_obs(12345, 0, "pol0", False, { + "action": action, "obs": obs, "reward": r, + "terminated": terminated, "truncated", truncated + }) + input_dict = collector.get_inference_input_dict(policy.model) + action = policy.compute_actions_from_input_dict(input_dict) + # repeat + """ + raise NotImplementedError + + @abstractmethod + def postprocess_episode( + self, + episode, + is_done: bool = False, + check_dones: bool = False, + build: bool = False, + ) -> Optional[MultiAgentBatch]: + """Postprocesses all agents' trajectories in a given episode. + + Generates (single-trajectory) SampleBatches for all Policies/Agents and + calls Policy.postprocess_trajectory on each of these. Postprocessing + may happens in-place, meaning any changes to the viewed data columns + are directly reflected inside this collector's buffers. + Also makes sure that additional (newly created) data columns are + correctly added to the buffers. + + Args: + episode: The Episode object for which + to post-process data. + is_done: Whether the given episode is actually terminated + (all agents are terminated OR truncated). If True, the + episode will no longer be used/continued and we may need to + recycle/erase it internally. If a soft-horizon is hit, the + episode will continue to be used and `is_done` should be set + to False here. + check_dones: Whether we need to check that all agents' + trajectories have dones=True at the end. + build: Whether to build a MultiAgentBatch from the given + episode (and only that episode!) and return that + MultiAgentBatch. Used for batch_mode=`complete_episodes`. + + Returns: + Optional[MultiAgentBatch]: If `build` is True, the + SampleBatch or MultiAgentBatch built from `episode` (either + just from that episde or from the `_PolicyCollectorGroup` + in the `episode.batch_builder` property). + """ + raise NotImplementedError + + @abstractmethod + def try_build_truncated_episode_multi_agent_batch(self) -> \ + List[Union[MultiAgentBatch, SampleBatch]]: + """Tries to build an MA-batch, if `rollout_fragment_length` is reached. + + Any unprocessed data will be first postprocessed with a policy + postprocessor. + This is usually called to collect samples for policy training. + If not enough data has been collected yet (`rollout_fragment_length`), + returns an empty list. + + Returns: + List[Union[MultiAgentBatch, SampleBatch]]: Returns a (possibly + empty) list of MultiAgentBatches (containing the accumulated + SampleBatches for each policy or a simple SampleBatch if only + one policy). The list will be empty if + `self.rollout_fragment_length` has not been reached yet. + """ + raise NotImplementedError +# __sphinx_doc_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/simple_list_collector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/simple_list_collector.py new file mode 100644 index 0000000000000000000000000000000000000000..a301f61ec0df78cfb0bdefa3ca4d44927ed9e168 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/collectors/simple_list_collector.py @@ -0,0 +1,698 @@ +import collections +from gymnasium.spaces import Space +import logging +import numpy as np +import tree # pip install dm_tree +from typing import Dict, List, Optional, Tuple, TYPE_CHECKING, Union + +from ray.rllib.env.base_env import _DUMMY_AGENT_ID +from ray.rllib.evaluation.collectors.sample_collector import SampleCollector +from ray.rllib.evaluation.collectors.agent_collector import AgentCollector +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.policy_map import PolicyMap +from ray.rllib.policy.sample_batch import SampleBatch, MultiAgentBatch, concat_samples +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.debug import summarize +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.spaces.space_utils import get_dummy_batch_for_space +from ray.rllib.utils.typing import ( + AgentID, + EpisodeID, + EnvID, + PolicyID, + TensorType, + ViewRequirementsDict, +) +from ray.util.debug import log_once + +_, tf, _ = try_import_tf() +torch, _ = try_import_torch() + +if TYPE_CHECKING: + from ray.rllib.callbacks.callbacks import RLlibCallback + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class _PolicyCollector: + """Collects already postprocessed (single agent) samples for one policy. + + Samples come in through already postprocessed SampleBatches, which + contain single episode/trajectory data for a single agent and are then + appended to this policy's buffers. + """ + + def __init__(self, policy: Policy): + """Initializes a _PolicyCollector instance. + + Args: + policy: The policy object. + """ + + self.batches = [] + self.policy = policy + # The total timestep count for all agents that use this policy. + # NOTE: This is not an env-step count (across n agents). AgentA and + # agentB, both using this policy, acting in the same episode and both + # doing n steps would increase the count by 2*n. + self.agent_steps = 0 + + def add_postprocessed_batch_for_training( + self, batch: SampleBatch, view_requirements: ViewRequirementsDict + ) -> None: + """Adds a postprocessed SampleBatch (single agent) to our buffers. + + Args: + batch: An individual agent's (one trajectory) + SampleBatch to be added to the Policy's buffers. + view_requirements: The view + requirements for the policy. This is so we know, whether a + view-column needs to be copied at all (not needed for + training). + """ + # Add the agent's trajectory length to our count. + self.agent_steps += batch.count + # And remove columns not needed for training. + for view_col, view_req in view_requirements.items(): + if view_col in batch and not view_req.used_for_training: + del batch[view_col] + self.batches.append(batch) + + def build(self): + """Builds a SampleBatch for this policy from the collected data. + + Also resets all buffers for further sample collection for this policy. + + Returns: + SampleBatch: The SampleBatch with all thus-far collected data for + this policy. + """ + # Create batch from our buffers. + batch = concat_samples(self.batches) + # Clear batches for future samples. + self.batches = [] + # Reset agent steps to 0. + self.agent_steps = 0 + # Add num_grad_updates counter to the policy's batch. + batch.num_grad_updates = self.policy.num_grad_updates + + return batch + + +class _PolicyCollectorGroup: + def __init__(self, policy_map): + self.policy_collectors = {} + # Total env-steps (1 env-step=up to N agents stepped). + self.env_steps = 0 + # Total agent steps (1 agent-step=1 individual agent (out of N) + # stepped). + self.agent_steps = 0 + + +@OldAPIStack +class SimpleListCollector(SampleCollector): + """Util to build SampleBatches for each policy in a multi-agent env. + + Input data is per-agent, while output data is per-policy. There is an M:N + mapping between agents and policies. We retain one local batch builder + per agent. When an agent is done, then its local batch is appended into the + corresponding policy batch for the agent's policy. + """ + + def __init__( + self, + policy_map: PolicyMap, + clip_rewards: Union[bool, float], + callbacks: "RLlibCallback", + multiple_episodes_in_batch: bool = True, + rollout_fragment_length: int = 200, + count_steps_by: str = "env_steps", + ): + """Initializes a SimpleListCollector instance.""" + + super().__init__( + policy_map, + clip_rewards, + callbacks, + multiple_episodes_in_batch, + rollout_fragment_length, + count_steps_by, + ) + + self.large_batch_threshold: int = ( + max(1000, self.rollout_fragment_length * 10) + if self.rollout_fragment_length != float("inf") + else 5000 + ) + + # Whenever we observe a new episode+agent, add a new + # _SingleTrajectoryCollector. + self.agent_collectors: Dict[Tuple[EpisodeID, AgentID], AgentCollector] = {} + # Internal agent-key-to-policy-id map. + self.agent_key_to_policy_id = {} + # Pool of used/unused PolicyCollectorGroups (attached to episodes for + # across-episode multi-agent sample collection). + self.policy_collector_groups = [] + + # Agents to collect data from for the next forward pass (per policy). + self.forward_pass_agent_keys = {pid: [] for pid in self.policy_map.keys()} + self.forward_pass_size = {pid: 0 for pid in self.policy_map.keys()} + + # Maps episode ID to the (non-built) env steps taken in this episode. + self.episode_steps: Dict[EpisodeID, int] = collections.defaultdict(int) + # Maps episode ID to the (non-built) individual agent steps in this + # episode. + self.agent_steps: Dict[EpisodeID, int] = collections.defaultdict(int) + # Maps episode ID to Episode. + self.episodes = {} + + @override(SampleCollector) + def episode_step(self, episode) -> None: + episode_id = episode.episode_id + # In the rase case that an "empty" step is taken at the beginning of + # the episode (none of the agents has an observation in the obs-dict + # and thus does not take an action), we have seen the episode before + # and have to add it here to our registry. + if episode_id not in self.episodes: + self.episodes[episode_id] = episode + else: + assert episode is self.episodes[episode_id] + self.episode_steps[episode_id] += 1 + episode.length += 1 + + # In case of "empty" env steps (no agent is stepping), the builder + # object may still be None. + if episode.batch_builder: + env_steps = episode.batch_builder.env_steps + num_individual_observations = sum( + c.agent_steps for c in episode.batch_builder.policy_collectors.values() + ) + + if num_individual_observations > self.large_batch_threshold and log_once( + "large_batch_warning" + ): + logger.warning( + "More than {} observations in {} env steps for " + "episode {} ".format( + num_individual_observations, env_steps, episode_id + ) + + "are buffered in the sampler. If this is more than you " + "expected, check that that you set a horizon on your " + "environment correctly and that it terminates at some " + "point. Note: In multi-agent environments, " + "`rollout_fragment_length` sets the batch size based on " + "(across-agents) environment steps, not the steps of " + "individual agents, which can result in unexpectedly " + "large batches." + + ( + "Also, you may be waiting for your Env to " + "terminate (batch_mode=`complete_episodes`). Make sure " + "it does at some point." + if not self.multiple_episodes_in_batch + else "" + ) + ) + + @override(SampleCollector) + def add_init_obs( + self, + *, + episode, + agent_id: AgentID, + env_id: EnvID, + policy_id: PolicyID, + init_obs: TensorType, + init_infos: Optional[Dict[str, TensorType]] = None, + t: int = -1, + ) -> None: + # Make sure our mappings are up to date. + agent_key = (episode.episode_id, agent_id) + self.agent_key_to_policy_id[agent_key] = policy_id + policy = self.policy_map[policy_id] + + # Add initial obs to Trajectory. + assert agent_key not in self.agent_collectors + # TODO: determine exact shift-before based on the view-req shifts. + + # get max_seq_len value (Default is 1) + try: + max_seq_len = policy.config["model"]["max_seq_len"] + except KeyError: + max_seq_len = 1 + + self.agent_collectors[agent_key] = AgentCollector( + policy.view_requirements, + max_seq_len=max_seq_len, + disable_action_flattening=policy.config.get( + "_disable_action_flattening", False + ), + intial_states=policy.get_initial_state(), + is_policy_recurrent=policy.is_recurrent(), + ) + self.agent_collectors[agent_key].add_init_obs( + episode_id=episode.episode_id, + agent_index=episode._agent_index(agent_id), + env_id=env_id, + init_obs=init_obs, + init_infos=init_infos or {}, + t=t, + ) + + self.episodes[episode.episode_id] = episode + if episode.batch_builder is None: + episode.batch_builder = ( + self.policy_collector_groups.pop() + if self.policy_collector_groups + else _PolicyCollectorGroup(self.policy_map) + ) + + self._add_to_next_inference_call(agent_key) + + @override(SampleCollector) + def add_action_reward_next_obs( + self, + episode_id: EpisodeID, + agent_id: AgentID, + env_id: EnvID, + policy_id: PolicyID, + agent_done: bool, + values: Dict[str, TensorType], + ) -> None: + # Make sure, episode/agent already has some (at least init) data. + agent_key = (episode_id, agent_id) + assert self.agent_key_to_policy_id[agent_key] == policy_id + assert agent_key in self.agent_collectors + + self.agent_steps[episode_id] += 1 + + # Include the current agent id for multi-agent algorithms. + if agent_id != _DUMMY_AGENT_ID: + values["agent_id"] = agent_id + + # Add action/reward/next-obs (and other data) to Trajectory. + self.agent_collectors[agent_key].add_action_reward_next_obs(values) + + if not agent_done: + self._add_to_next_inference_call(agent_key) + + @override(SampleCollector) + def total_env_steps(self) -> int: + # Add the non-built ongoing-episode env steps + the already built + # env-steps. + return sum(self.episode_steps.values()) + sum( + pg.env_steps for pg in self.policy_collector_groups.values() + ) + + @override(SampleCollector) + def total_agent_steps(self) -> int: + # Add the non-built ongoing-episode agent steps (still in the agent + # collectors) + the already built agent steps. + return sum(a.agent_steps for a in self.agent_collectors.values()) + sum( + pg.agent_steps for pg in self.policy_collector_groups.values() + ) + + @override(SampleCollector) + def get_inference_input_dict(self, policy_id: PolicyID) -> Dict[str, TensorType]: + policy = self.policy_map[policy_id] + keys = self.forward_pass_agent_keys[policy_id] + batch_size = len(keys) + + # Return empty batch, if no forward pass to do. + if batch_size == 0: + return SampleBatch() + + buffers = {} + for k in keys: + collector = self.agent_collectors[k] + buffers[k] = collector.buffers + # Use one agent's buffer_structs (they should all be the same). + buffer_structs = self.agent_collectors[keys[0]].buffer_structs + + input_dict = {} + for view_col, view_req in policy.view_requirements.items(): + # Not used for action computations. + if not view_req.used_for_compute_actions: + continue + + # Create the batch of data from the different buffers. + data_col = view_req.data_col or view_col + delta = ( + -1 + if data_col + in [ + SampleBatch.OBS, + SampleBatch.INFOS, + SampleBatch.ENV_ID, + SampleBatch.EPS_ID, + SampleBatch.AGENT_INDEX, + SampleBatch.T, + ] + else 0 + ) + # Range of shifts, e.g. "-100:0". Note: This includes index 0! + if view_req.shift_from is not None: + time_indices = (view_req.shift_from + delta, view_req.shift_to + delta) + # Single shift (e.g. -1) or list of shifts, e.g. [-4, -1, 0]. + else: + time_indices = view_req.shift + delta + + # Loop through agents and add up their data (batch). + data = None + for k in keys: + # Buffer for the data does not exist yet: Create dummy + # (zero) data. + if data_col not in buffers[k]: + if view_req.data_col is not None: + space = policy.view_requirements[view_req.data_col].space + else: + space = view_req.space + + if isinstance(space, Space): + fill_value = get_dummy_batch_for_space( + space, + batch_size=0, + ) + else: + fill_value = space + + self.agent_collectors[k]._build_buffers({data_col: fill_value}) + + if data is None: + data = [[] for _ in range(len(buffers[keys[0]][data_col]))] + + # `shift_from` and `shift_to` are defined: User wants a + # view with some time-range. + if isinstance(time_indices, tuple): + # `shift_to` == -1: Until the end (including(!) the + # last item). + if time_indices[1] == -1: + for d, b in zip(data, buffers[k][data_col]): + d.append(b[time_indices[0] :]) + # `shift_to` != -1: "Normal" range. + else: + for d, b in zip(data, buffers[k][data_col]): + d.append(b[time_indices[0] : time_indices[1] + 1]) + # Single index. + else: + for d, b in zip(data, buffers[k][data_col]): + d.append(b[time_indices]) + + np_data = [np.array(d) for d in data] + if data_col in buffer_structs: + input_dict[view_col] = tree.unflatten_as( + buffer_structs[data_col], np_data + ) + else: + input_dict[view_col] = np_data[0] + + self._reset_inference_calls(policy_id) + + return SampleBatch( + input_dict, + seq_lens=np.ones(batch_size, dtype=np.int32) + if "state_in_0" in input_dict + else None, + ) + + @override(SampleCollector) + def postprocess_episode( + self, + episode, + is_done: bool = False, + check_dones: bool = False, + build: bool = False, + ) -> Union[None, SampleBatch, MultiAgentBatch]: + episode_id = episode.episode_id + policy_collector_group = episode.batch_builder + + # Build SampleBatches for the given episode. + pre_batches = {} + for (eps_id, agent_id), collector in self.agent_collectors.items(): + # Build only if there is data and agent is part of given episode. + if collector.agent_steps == 0 or eps_id != episode_id: + continue + pid = self.agent_key_to_policy_id[(eps_id, agent_id)] + policy = self.policy_map[pid] + pre_batch = collector.build_for_training(policy.view_requirements) + pre_batches[agent_id] = (policy, pre_batch) + + # Apply reward clipping before calling postprocessing functions. + if self.clip_rewards is True: + for _, (_, pre_batch) in pre_batches.items(): + pre_batch["rewards"] = np.sign(pre_batch["rewards"]) + elif self.clip_rewards: + for _, (_, pre_batch) in pre_batches.items(): + pre_batch["rewards"] = np.clip( + pre_batch["rewards"], + a_min=-self.clip_rewards, + a_max=self.clip_rewards, + ) + + post_batches = {} + for agent_id, (_, pre_batch) in pre_batches.items(): + # Entire episode is said to be done. + # Error if no DONE at end of this agent's trajectory. + if is_done and check_dones and not pre_batch.is_terminated_or_truncated(): + raise ValueError( + "Episode {} terminated for all agents, but we still " + "don't have a last observation for agent {} (policy " + "{}). ".format( + episode_id, + agent_id, + self.agent_key_to_policy_id[(episode_id, agent_id)], + ) + + "Please ensure that you include the last observations " + "of all live agents when setting truncated[__all__] or " + "terminated[__all__] to True." + ) + + # Skip a trajectory's postprocessing (and thus using it for training), + # if its agent's info exists and contains the training_enabled=False + # setting (used by our PolicyClients). + last_info = episode.last_info_for(agent_id) + if last_info and not last_info.get("training_enabled", True): + if is_done: + agent_key = (episode_id, agent_id) + del self.agent_key_to_policy_id[agent_key] + del self.agent_collectors[agent_key] + continue + + if len(pre_batches) > 1: + other_batches = pre_batches.copy() + del other_batches[agent_id] + else: + other_batches = {} + pid = self.agent_key_to_policy_id[(episode_id, agent_id)] + policy = self.policy_map[pid] + if not pre_batch.is_single_trajectory(): + raise ValueError( + "Batches sent to postprocessing must be from a single trajectory! " + "TERMINATED & TRUNCATED need to be False everywhere, except the " + "last timestep, which can be either True or False for those keys)!", + pre_batch, + ) + elif len(set(pre_batch[SampleBatch.EPS_ID])) > 1: + episode_ids = set(pre_batch[SampleBatch.EPS_ID]) + raise ValueError( + "Batches sent to postprocessing must only contain steps " + "from a single episode! Your trajectory contains data from " + f"{len(episode_ids)} episodes ({list(episode_ids)}).", + pre_batch, + ) + # Call the Policy's Exploration's postprocess method. + post_batches[agent_id] = pre_batch + if getattr(policy, "exploration", None) is not None: + policy.exploration.postprocess_trajectory( + policy, post_batches[agent_id], policy.get_session() + ) + post_batches[agent_id].set_get_interceptor(None) + post_batches[agent_id] = policy.postprocess_trajectory( + post_batches[agent_id], other_batches, episode + ) + + if log_once("after_post"): + logger.info( + "Trajectory fragment after postprocess_trajectory():\n\n{}\n".format( + summarize(post_batches) + ) + ) + + # Append into policy batches and reset. + from ray.rllib.evaluation.rollout_worker import get_global_worker + + for agent_id, post_batch in sorted(post_batches.items()): + agent_key = (episode_id, agent_id) + pid = self.agent_key_to_policy_id[agent_key] + policy = self.policy_map[pid] + self.callbacks.on_postprocess_trajectory( + worker=get_global_worker(), + episode=episode, + agent_id=agent_id, + policy_id=pid, + policies=self.policy_map, + postprocessed_batch=post_batch, + original_batches=pre_batches, + ) + + # Add the postprocessed SampleBatch to the policy collectors for + # training. + # PID may be a newly added policy. Just confirm we have it in our + # policy map before proceeding with adding a new _PolicyCollector() + # to the group. + if pid not in policy_collector_group.policy_collectors: + assert pid in self.policy_map + policy_collector_group.policy_collectors[pid] = _PolicyCollector(policy) + policy_collector_group.policy_collectors[ + pid + ].add_postprocessed_batch_for_training(post_batch, policy.view_requirements) + + if is_done: + del self.agent_key_to_policy_id[agent_key] + del self.agent_collectors[agent_key] + + if policy_collector_group: + env_steps = self.episode_steps[episode_id] + policy_collector_group.env_steps += env_steps + agent_steps = self.agent_steps[episode_id] + policy_collector_group.agent_steps += agent_steps + + if is_done: + del self.episode_steps[episode_id] + del self.episodes[episode_id] + + if episode_id in self.agent_steps: + del self.agent_steps[episode_id] + else: + assert ( + len(pre_batches) == 0 + ), "Expected the batch to be empty since the episode_id is missing." + # if the key does not exist it means that throughout the episode all + # observations were empty (i.e. there was no agent in the env) + msg = ( + f"Data from episode {episode_id} does not show any agent " + f"interactions. Hint: Make sure for at least one timestep in the " + f"episode, env.step() returns non-empty values." + ) + raise ValueError(msg) + + # Make PolicyCollectorGroup available for more agent batches in + # other episodes. Do not reset count to 0. + if policy_collector_group: + self.policy_collector_groups.append(policy_collector_group) + else: + self.episode_steps[episode_id] = self.agent_steps[episode_id] = 0 + + # Build a MultiAgentBatch from the episode and return. + if build: + return self._build_multi_agent_batch(episode) + + def _build_multi_agent_batch(self, episode) -> Union[MultiAgentBatch, SampleBatch]: + + ma_batch = {} + for pid, collector in episode.batch_builder.policy_collectors.items(): + if collector.agent_steps > 0: + ma_batch[pid] = collector.build() + + # TODO(sven): We should always return the same type here (MultiAgentBatch), + # no matter what. Just have to unify our `training_step` methods, then. This + # will reduce a lot of confusion about what comes out of the sampling process. + # Create the batch. + ma_batch = MultiAgentBatch.wrap_as_needed( + ma_batch, env_steps=episode.batch_builder.env_steps + ) + + # PolicyCollectorGroup is empty. + episode.batch_builder.env_steps = 0 + episode.batch_builder.agent_steps = 0 + + return ma_batch + + @override(SampleCollector) + def try_build_truncated_episode_multi_agent_batch( + self, + ) -> List[Union[MultiAgentBatch, SampleBatch]]: + batches = [] + # Loop through ongoing episodes and see whether their length plus + # what's already in the policy collectors reaches the fragment-len + # (abiding to the unit used: env-steps or agent-steps). + for episode_id, episode in self.episodes.items(): + # Measure batch size in env-steps. + if self.count_steps_by == "env_steps": + built_steps = ( + episode.batch_builder.env_steps if episode.batch_builder else 0 + ) + ongoing_steps = self.episode_steps[episode_id] + # Measure batch-size in agent-steps. + else: + built_steps = ( + episode.batch_builder.agent_steps if episode.batch_builder else 0 + ) + ongoing_steps = self.agent_steps[episode_id] + + # Reached the fragment-len -> We should build an MA-Batch. + if built_steps + ongoing_steps >= self.rollout_fragment_length: + if self.count_steps_by == "env_steps": + assert built_steps + ongoing_steps == self.rollout_fragment_length + # If we reached the fragment-len only because of `episode_id` + # (still ongoing) -> postprocess `episode_id` first. + if built_steps < self.rollout_fragment_length: + self.postprocess_episode(episode, is_done=False) + # If there is a builder for this episode, + # build the MA-batch and add to return values. + if episode.batch_builder: + batch = self._build_multi_agent_batch(episode=episode) + batches.append(batch) + # No batch-builder: + # We have reached the rollout-fragment length w/o any agent + # steps! Warn that the environment may never request any + # actions from any agents. + elif log_once("no_agent_steps"): + logger.warning( + "Your environment seems to be stepping w/o ever " + "emitting agent observations (agents are never " + "requested to act)!" + ) + + return batches + + def _add_to_next_inference_call(self, agent_key: Tuple[EpisodeID, AgentID]) -> None: + """Adds an Agent key (episode+agent IDs) to the next inference call. + + This makes sure that the agent's current data (in the trajectory) is + used for generating the next input_dict for a + `Policy.compute_actions()` call. + + Args: + agent_key (Tuple[EpisodeID, AgentID]: A unique agent key (across + vectorized environments). + """ + pid = self.agent_key_to_policy_id[agent_key] + + # PID may be a newly added policy (added on the fly during training). + # Just confirm we have it in our policy map before proceeding with + # forward_pass_size=0. + if pid not in self.forward_pass_size: + assert pid in self.policy_map + self.forward_pass_size[pid] = 0 + self.forward_pass_agent_keys[pid] = [] + + idx = self.forward_pass_size[pid] + assert idx >= 0 + if idx == 0: + self.forward_pass_agent_keys[pid].clear() + + self.forward_pass_agent_keys[pid].append(agent_key) + self.forward_pass_size[pid] += 1 + + def _reset_inference_calls(self, policy_id: PolicyID) -> None: + """Resets internal inference input-dict registries. + + Calling `self.get_inference_input_dict()` after this method is called + would return an empty input-dict. + + Args: + policy_id: The policy ID for which to reset the + inference pointers. + """ + self.forward_pass_size[policy_id] = 0 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b18352ce28a9aaf9dba63004b66c56065415747 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/centralized_critic.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/centralized_critic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e5134b74522b61de9c91e908af0827760c1e8b8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/centralized_critic.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/compute_adapted_gae_on_postprocess_trajectory.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/compute_adapted_gae_on_postprocess_trajectory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5ac6e6153287f3bfa85f0fa82bf6faa7045fc27 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/compute_adapted_gae_on_postprocess_trajectory.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/quadx_waypoints.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/quadx_waypoints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a593bfaf19bdcc8ad5267825b1ff7086c9d21195 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/quadx_waypoints.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/replay_buffer_api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/replay_buffer_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4c6cf5e04edf8eb96a4401aad30d98ecc24d079 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__pycache__/replay_buffer_api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71e69f3e2a6cb11687337d207561b7acbd0c093f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/attention_net_supervised.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/attention_net_supervised.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..193d13a4d3134599a3f6abcccf317ea46d08ac86 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/attention_net_supervised.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dbed31cbdf1048d27ca50ea7e029113ac632110 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole_embeddings_learnt_by_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole_embeddings_learnt_by_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b06eccf4c42a22741138cf8b31b78887adc7dff Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole_embeddings_learnt_by_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/attention_net_supervised.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/attention_net_supervised.py new file mode 100644 index 0000000000000000000000000000000000000000..2c0f13f506aa5f5a04d31a323df6b6213c3a83e1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/attention_net_supervised.py @@ -0,0 +1,77 @@ +# @OldAPIStack +from gymnasium.spaces import Box, Discrete +import numpy as np + +from rllib.models.tf.attention_net import TrXLNet +from ray.rllib.utils.framework import try_import_tf + +tf1, tf, tfv = try_import_tf() + + +def bit_shift_generator(seq_length, shift, batch_size): + while True: + values = np.array([0.0, 1.0], dtype=np.float32) + seq = np.random.choice(values, (batch_size, seq_length, 1)) + targets = np.squeeze(np.roll(seq, shift, axis=1).astype(np.int32)) + targets[:, :shift] = 0 + yield seq, targets + + +def train_loss(targets, outputs): + loss = tf.nn.sparse_softmax_cross_entropy_with_logits( + labels=targets, logits=outputs + ) + return tf.reduce_mean(loss) + + +def train_bit_shift(seq_length, num_iterations, print_every_n): + + optimizer = tf.keras.optimizers.Adam(1e-3) + + model = TrXLNet( + observation_space=Box(low=0, high=1, shape=(1,), dtype=np.int32), + action_space=Discrete(2), + num_outputs=2, + model_config={"max_seq_len": seq_length}, + name="trxl", + num_transformer_units=1, + attention_dim=10, + num_heads=5, + head_dim=20, + position_wise_mlp_dim=20, + ) + + shift = 10 + train_batch = 10 + test_batch = 100 + data_gen = bit_shift_generator(seq_length, shift=shift, batch_size=train_batch) + test_gen = bit_shift_generator(seq_length, shift=shift, batch_size=test_batch) + + @tf.function + def update_step(inputs, targets): + model_out = model( + {"obs": inputs}, + state=[tf.reshape(inputs, [-1, seq_length, 1])], + seq_lens=np.full(shape=(train_batch,), fill_value=seq_length), + ) + optimizer.minimize( + lambda: train_loss(targets, model_out), lambda: model.trainable_variables + ) + + for i, (inputs, targets) in zip(range(num_iterations), data_gen): + inputs_in = np.reshape(inputs, [-1, 1]) + targets_in = np.reshape(targets, [-1]) + update_step(tf.convert_to_tensor(inputs_in), tf.convert_to_tensor(targets_in)) + + if i % print_every_n == 0: + test_inputs, test_targets = next(test_gen) + print(i, train_loss(test_targets, model(test_inputs))) + + +if __name__ == "__main__": + tf.enable_eager_execution() + train_bit_shift( + seq_length=20, + num_iterations=2000, + print_every_n=200, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d41f24377ac043976fdd6430dbb7d55ce2d04a2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/action_mask_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/action_mask_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b182b628b44565060c43dc35cfe83d5b9873e88 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/action_mask_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/autoregressive_action_dist.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/autoregressive_action_dist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..491f55d97e5c981c0a54033b4e8187aa68cc00e1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/autoregressive_action_dist.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/autoregressive_action_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/autoregressive_action_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9f859fc3068986a93e3c703fbfff27dbc23ca4e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/autoregressive_action_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/centralized_critic_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/centralized_critic_models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e46dd6e876b7526112e4b0956c9bb036e84570ed Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/centralized_critic_models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_loss_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_loss_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccde2bb9823004423f901cf09e83bd1039315bcd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_loss_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/fast_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/fast_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b74b93c1b1c18eece983331162f26abb8fb72d1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/fast_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_encoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..754febaa0f5c88235baf8e5d4d89deacf8f0f195 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_encoder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_with_lstm_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_with_lstm_models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdd51502de9db41d9686d5fbd07231da6420ea62 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_with_lstm_models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/neural_computer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/neural_computer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80b354f554d3778cef95a836b982657985bcd7d9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/neural_computer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/parametric_actions_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/parametric_actions_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97359a39b3c82cc2ca27037b10d513e67e2c855c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/parametric_actions_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/shared_weights_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/shared_weights_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ac5b5646e414dff78e40bc1de5786b5c26e900c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/shared_weights_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/simple_rpg_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/simple_rpg_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92a81b21d1da514947c9686e214dc8d2f0d0a5a4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/simple_rpg_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/action_mask_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/action_mask_model.py new file mode 100644 index 0000000000000000000000000000000000000000..92fe99e53847ef5f801cc94dc7e30a2f28838ffc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/action_mask_model.py @@ -0,0 +1,126 @@ +# @OldAPIStack +from gymnasium.spaces import Dict + +from ray.rllib.models.tf.fcnet import FullyConnectedNetwork +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.torch_utils import FLOAT_MIN + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class ActionMaskModel(TFModelV2): + """Model that handles simple discrete action masking. + + This assumes the outputs are logits for a single Categorical action dist. + Getting this to work with a more complex output (e.g., if the action space + is a tuple of several distributions) is also possible but left as an + exercise to the reader. + """ + + def __init__( + self, obs_space, action_space, num_outputs, model_config, name, **kwargs + ): + + orig_space = getattr(obs_space, "original_space", obs_space) + assert ( + isinstance(orig_space, Dict) + and "action_mask" in orig_space.spaces + and "observations" in orig_space.spaces + ) + + super().__init__(obs_space, action_space, num_outputs, model_config, name) + + self.internal_model = FullyConnectedNetwork( + orig_space["observations"], + action_space, + num_outputs, + model_config, + name + "_internal", + ) + + # disable action masking --> will likely lead to invalid actions + self.no_masking = model_config["custom_model_config"].get("no_masking", False) + + def forward(self, input_dict, state, seq_lens): + # Extract the available actions tensor from the observation. + action_mask = input_dict["obs"]["action_mask"] + + # Compute the unmasked logits. + logits, _ = self.internal_model({"obs": input_dict["obs"]["observations"]}) + + # If action masking is disabled, directly return unmasked logits + if self.no_masking: + return logits, state + + # Convert action_mask into a [0.0 || -inf]-type mask. + inf_mask = tf.maximum(tf.math.log(action_mask), tf.float32.min) + masked_logits = logits + inf_mask + + # Return masked logits. + return masked_logits, state + + def value_function(self): + return self.internal_model.value_function() + + +class TorchActionMaskModel(TorchModelV2, nn.Module): + """PyTorch version of above ActionMaskingModel.""" + + def __init__( + self, + obs_space, + action_space, + num_outputs, + model_config, + name, + **kwargs, + ): + orig_space = getattr(obs_space, "original_space", obs_space) + assert ( + isinstance(orig_space, Dict) + and "action_mask" in orig_space.spaces + and "observations" in orig_space.spaces + ) + + TorchModelV2.__init__( + self, obs_space, action_space, num_outputs, model_config, name, **kwargs + ) + nn.Module.__init__(self) + + self.internal_model = TorchFC( + orig_space["observations"], + action_space, + num_outputs, + model_config, + name + "_internal", + ) + + # disable action masking --> will likely lead to invalid actions + self.no_masking = False + if "no_masking" in model_config["custom_model_config"]: + self.no_masking = model_config["custom_model_config"]["no_masking"] + + def forward(self, input_dict, state, seq_lens): + # Extract the available actions tensor from the observation. + action_mask = input_dict["obs"]["action_mask"] + + # Compute the unmasked logits. + logits, _ = self.internal_model({"obs": input_dict["obs"]["observations"]}) + + # If action masking is disabled, directly return unmasked logits + if self.no_masking: + return logits, state + + # Convert action_mask into a [0.0 || -inf]-type mask. + inf_mask = torch.clamp(torch.log(action_mask), min=FLOAT_MIN) + masked_logits = logits + inf_mask + + # Return masked logits. + return masked_logits, state + + def value_function(self): + return self.internal_model.value_function() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/autoregressive_action_dist.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/autoregressive_action_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8f2d53f7789d5a1f670361c10b041123664ab7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/autoregressive_action_dist.py @@ -0,0 +1,149 @@ +# @OldAPIStack +from ray.rllib.models.tf.tf_action_dist import Categorical, ActionDistribution +from ray.rllib.models.torch.torch_action_dist import ( + TorchCategorical, + TorchDistributionWrapper, +) +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class BinaryAutoregressiveDistribution(ActionDistribution): + """Action distribution P(a1, a2) = P(a1) * P(a2 | a1)""" + + def deterministic_sample(self): + # First, sample a1. + a1_dist = self._a1_distribution() + a1 = a1_dist.deterministic_sample() + + # Sample a2 conditioned on a1. + a2_dist = self._a2_distribution(a1) + a2 = a2_dist.deterministic_sample() + self._action_logp = a1_dist.logp(a1) + a2_dist.logp(a2) + + # Return the action tuple. + return (a1, a2) + + def sample(self): + # First, sample a1. + a1_dist = self._a1_distribution() + a1 = a1_dist.sample() + + # Sample a2 conditioned on a1. + a2_dist = self._a2_distribution(a1) + a2 = a2_dist.sample() + self._action_logp = a1_dist.logp(a1) + a2_dist.logp(a2) + + # Return the action tuple. + return (a1, a2) + + def logp(self, actions): + a1, a2 = actions[:, 0], actions[:, 1] + a1_vec = tf.expand_dims(tf.cast(a1, tf.float32), 1) + a1_logits, a2_logits = self.model.action_model([self.inputs, a1_vec]) + return Categorical(a1_logits).logp(a1) + Categorical(a2_logits).logp(a2) + + def sampled_action_logp(self): + return self._action_logp + + def entropy(self): + a1_dist = self._a1_distribution() + a2_dist = self._a2_distribution(a1_dist.sample()) + return a1_dist.entropy() + a2_dist.entropy() + + def kl(self, other): + a1_dist = self._a1_distribution() + a1_terms = a1_dist.kl(other._a1_distribution()) + + a1 = a1_dist.sample() + a2_terms = self._a2_distribution(a1).kl(other._a2_distribution(a1)) + return a1_terms + a2_terms + + def _a1_distribution(self): + BATCH = tf.shape(self.inputs)[0] + a1_logits, _ = self.model.action_model([self.inputs, tf.zeros((BATCH, 1))]) + a1_dist = Categorical(a1_logits) + return a1_dist + + def _a2_distribution(self, a1): + a1_vec = tf.expand_dims(tf.cast(a1, tf.float32), 1) + _, a2_logits = self.model.action_model([self.inputs, a1_vec]) + a2_dist = Categorical(a2_logits) + return a2_dist + + @staticmethod + def required_model_output_shape(action_space, model_config): + return 16 # controls model output feature vector size + + +class TorchBinaryAutoregressiveDistribution(TorchDistributionWrapper): + """Action distribution P(a1, a2) = P(a1) * P(a2 | a1)""" + + def deterministic_sample(self): + # First, sample a1. + a1_dist = self._a1_distribution() + a1 = a1_dist.deterministic_sample() + + # Sample a2 conditioned on a1. + a2_dist = self._a2_distribution(a1) + a2 = a2_dist.deterministic_sample() + self._action_logp = a1_dist.logp(a1) + a2_dist.logp(a2) + + # Return the action tuple. + return (a1, a2) + + def sample(self): + # First, sample a1. + a1_dist = self._a1_distribution() + a1 = a1_dist.sample() + + # Sample a2 conditioned on a1. + a2_dist = self._a2_distribution(a1) + a2 = a2_dist.sample() + self._action_logp = a1_dist.logp(a1) + a2_dist.logp(a2) + + # Return the action tuple. + return (a1, a2) + + def logp(self, actions): + a1, a2 = actions[:, 0], actions[:, 1] + a1_vec = torch.unsqueeze(a1.float(), 1) + a1_logits, a2_logits = self.model.action_module(self.inputs, a1_vec) + return TorchCategorical(a1_logits).logp(a1) + TorchCategorical(a2_logits).logp( + a2 + ) + + def sampled_action_logp(self): + return self._action_logp + + def entropy(self): + a1_dist = self._a1_distribution() + a2_dist = self._a2_distribution(a1_dist.sample()) + return a1_dist.entropy() + a2_dist.entropy() + + def kl(self, other): + a1_dist = self._a1_distribution() + a1_terms = a1_dist.kl(other._a1_distribution()) + + a1 = a1_dist.sample() + a2_terms = self._a2_distribution(a1).kl(other._a2_distribution(a1)) + return a1_terms + a2_terms + + def _a1_distribution(self): + BATCH = self.inputs.shape[0] + zeros = torch.zeros((BATCH, 1)).to(self.inputs.device) + a1_logits, _ = self.model.action_module(self.inputs, zeros) + a1_dist = TorchCategorical(a1_logits) + return a1_dist + + def _a2_distribution(self, a1): + a1_vec = torch.unsqueeze(a1.float(), 1) + _, a2_logits = self.model.action_module(self.inputs, a1_vec) + a2_dist = TorchCategorical(a2_logits) + return a2_dist + + @staticmethod + def required_model_output_shape(action_space, model_config): + return 16 # controls model output feature vector size diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/autoregressive_action_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/autoregressive_action_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8b71e5ab9dc28bbb9bd5f39767350ab51639ea27 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/autoregressive_action_model.py @@ -0,0 +1,162 @@ +# @OldAPIStack +from gymnasium.spaces import Discrete, Tuple + +from ray.rllib.models.tf.misc import normc_initializer +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.torch.misc import normc_initializer as normc_init_torch +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class AutoregressiveActionModel(TFModelV2): + """Implements the `.action_model` branch required above.""" + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + super(AutoregressiveActionModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + if action_space != Tuple([Discrete(2), Discrete(2)]): + raise ValueError("This model only supports the [2, 2] action space") + + # Inputs + obs_input = tf.keras.layers.Input(shape=obs_space.shape, name="obs_input") + a1_input = tf.keras.layers.Input(shape=(1,), name="a1_input") + ctx_input = tf.keras.layers.Input(shape=(num_outputs,), name="ctx_input") + + # Output of the model (normally 'logits', but for an autoregressive + # dist this is more like a context/feature layer encoding the obs) + context = tf.keras.layers.Dense( + num_outputs, + name="hidden", + activation=tf.nn.tanh, + kernel_initializer=normc_initializer(1.0), + )(obs_input) + + # V(s) + value_out = tf.keras.layers.Dense( + 1, + name="value_out", + activation=None, + kernel_initializer=normc_initializer(0.01), + )(context) + + # P(a1 | obs) + a1_logits = tf.keras.layers.Dense( + 2, + name="a1_logits", + activation=None, + kernel_initializer=normc_initializer(0.01), + )(ctx_input) + + # P(a2 | a1) + # --note: typically you'd want to implement P(a2 | a1, obs) as follows: + # a2_context = tf.keras.layers.Concatenate(axis=1)( + # [ctx_input, a1_input]) + a2_context = a1_input + a2_hidden = tf.keras.layers.Dense( + 16, + name="a2_hidden", + activation=tf.nn.tanh, + kernel_initializer=normc_initializer(1.0), + )(a2_context) + a2_logits = tf.keras.layers.Dense( + 2, + name="a2_logits", + activation=None, + kernel_initializer=normc_initializer(0.01), + )(a2_hidden) + + # Base layers + self.base_model = tf.keras.Model(obs_input, [context, value_out]) + self.base_model.summary() + + # Autoregressive action sampler + self.action_model = tf.keras.Model( + [ctx_input, a1_input], [a1_logits, a2_logits] + ) + self.action_model.summary() + + def forward(self, input_dict, state, seq_lens): + context, self._value_out = self.base_model(input_dict["obs"]) + return context, state + + def value_function(self): + return tf.reshape(self._value_out, [-1]) + + +class TorchAutoregressiveActionModel(TorchModelV2, nn.Module): + """PyTorch version of the AutoregressiveActionModel above.""" + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + TorchModelV2.__init__( + self, obs_space, action_space, num_outputs, model_config, name + ) + nn.Module.__init__(self) + + if action_space != Tuple([Discrete(2), Discrete(2)]): + raise ValueError("This model only supports the [2, 2] action space") + + # Output of the model (normally 'logits', but for an autoregressive + # dist this is more like a context/feature layer encoding the obs) + self.context_layer = SlimFC( + in_size=obs_space.shape[0], + out_size=num_outputs, + initializer=normc_init_torch(1.0), + activation_fn=nn.Tanh, + ) + + # V(s) + self.value_branch = SlimFC( + in_size=num_outputs, + out_size=1, + initializer=normc_init_torch(0.01), + activation_fn=None, + ) + + # P(a1 | obs) + self.a1_logits = SlimFC( + in_size=num_outputs, + out_size=2, + activation_fn=None, + initializer=normc_init_torch(0.01), + ) + + class _ActionModel(nn.Module): + def __init__(self): + nn.Module.__init__(self) + self.a2_hidden = SlimFC( + in_size=1, + out_size=16, + activation_fn=nn.Tanh, + initializer=normc_init_torch(1.0), + ) + self.a2_logits = SlimFC( + in_size=16, + out_size=2, + activation_fn=None, + initializer=normc_init_torch(0.01), + ) + + def forward(self_, ctx_input, a1_input): + a1_logits = self.a1_logits(ctx_input) + a2_logits = self_.a2_logits(self_.a2_hidden(a1_input)) + return a1_logits, a2_logits + + # P(a2 | a1) + # --note: typically you'd want to implement P(a2 | a1, obs) as follows: + # a2_context = tf.keras.layers.Concatenate(axis=1)( + # [ctx_input, a1_input]) + self.action_module = _ActionModel() + + self._context = None + + def forward(self, input_dict, state, seq_lens): + self._context = self.context_layer(input_dict["obs"]) + return self._context, state + + def value_function(self): + return torch.reshape(self.value_branch(self._context), [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/centralized_critic_models.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/centralized_critic_models.py new file mode 100644 index 0000000000000000000000000000000000000000..5ccc4448e5428f466ea79d858a9e5cc835dc7959 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/centralized_critic_models.py @@ -0,0 +1,182 @@ +# @OldAPIStack +from gymnasium.spaces import Box + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.tf.fcnet import FullyConnectedNetwork +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class CentralizedCriticModel(TFModelV2): + """Multi-agent model that implements a centralized value function.""" + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + super(CentralizedCriticModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + # Base of the model + self.model = FullyConnectedNetwork( + obs_space, action_space, num_outputs, model_config, name + ) + + # Central VF maps (obs, opp_obs, opp_act) -> vf_pred + obs = tf.keras.layers.Input(shape=(6,), name="obs") + opp_obs = tf.keras.layers.Input(shape=(6,), name="opp_obs") + opp_act = tf.keras.layers.Input(shape=(2,), name="opp_act") + concat_obs = tf.keras.layers.Concatenate(axis=1)([obs, opp_obs, opp_act]) + central_vf_dense = tf.keras.layers.Dense( + 16, activation=tf.nn.tanh, name="c_vf_dense" + )(concat_obs) + central_vf_out = tf.keras.layers.Dense(1, activation=None, name="c_vf_out")( + central_vf_dense + ) + self.central_vf = tf.keras.Model( + inputs=[obs, opp_obs, opp_act], outputs=central_vf_out + ) + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + return self.model.forward(input_dict, state, seq_lens) + + def central_value_function(self, obs, opponent_obs, opponent_actions): + return tf.reshape( + self.central_vf( + [obs, opponent_obs, tf.one_hot(tf.cast(opponent_actions, tf.int32), 2)] + ), + [-1], + ) + + @override(ModelV2) + def value_function(self): + return self.model.value_function() # not used + + +class YetAnotherCentralizedCriticModel(TFModelV2): + """Multi-agent model that implements a centralized value function. + + It assumes the observation is a dict with 'own_obs' and 'opponent_obs', the + former of which can be used for computing actions (i.e., decentralized + execution), and the latter for optimization (i.e., centralized learning). + + This model has two parts: + - An action model that looks at just 'own_obs' to compute actions + - A value model that also looks at the 'opponent_obs' / 'opponent_action' + to compute the value (it does this by using the 'obs_flat' tensor). + """ + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + super(YetAnotherCentralizedCriticModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + + self.action_model = FullyConnectedNetwork( + Box(low=0, high=1, shape=(6,)), # one-hot encoded Discrete(6) + action_space, + num_outputs, + model_config, + name + "_action", + ) + + self.value_model = FullyConnectedNetwork( + obs_space, action_space, 1, model_config, name + "_vf" + ) + + def forward(self, input_dict, state, seq_lens): + self._value_out, _ = self.value_model( + {"obs": input_dict["obs_flat"]}, state, seq_lens + ) + return self.action_model({"obs": input_dict["obs"]["own_obs"]}, state, seq_lens) + + def value_function(self): + return tf.reshape(self._value_out, [-1]) + + +class TorchCentralizedCriticModel(TorchModelV2, nn.Module): + """Multi-agent model that implements a centralized VF.""" + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + TorchModelV2.__init__( + self, obs_space, action_space, num_outputs, model_config, name + ) + nn.Module.__init__(self) + + # Base of the model + self.model = TorchFC(obs_space, action_space, num_outputs, model_config, name) + + # Central VF maps (obs, opp_obs, opp_act) -> vf_pred + input_size = 6 + 6 + 2 # obs + opp_obs + opp_act + self.central_vf = nn.Sequential( + SlimFC(input_size, 16, activation_fn=nn.Tanh), + SlimFC(16, 1), + ) + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + model_out, _ = self.model(input_dict, state, seq_lens) + return model_out, [] + + def central_value_function(self, obs, opponent_obs, opponent_actions): + input_ = torch.cat( + [ + obs, + opponent_obs, + torch.nn.functional.one_hot(opponent_actions.long(), 2).float(), + ], + 1, + ) + return torch.reshape(self.central_vf(input_), [-1]) + + @override(ModelV2) + def value_function(self): + return self.model.value_function() # not used + + +class YetAnotherTorchCentralizedCriticModel(TorchModelV2, nn.Module): + """Multi-agent model that implements a centralized value function. + + It assumes the observation is a dict with 'own_obs' and 'opponent_obs', the + former of which can be used for computing actions (i.e., decentralized + execution), and the latter for optimization (i.e., centralized learning). + + This model has two parts: + - An action model that looks at just 'own_obs' to compute actions + - A value model that also looks at the 'opponent_obs' / 'opponent_action' + to compute the value (it does this by using the 'obs_flat' tensor). + """ + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + TorchModelV2.__init__( + self, obs_space, action_space, num_outputs, model_config, name + ) + nn.Module.__init__(self) + + self.action_model = TorchFC( + Box(low=0, high=1, shape=(6,)), # one-hot encoded Discrete(6) + action_space, + num_outputs, + model_config, + name + "_action", + ) + + self.value_model = TorchFC( + obs_space, action_space, 1, model_config, name + "_vf" + ) + self._model_in = None + + def forward(self, input_dict, state, seq_lens): + # Store model-input for possible `value_function()` call. + self._model_in = [input_dict["obs_flat"], state, seq_lens] + return self.action_model({"obs": input_dict["obs"]["own_obs"]}, state, seq_lens) + + def value_function(self): + value_out, _ = self.value_model( + {"obs": self._model_in[0]}, self._model_in[1], self._model_in[2] + ) + return torch.reshape(value_out, [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/custom_loss_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/custom_loss_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8e3636c0c6520d25c6f27e46bd1ad56add30500b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/custom_loss_model.py @@ -0,0 +1,137 @@ +import numpy as np + +from ray.rllib.models.modelv2 import ModelV2, restore_original_dimensions +from ray.rllib.models.tf.tf_action_dist import Categorical +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.tf.fcnet import FullyConnectedNetwork +from ray.rllib.models.torch.torch_action_dist import TorchCategorical +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.offline import JsonReader + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class CustomLossModel(TFModelV2): + """Custom model that adds an imitation loss on top of the policy loss.""" + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + super().__init__(obs_space, action_space, num_outputs, model_config, name) + + self.fcnet = FullyConnectedNetwork( + self.obs_space, self.action_space, num_outputs, model_config, name="fcnet" + ) + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + # Delegate to our FCNet. + return self.fcnet(input_dict, state, seq_lens) + + @override(ModelV2) + def value_function(self): + # Delegate to our FCNet. + return self.fcnet.value_function() + + @override(ModelV2) + def custom_loss(self, policy_loss, loss_inputs): + # Create a new input reader per worker. + reader = JsonReader(self.model_config["custom_model_config"]["input_files"]) + input_ops = reader.tf_input_ops() + + # Define a secondary loss by building a graph copy with weight sharing. + obs = restore_original_dimensions( + tf.cast(input_ops["obs"], tf.float32), self.obs_space + ) + logits, _ = self.forward({"obs": obs}, [], None) + + # Compute the IL loss. + action_dist = Categorical(logits, self.model_config) + self.policy_loss = policy_loss + self.imitation_loss = tf.reduce_mean(-action_dist.logp(input_ops["actions"])) + return policy_loss + 10 * self.imitation_loss + + def metrics(self): + return { + "policy_loss": self.policy_loss, + "imitation_loss": self.imitation_loss, + } + + +class TorchCustomLossModel(TorchModelV2, nn.Module): + """PyTorch version of the CustomLossModel above.""" + + def __init__( + self, obs_space, action_space, num_outputs, model_config, name, input_files + ): + super().__init__(obs_space, action_space, num_outputs, model_config, name) + nn.Module.__init__(self) + + self.input_files = input_files + # Create a new input reader per worker. + self.reader = JsonReader(self.input_files) + self.fcnet = TorchFC( + self.obs_space, self.action_space, num_outputs, model_config, name="fcnet" + ) + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + # Delegate to our FCNet. + return self.fcnet(input_dict, state, seq_lens) + + @override(ModelV2) + def value_function(self): + # Delegate to our FCNet. + return self.fcnet.value_function() + + @override(ModelV2) + def custom_loss(self, policy_loss, loss_inputs): + """Calculates a custom loss on top of the given policy_loss(es). + + Args: + policy_loss (List[TensorType]): The list of already calculated + policy losses (as many as there are optimizers). + loss_inputs: Struct of np.ndarrays holding the + entire train batch. + + Returns: + List[TensorType]: The altered list of policy losses. In case the + custom loss should have its own optimizer, make sure the + returned list is one larger than the incoming policy_loss list. + In case you simply want to mix in the custom loss into the + already calculated policy losses, return a list of altered + policy losses (as done in this example below). + """ + # Get the next batch from our input files. + batch = self.reader.next() + + # Define a secondary loss by building a graph copy with weight sharing. + obs = restore_original_dimensions( + torch.from_numpy(batch["obs"]).float().to(policy_loss[0].device), + self.obs_space, + tensorlib="torch", + ) + logits, _ = self.forward({"obs": obs}, [], None) + + # Compute the IL loss. + action_dist = TorchCategorical(logits, self.model_config) + imitation_loss = torch.mean( + -action_dist.logp( + torch.from_numpy(batch["actions"]).to(policy_loss[0].device) + ) + ) + self.imitation_loss_metric = imitation_loss.item() + self.policy_loss_metric = np.mean([loss.item() for loss in policy_loss]) + + # Add the imitation loss to each already calculated policy loss term. + # Alternatively (if custom loss has its own optimizer): + # return policy_loss + [10 * self.imitation_loss] + return [loss_ + 10 * imitation_loss for loss_ in policy_loss] + + def metrics(self): + return { + "policy_loss": self.policy_loss_metric, + "imitation_loss": self.imitation_loss_metric, + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/fast_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/fast_model.py new file mode 100644 index 0000000000000000000000000000000000000000..99ac7e83a7de342b24aeca1949a77730598c38e9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/fast_model.py @@ -0,0 +1,80 @@ +# @OldAPIStack +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class FastModel(TFModelV2): + """An example for a non-Keras ModelV2 in tf that learns a single weight. + + Defines all network architecture in `forward` (not `__init__` as it's + usually done for Keras-style TFModelV2s). + """ + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + super().__init__(obs_space, action_space, num_outputs, model_config, name) + # Have we registered our vars yet (see `forward`)? + self._registered = False + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + with tf1.variable_scope("model", reuse=tf1.AUTO_REUSE): + bias = tf1.get_variable( + dtype=tf.float32, + name="bias", + initializer=tf.keras.initializers.Zeros(), + shape=(), + ) + output = bias + tf.zeros([tf.shape(input_dict["obs"])[0], self.num_outputs]) + self._value_out = tf.reduce_mean(output, -1) # fake value + + if not self._registered: + self.register_variables( + tf1.get_collection( + tf1.GraphKeys.TRAINABLE_VARIABLES, scope=".+/model/.+" + ) + ) + self._registered = True + + return output, [] + + @override(ModelV2) + def value_function(self): + return tf.reshape(self._value_out, [-1]) + + +class TorchFastModel(TorchModelV2, nn.Module): + """Torch version of FastModel (tf).""" + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + TorchModelV2.__init__( + self, obs_space, action_space, num_outputs, model_config, name + ) + nn.Module.__init__(self) + + self.bias = nn.Parameter( + torch.tensor([0.0], dtype=torch.float32, requires_grad=True) + ) + + # Only needed to give some params to the optimizer (even though, + # they are never used anywhere). + self.dummy_layer = SlimFC(1, 1) + self._output = None + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + self._output = self.bias + torch.zeros( + size=(input_dict["obs"].shape[0], self.num_outputs) + ).to(self.bias.device) + return self._output, [] + + @override(ModelV2) + def value_function(self): + assert self._output is not None, "must call forward first!" + return torch.reshape(torch.mean(self._output, -1), [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/mobilenet_v2_encoder.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/mobilenet_v2_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..34baf73f4ef53d433d3ee439f7b6a41a2560cdc5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/mobilenet_v2_encoder.py @@ -0,0 +1,48 @@ +# @OldAPIStack +""" +This file implements a MobileNet v2 Encoder. +It uses MobileNet v2 to encode images into a latent space of 1000 dimensions. + +Depending on the experiment, the MobileNet v2 encoder layers can be frozen or +unfrozen. This is controlled by the `freeze` parameter in the config. + +This is an example of how a pre-trained neural network can be used as an encoder +in RLlib. You can modify this example to accommodate your own encoder network or +other pre-trained networks. +""" + +from ray.rllib.core.models.base import Encoder, ENCODER_OUT +from ray.rllib.core.models.configs import ModelConfig +from ray.rllib.core.models.torch.base import TorchModel +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + +MOBILENET_INPUT_SHAPE = (3, 224, 224) + + +class MobileNetV2EncoderConfig(ModelConfig): + # MobileNet v2 has a flat output with a length of 1000. + output_dims = (1000,) + freeze = True + + def build(self, framework): + assert framework == "torch", "Unsupported framework `{}`!".format(framework) + return MobileNetV2Encoder(self) + + +class MobileNetV2Encoder(TorchModel, Encoder): + """A MobileNet v2 encoder for RLlib.""" + + def __init__(self, config): + super().__init__(config) + self.net = torch.hub.load( + "pytorch/vision:v0.6.0", "mobilenet_v2", pretrained=True + ) + if config.freeze: + # We don't want to train this encoder, so freeze its parameters! + for p in self.net.parameters(): + p.requires_grad = False + + def _forward(self, input_dict, **kwargs): + return {ENCODER_OUT: (self.net(input_dict["obs"]))} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/mobilenet_v2_with_lstm_models.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/mobilenet_v2_with_lstm_models.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0b310c4ed05a45d7aed65d695c474055df82f5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/mobilenet_v2_with_lstm_models.py @@ -0,0 +1,160 @@ +# @OldAPIStack +import numpy as np + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.recurrent_net import RecurrentNetwork +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.recurrent_net import RecurrentNetwork as TorchRNN +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class MobileV2PlusRNNModel(RecurrentNetwork): + """A conv. + recurrent keras net example using a pre-trained MobileNet.""" + + def __init__( + self, obs_space, action_space, num_outputs, model_config, name, cnn_shape + ): + + super(MobileV2PlusRNNModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + + self.cell_size = 16 + visual_size = cnn_shape[0] * cnn_shape[1] * cnn_shape[2] + + state_in_h = tf.keras.layers.Input(shape=(self.cell_size,), name="h") + state_in_c = tf.keras.layers.Input(shape=(self.cell_size,), name="c") + seq_in = tf.keras.layers.Input(shape=(), name="seq_in", dtype=tf.int32) + + inputs = tf.keras.layers.Input(shape=(None, visual_size), name="visual_inputs") + + input_visual = inputs + input_visual = tf.reshape( + input_visual, [-1, cnn_shape[0], cnn_shape[1], cnn_shape[2]] + ) + cnn_input = tf.keras.layers.Input(shape=cnn_shape, name="cnn_input") + + cnn_model = tf.keras.applications.mobilenet_v2.MobileNetV2( + alpha=1.0, + include_top=True, + weights=None, + input_tensor=cnn_input, + pooling=None, + ) + vision_out = cnn_model(input_visual) + vision_out = tf.reshape( + vision_out, [-1, tf.shape(inputs)[1], vision_out.shape.as_list()[-1]] + ) + + lstm_out, state_h, state_c = tf.keras.layers.LSTM( + self.cell_size, return_sequences=True, return_state=True, name="lstm" + )( + inputs=vision_out, + mask=tf.sequence_mask(seq_in), + initial_state=[state_in_h, state_in_c], + ) + + # Postprocess LSTM output with another hidden layer and compute values. + logits = tf.keras.layers.Dense( + self.num_outputs, activation=tf.keras.activations.linear, name="logits" + )(lstm_out) + values = tf.keras.layers.Dense(1, activation=None, name="values")(lstm_out) + + # Create the RNN model + self.rnn_model = tf.keras.Model( + inputs=[inputs, seq_in, state_in_h, state_in_c], + outputs=[logits, values, state_h, state_c], + ) + self.rnn_model.summary() + + @override(RecurrentNetwork) + def forward_rnn(self, inputs, state, seq_lens): + model_out, self._value_out, h, c = self.rnn_model([inputs, seq_lens] + state) + return model_out, [h, c] + + @override(ModelV2) + def get_initial_state(self): + return [ + np.zeros(self.cell_size, np.float32), + np.zeros(self.cell_size, np.float32), + ] + + @override(ModelV2) + def value_function(self): + return tf.reshape(self._value_out, [-1]) + + +class TorchMobileV2PlusRNNModel(TorchRNN, nn.Module): + """A conv. + recurrent torch net example using a pre-trained MobileNet.""" + + def __init__( + self, obs_space, action_space, num_outputs, model_config, name, cnn_shape + ): + + TorchRNN.__init__( + self, obs_space, action_space, num_outputs, model_config, name + ) + nn.Module.__init__(self) + + self.lstm_state_size = 16 + self.cnn_shape = list(cnn_shape) + self.visual_size_in = cnn_shape[0] * cnn_shape[1] * cnn_shape[2] + # MobileNetV2 has a flat output of (1000,). + self.visual_size_out = 1000 + + # Load the MobileNetV2 from torch.hub. + self.cnn_model = torch.hub.load( + "pytorch/vision:v0.6.0", "mobilenet_v2", pretrained=True + ) + + self.lstm = nn.LSTM( + self.visual_size_out, self.lstm_state_size, batch_first=True + ) + + # Postprocess LSTM output with another hidden layer and compute values. + self.logits = SlimFC(self.lstm_state_size, self.num_outputs) + self.value_branch = SlimFC(self.lstm_state_size, 1) + # Holds the current "base" output (before logits layer). + self._features = None + + @override(TorchRNN) + def forward_rnn(self, inputs, state, seq_lens): + # Create image dims. + vision_in = torch.reshape(inputs, [-1] + self.cnn_shape) + vision_out = self.cnn_model(vision_in) + # Flatten. + vision_out_time_ranked = torch.reshape( + vision_out, [inputs.shape[0], inputs.shape[1], vision_out.shape[-1]] + ) + if len(state[0].shape) == 2: + state[0] = state[0].unsqueeze(0) + state[1] = state[1].unsqueeze(0) + # Forward through LSTM. + self._features, [h, c] = self.lstm(vision_out_time_ranked, state) + # Forward LSTM out through logits layer and value layer. + logits = self.logits(self._features) + return logits, [h.squeeze(0), c.squeeze(0)] + + @override(ModelV2) + def get_initial_state(self): + # Place hidden states on same device as model. + h = [ + list(self.cnn_model.modules())[-1] + .weight.new(1, self.lstm_state_size) + .zero_() + .squeeze(0), + list(self.cnn_model.modules())[-1] + .weight.new(1, self.lstm_state_size) + .zero_() + .squeeze(0), + ] + return h + + @override(ModelV2) + def value_function(self): + assert self._features is not None, "must call forward() first" + return torch.reshape(self.value_branch(self._features), [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/neural_computer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/neural_computer.py new file mode 100644 index 0000000000000000000000000000000000000000..d863f71e62d7426c360cffc73042db3c393a7f78 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/neural_computer.py @@ -0,0 +1,247 @@ +# @OldAPIStack +from collections import OrderedDict +import gymnasium as gym +from typing import Union, Dict, List, Tuple + +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModelConfigDict, TensorType + +try: + from dnc import DNC +except ModuleNotFoundError: + print("dnc module not found. Did you forget to 'pip install dnc'?") + raise + +torch, nn = try_import_torch() + + +class DNCMemory(TorchModelV2, nn.Module): + """Differentiable Neural Computer wrapper around ixaxaar's DNC implementation, + see https://github.com/ixaxaar/pytorch-dnc""" + + DEFAULT_CONFIG = { + "dnc_model": DNC, + # Number of controller hidden layers + "num_hidden_layers": 1, + # Number of weights per controller hidden layer + "hidden_size": 64, + # Number of LSTM units + "num_layers": 1, + # Number of read heads, i.e. how many addrs are read at once + "read_heads": 4, + # Number of memory cells in the controller + "nr_cells": 32, + # Size of each cell + "cell_size": 16, + # LSTM activation function + "nonlinearity": "tanh", + # Observation goes through this torch.nn.Module before + # feeding to the DNC + "preprocessor": torch.nn.Sequential(torch.nn.Linear(64, 64), torch.nn.Tanh()), + # Input size to the preprocessor + "preprocessor_input_size": 64, + # The output size of the preprocessor + # and the input size of the dnc + "preprocessor_output_size": 64, + } + + MEMORY_KEYS = [ + "memory", + "link_matrix", + "precedence", + "read_weights", + "write_weights", + "usage_vector", + ] + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + **custom_model_kwargs, + ): + nn.Module.__init__(self) + super(DNCMemory, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + self.num_outputs = num_outputs + self.obs_dim = gym.spaces.utils.flatdim(obs_space) + self.act_dim = gym.spaces.utils.flatdim(action_space) + + self.cfg = dict(self.DEFAULT_CONFIG, **custom_model_kwargs) + assert ( + self.cfg["num_layers"] == 1 + ), "num_layers != 1 has not been implemented yet" + self.cur_val = None + + self.preprocessor = torch.nn.Sequential( + torch.nn.Linear(self.obs_dim, self.cfg["preprocessor_input_size"]), + self.cfg["preprocessor"], + ) + + self.logit_branch = SlimFC( + in_size=self.cfg["hidden_size"], + out_size=self.num_outputs, + activation_fn=None, + initializer=torch.nn.init.xavier_uniform_, + ) + + self.value_branch = SlimFC( + in_size=self.cfg["hidden_size"], + out_size=1, + activation_fn=None, + initializer=torch.nn.init.xavier_uniform_, + ) + + self.dnc: Union[None, DNC] = None + + def get_initial_state(self) -> List[TensorType]: + ctrl_hidden = [ + torch.zeros(self.cfg["num_hidden_layers"], self.cfg["hidden_size"]), + torch.zeros(self.cfg["num_hidden_layers"], self.cfg["hidden_size"]), + ] + m = self.cfg["nr_cells"] + r = self.cfg["read_heads"] + w = self.cfg["cell_size"] + memory = [ + torch.zeros(m, w), # memory + torch.zeros(1, m, m), # link_matrix + torch.zeros(1, m), # precedence + torch.zeros(r, m), # read_weights + torch.zeros(1, m), # write_weights + torch.zeros(m), # usage_vector + ] + + read_vecs = torch.zeros(w * r) + + state = [*ctrl_hidden, read_vecs, *memory] + assert len(state) == 9 + return state + + def value_function(self) -> TensorType: + assert self.cur_val is not None, "must call forward() first" + return self.cur_val + + def unpack_state( + self, + state: List[TensorType], + ) -> Tuple[List[Tuple[TensorType, TensorType]], Dict[str, TensorType], TensorType]: + """Given a list of tensors, reformat for self.dnc input""" + assert len(state) == 9, "Failed to verify unpacked state" + ctrl_hidden: List[Tuple[TensorType, TensorType]] = [ + ( + state[0].permute(1, 0, 2).contiguous(), + state[1].permute(1, 0, 2).contiguous(), + ) + ] + read_vecs: TensorType = state[2] + memory: List[TensorType] = state[3:] + memory_dict: OrderedDict[str, TensorType] = OrderedDict( + zip(self.MEMORY_KEYS, memory) + ) + + return ctrl_hidden, memory_dict, read_vecs + + def pack_state( + self, + ctrl_hidden: List[Tuple[TensorType, TensorType]], + memory_dict: Dict[str, TensorType], + read_vecs: TensorType, + ) -> List[TensorType]: + """Given the dnc output, pack it into a list of tensors + for rllib state. Order is ctrl_hidden, read_vecs, memory_dict""" + state = [] + ctrl_hidden = [ + ctrl_hidden[0][0].permute(1, 0, 2), + ctrl_hidden[0][1].permute(1, 0, 2), + ] + state += ctrl_hidden + assert len(state) == 2, "Failed to verify packed state" + state.append(read_vecs) + assert len(state) == 3, "Failed to verify packed state" + state += memory_dict.values() + assert len(state) == 9, "Failed to verify packed state" + return state + + def validate_unpack(self, dnc_output, unpacked_state): + """Ensure the unpacked state shapes match the DNC output""" + s_ctrl_hidden, s_memory_dict, s_read_vecs = unpacked_state + ctrl_hidden, memory_dict, read_vecs = dnc_output + + for i in range(len(ctrl_hidden)): + for j in range(len(ctrl_hidden[i])): + assert s_ctrl_hidden[i][j].shape == ctrl_hidden[i][j].shape, ( + "Controller state mismatch: got " + f"{s_ctrl_hidden[i][j].shape} should be " + f"{ctrl_hidden[i][j].shape}" + ) + + for k in memory_dict: + assert s_memory_dict[k].shape == memory_dict[k].shape, ( + "Memory state mismatch at key " + f"{k}: got {s_memory_dict[k].shape} should be " + f"{memory_dict[k].shape}" + ) + + assert s_read_vecs.shape == read_vecs.shape, ( + "Read state mismatch: got " + f"{s_read_vecs.shape} should be " + f"{read_vecs.shape}" + ) + + def build_dnc(self, device_idx: Union[int, None]) -> None: + self.dnc = self.cfg["dnc_model"]( + input_size=self.cfg["preprocessor_output_size"], + hidden_size=self.cfg["hidden_size"], + num_layers=self.cfg["num_layers"], + num_hidden_layers=self.cfg["num_hidden_layers"], + read_heads=self.cfg["read_heads"], + cell_size=self.cfg["cell_size"], + nr_cells=self.cfg["nr_cells"], + nonlinearity=self.cfg["nonlinearity"], + gpu_id=device_idx, + ) + + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> Tuple[TensorType, List[TensorType]]: + + flat = input_dict["obs_flat"] + # Batch and Time + # Forward expects outputs as [B, T, logits] + B = len(seq_lens) + T = flat.shape[0] // B + + # Deconstruct batch into batch and time dimensions: [B, T, feats] + flat = torch.reshape(flat, [-1, T] + list(flat.shape[1:])) + + # First run + if self.dnc is None: + gpu_id = flat.device.index if flat.device.index is not None else -1 + self.build_dnc(gpu_id) + hidden = (None, None, None) + + else: + hidden = self.unpack_state(state) # type: ignore + + # Run thru preprocessor before DNC + z = self.preprocessor(flat.reshape(B * T, self.obs_dim)) + z = z.reshape(B, T, self.cfg["preprocessor_output_size"]) + output, hidden = self.dnc(z, hidden) + packed_state = self.pack_state(*hidden) + + # Compute action/value from output + logits = self.logit_branch(output.view(B * T, -1)) + values = self.value_branch(output.view(B * T, -1)) + + self.cur_val = values.squeeze(1) + + return logits, packed_state diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/parametric_actions_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/parametric_actions_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e568b8bed72ad00d740ae9be774fe43e06a44fe5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/parametric_actions_model.py @@ -0,0 +1,201 @@ +# @OldAPIStack +from gymnasium.spaces import Box + +from ray.rllib.algorithms.dqn.distributional_q_tf_model import DistributionalQTFModel +from ray.rllib.algorithms.dqn.dqn_torch_model import DQNTorchModel +from ray.rllib.models.tf.fcnet import FullyConnectedNetwork +from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.torch_utils import FLOAT_MAX, FLOAT_MIN + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class ParametricActionsModel(DistributionalQTFModel): + """Parametric action model that handles the dot product and masking. + + This assumes the outputs are logits for a single Categorical action dist. + Getting this to work with a more complex output (e.g., if the action space + is a tuple of several distributions) is also possible but left as an + exercise to the reader. + """ + + def __init__( + self, + obs_space, + action_space, + num_outputs, + model_config, + name, + true_obs_shape=(4,), + action_embed_size=2, + **kw + ): + super(ParametricActionsModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name, **kw + ) + self.action_embed_model = FullyConnectedNetwork( + Box(-1, 1, shape=true_obs_shape), + action_space, + action_embed_size, + model_config, + name + "_action_embed", + ) + + def forward(self, input_dict, state, seq_lens): + # Extract the available actions tensor from the observation. + avail_actions = input_dict["obs"]["avail_actions"] + action_mask = input_dict["obs"]["action_mask"] + + # Compute the predicted action embedding + action_embed, _ = self.action_embed_model({"obs": input_dict["obs"]["cart"]}) + + # Expand the model output to [BATCH, 1, EMBED_SIZE]. Note that the + # avail actions tensor is of shape [BATCH, MAX_ACTIONS, EMBED_SIZE]. + intent_vector = tf.expand_dims(action_embed, 1) + + # Batch dot product => shape of logits is [BATCH, MAX_ACTIONS]. + action_logits = tf.reduce_sum(avail_actions * intent_vector, axis=2) + + # Mask out invalid actions (use tf.float32.min for stability) + inf_mask = tf.maximum(tf.math.log(action_mask), tf.float32.min) + return action_logits + inf_mask, state + + def value_function(self): + return self.action_embed_model.value_function() + + +class TorchParametricActionsModel(DQNTorchModel): + """PyTorch version of above ParametricActionsModel.""" + + def __init__( + self, + obs_space, + action_space, + num_outputs, + model_config, + name, + true_obs_shape=(4,), + action_embed_size=2, + **kw + ): + DQNTorchModel.__init__( + self, obs_space, action_space, num_outputs, model_config, name, **kw + ) + + self.action_embed_model = TorchFC( + Box(-1, 1, shape=true_obs_shape), + action_space, + action_embed_size, + model_config, + name + "_action_embed", + ) + + def forward(self, input_dict, state, seq_lens): + # Extract the available actions tensor from the observation. + avail_actions = input_dict["obs"]["avail_actions"] + action_mask = input_dict["obs"]["action_mask"] + + # Compute the predicted action embedding + action_embed, _ = self.action_embed_model({"obs": input_dict["obs"]["cart"]}) + + # Expand the model output to [BATCH, 1, EMBED_SIZE]. Note that the + # avail actions tensor is of shape [BATCH, MAX_ACTIONS, EMBED_SIZE]. + intent_vector = torch.unsqueeze(action_embed, 1) + + # Batch dot product => shape of logits is [BATCH, MAX_ACTIONS]. + action_logits = torch.sum(avail_actions * intent_vector, dim=2) + + # Mask out invalid actions (use -inf to tag invalid). + # These are then recognized by the EpsilonGreedy exploration component + # as invalid actions that are not to be chosen. + inf_mask = torch.clamp(torch.log(action_mask), FLOAT_MIN, FLOAT_MAX) + + return action_logits + inf_mask, state + + def value_function(self): + return self.action_embed_model.value_function() + + +class ParametricActionsModelThatLearnsEmbeddings(DistributionalQTFModel): + """Same as the above ParametricActionsModel. + + However, this version also learns the action embeddings. + """ + + def __init__( + self, + obs_space, + action_space, + num_outputs, + model_config, + name, + true_obs_shape=(4,), + action_embed_size=2, + **kw + ): + super(ParametricActionsModelThatLearnsEmbeddings, self).__init__( + obs_space, action_space, num_outputs, model_config, name, **kw + ) + + action_ids_shifted = tf.constant( + list(range(1, num_outputs + 1)), dtype=tf.float32 + ) + + obs_cart = tf.keras.layers.Input(shape=true_obs_shape, name="obs_cart") + valid_avail_actions_mask = tf.keras.layers.Input( + shape=(num_outputs,), name="valid_avail_actions_mask" + ) + + self.pred_action_embed_model = FullyConnectedNetwork( + Box(-1, 1, shape=true_obs_shape), + action_space, + action_embed_size, + model_config, + name + "_pred_action_embed", + ) + + # Compute the predicted action embedding + pred_action_embed, _ = self.pred_action_embed_model({"obs": obs_cart}) + _value_out = self.pred_action_embed_model.value_function() + + # Expand the model output to [BATCH, 1, EMBED_SIZE]. Note that the + # avail actions tensor is of shape [BATCH, MAX_ACTIONS, EMBED_SIZE]. + intent_vector = tf.expand_dims(pred_action_embed, 1) + + valid_avail_actions = action_ids_shifted * valid_avail_actions_mask + # Embedding for valid available actions which will be learned. + # Embedding vector for 0 is an invalid embedding (a "dummy embedding"). + valid_avail_actions_embed = tf.keras.layers.Embedding( + input_dim=num_outputs + 1, + output_dim=action_embed_size, + name="action_embed_matrix", + )(valid_avail_actions) + + # Batch dot product => shape of logits is [BATCH, MAX_ACTIONS]. + action_logits = tf.reduce_sum(valid_avail_actions_embed * intent_vector, axis=2) + + # Mask out invalid actions (use tf.float32.min for stability) + inf_mask = tf.maximum(tf.math.log(valid_avail_actions_mask), tf.float32.min) + + action_logits = action_logits + inf_mask + + self.param_actions_model = tf.keras.Model( + inputs=[obs_cart, valid_avail_actions_mask], + outputs=[action_logits, _value_out], + ) + self.param_actions_model.summary() + + def forward(self, input_dict, state, seq_lens): + # Extract the available actions mask tensor from the observation. + valid_avail_actions_mask = input_dict["obs"]["valid_avail_actions_mask"] + + action_logits, self._value_out = self.param_actions_model( + [input_dict["obs"]["cart"], valid_avail_actions_mask] + ) + + return action_logits, state + + def value_function(self): + return self._value_out diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/shared_weights_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/shared_weights_model.py new file mode 100644 index 0000000000000000000000000000000000000000..478859af9da3aa09b21523302747ba842364a00c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/shared_weights_model.py @@ -0,0 +1,206 @@ +# @OldAPIStack +import numpy as np + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + +TF2_GLOBAL_SHARED_LAYER = None + + +class TF2SharedWeightsModel(TFModelV2): + """Example of weight sharing between two different TFModelV2s. + + NOTE: This will only work for tf2.x. When running with config.framework=tf, + use SharedWeightsModel1 and SharedWeightsModel2 below, instead! + + The shared (single) layer is simply defined outside of the two Models, + then used by both Models in their forward pass. + """ + + def __init__( + self, observation_space, action_space, num_outputs, model_config, name + ): + super().__init__( + observation_space, action_space, num_outputs, model_config, name + ) + + global TF2_GLOBAL_SHARED_LAYER + # The global, shared layer to be used by both models. + if TF2_GLOBAL_SHARED_LAYER is None: + TF2_GLOBAL_SHARED_LAYER = tf.keras.layers.Dense( + units=64, activation=tf.nn.relu, name="fc1" + ) + + inputs = tf.keras.layers.Input(observation_space.shape) + last_layer = TF2_GLOBAL_SHARED_LAYER(inputs) + output = tf.keras.layers.Dense( + units=num_outputs, activation=None, name="fc_out" + )(last_layer) + vf = tf.keras.layers.Dense(units=1, activation=None, name="value_out")( + last_layer + ) + self.base_model = tf.keras.models.Model(inputs, [output, vf]) + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + out, self._value_out = self.base_model(input_dict["obs"]) + return out, [] + + @override(ModelV2) + def value_function(self): + return tf.reshape(self._value_out, [-1]) + + +class SharedWeightsModel1(TFModelV2): + """Example of weight sharing between two different TFModelV2s. + + NOTE: This will only work for tf1 (static graph). When running with + config.framework_str=tf2, use TF2SharedWeightsModel, instead! + + Here, we share the variables defined in the 'shared' variable scope + by entering it explicitly with tf1.AUTO_REUSE. This creates the + variables for the 'fc1' layer in a global scope called 'shared' + (outside of the Policy's normal variable scope). + """ + + def __init__( + self, observation_space, action_space, num_outputs, model_config, name + ): + super().__init__( + observation_space, action_space, num_outputs, model_config, name + ) + + inputs = tf.keras.layers.Input(observation_space.shape) + with tf1.variable_scope( + tf1.VariableScope(tf1.AUTO_REUSE, "shared"), + reuse=tf1.AUTO_REUSE, + auxiliary_name_scope=False, + ): + last_layer = tf.keras.layers.Dense( + units=64, activation=tf.nn.relu, name="fc1" + )(inputs) + output = tf.keras.layers.Dense( + units=num_outputs, activation=None, name="fc_out" + )(last_layer) + vf = tf.keras.layers.Dense(units=1, activation=None, name="value_out")( + last_layer + ) + self.base_model = tf.keras.models.Model(inputs, [output, vf]) + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + out, self._value_out = self.base_model(input_dict["obs"]) + return out, [] + + @override(ModelV2) + def value_function(self): + return tf.reshape(self._value_out, [-1]) + + +class SharedWeightsModel2(TFModelV2): + """The "other" TFModelV2 using the same shared space as the one above.""" + + def __init__( + self, observation_space, action_space, num_outputs, model_config, name + ): + super().__init__( + observation_space, action_space, num_outputs, model_config, name + ) + + inputs = tf.keras.layers.Input(observation_space.shape) + + # Weights shared with SharedWeightsModel1. + with tf1.variable_scope( + tf1.VariableScope(tf1.AUTO_REUSE, "shared"), + reuse=tf1.AUTO_REUSE, + auxiliary_name_scope=False, + ): + last_layer = tf.keras.layers.Dense( + units=64, activation=tf.nn.relu, name="fc1" + )(inputs) + output = tf.keras.layers.Dense( + units=num_outputs, activation=None, name="fc_out" + )(last_layer) + vf = tf.keras.layers.Dense(units=1, activation=None, name="value_out")( + last_layer + ) + self.base_model = tf.keras.models.Model(inputs, [output, vf]) + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + out, self._value_out = self.base_model(input_dict["obs"]) + return out, [] + + @override(ModelV2) + def value_function(self): + return tf.reshape(self._value_out, [-1]) + + +TORCH_GLOBAL_SHARED_LAYER = None +if torch: + # The global, shared layer to be used by both models. + TORCH_GLOBAL_SHARED_LAYER = SlimFC( + 64, + 64, + activation_fn=nn.ReLU, + initializer=torch.nn.init.xavier_uniform_, + ) + + +class TorchSharedWeightsModel(TorchModelV2, nn.Module): + """Example of weight sharing between two different TorchModelV2s. + + The shared (single) layer is simply defined outside of the two Models, + then used by both Models in their forward pass. + """ + + def __init__( + self, observation_space, action_space, num_outputs, model_config, name + ): + TorchModelV2.__init__( + self, observation_space, action_space, num_outputs, model_config, name + ) + nn.Module.__init__(self) + + # Non-shared initial layer. + self.first_layer = SlimFC( + int(np.prod(observation_space.shape)), + 64, + activation_fn=nn.ReLU, + initializer=torch.nn.init.xavier_uniform_, + ) + + # Non-shared final layer. + self.last_layer = SlimFC( + 64, + self.num_outputs, + activation_fn=None, + initializer=torch.nn.init.xavier_uniform_, + ) + self.vf = SlimFC( + 64, + 1, + activation_fn=None, + initializer=torch.nn.init.xavier_uniform_, + ) + self._global_shared_layer = TORCH_GLOBAL_SHARED_LAYER + self._output = None + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + out = self.first_layer(input_dict["obs"]) + self._output = self._global_shared_layer(out) + model_out = self.last_layer(self._output) + return model_out, [] + + @override(ModelV2) + def value_function(self): + assert self._output is not None, "must call forward first!" + return torch.reshape(self.vf(self._output), [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/simple_rpg_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/simple_rpg_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b37d915df8a18101435ea9acd59b14f71e39b74d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/models/simple_rpg_model.py @@ -0,0 +1,65 @@ +# @OldAPIStack +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.tf.fcnet import FullyConnectedNetwork as TFFCNet +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFCNet +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + + +class CustomTorchRPGModel(TorchModelV2, nn.Module): + """Example of interpreting repeated observations.""" + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + super().__init__(obs_space, action_space, num_outputs, model_config, name) + nn.Module.__init__(self) + self.model = TorchFCNet( + obs_space, action_space, num_outputs, model_config, name + ) + + def forward(self, input_dict, state, seq_lens): + # The unpacked input tensors, where M=MAX_PLAYERS, N=MAX_ITEMS: + # { + # 'items', , + # 'location', , + # 'status', , + # } + print("The unpacked input tensors:", input_dict["obs"]) + print() + print("Unbatched repeat dim", input_dict["obs"].unbatch_repeat_dim()) + print() + print("Fully unbatched", input_dict["obs"].unbatch_all()) + print() + return self.model.forward(input_dict, state, seq_lens) + + def value_function(self): + return self.model.value_function() + + +class CustomTFRPGModel(TFModelV2): + """Example of interpreting repeated observations.""" + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + super().__init__(obs_space, action_space, num_outputs, model_config, name) + self.model = TFFCNet(obs_space, action_space, num_outputs, model_config, name) + + def forward(self, input_dict, state, seq_lens): + # The unpacked input tensors, where M=MAX_PLAYERS, N=MAX_ITEMS: + # { + # 'items', , + # 'location', , + # 'status', , + # } + print("The unpacked input tensors:", input_dict["obs"]) + print() + print("Unbatched repeat dim", input_dict["obs"].unbatch_repeat_dim()) + print() + if tf.executing_eagerly(): + print("Fully unbatched", input_dict["obs"].unbatch_all()) + print() + return self.model.forward(input_dict, state, seq_lens) + + def value_function(self): + return self.model.value_function() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/parametric_actions_cartpole.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/parametric_actions_cartpole.py new file mode 100644 index 0000000000000000000000000000000000000000..22bde41d1b95c438fa798f56df12cd748ae8f750 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/parametric_actions_cartpole.py @@ -0,0 +1,121 @@ +# @OldAPIStack +"""Example of handling variable length or parametric action spaces. + +This toy example demonstrates the action-embedding based approach for handling large +discrete action spaces (potentially infinite in size), similar to this example: + + https://neuro.cs.ut.ee/the-use-of-embeddings-in-openai-five/ + +This example works with RLlib's policy gradient style algorithms +(e.g., PG, PPO, IMPALA, A2C) and DQN. + +Note that since the model outputs now include "-inf" tf.float32.min +values, not all algorithm options are supported. For example, +algorithms might crash if they don't properly ignore the -inf action scores. +Working configurations are given below. +""" + +import argparse +import os + +import ray +from ray import tune +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.examples.envs.classes.parametric_actions_cartpole import ( + ParametricActionsCartPole, +) +from ray.rllib.examples._old_api_stack.models.parametric_actions_model import ( + ParametricActionsModel, + TorchParametricActionsModel, +) +from ray.rllib.models import ModelCatalog +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import check_learning_achieved +from ray.tune.registry import register_env + +parser = argparse.ArgumentParser() +parser.add_argument( + "--run", type=str, default="PPO", help="The RLlib-registered algorithm to use." +) +parser.add_argument( + "--framework", + choices=["tf", "tf2", "torch"], + default="torch", + help="The DL framework specifier.", +) +parser.add_argument( + "--as-test", + action="store_true", + help="Whether this script should be run as a test: --stop-reward must " + "be achieved within --stop-timesteps AND --stop-iters.", +) +parser.add_argument( + "--stop-iters", type=int, default=200, help="Number of iterations to train." +) +parser.add_argument( + "--stop-timesteps", type=int, default=100000, help="Number of timesteps to train." +) +parser.add_argument( + "--stop-reward", type=float, default=150.0, help="Reward at which we stop training." +) + +if __name__ == "__main__": + args = parser.parse_args() + ray.init() + + register_env("pa_cartpole", lambda _: ParametricActionsCartPole(10)) + ModelCatalog.register_custom_model( + "pa_model", + TorchParametricActionsModel + if args.framework == "torch" + else ParametricActionsModel, + ) + + if args.run == "DQN": + cfg = { + # TODO(ekl) we need to set these to prevent the masked values + # from being further processed in DistributionalQModel, which + # would mess up the masking. It is possible to support these if we + # defined a custom DistributionalQModel that is aware of masking. + "hiddens": [], + "dueling": False, + "enable_rl_module_and_learner": False, + "enable_env_runner_and_connector_v2": False, + } + else: + cfg = {} + + config = dict( + { + "env": "pa_cartpole", + "model": { + "custom_model": "pa_model", + }, + # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0. + "num_gpus": int(os.environ.get("RLLIB_NUM_GPUS", "0")), + "num_env_runners": 0, + "framework": args.framework, + }, + **cfg, + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}": args.stop_timesteps, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + + results = tune.Tuner( + args.run, + run_config=tune.RunConfig(stop=stop, verbose=1), + param_space=config, + ).fit() + + if args.as_test: + check_learning_achieved(results, args.stop_reward) + + ray.shutdown() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/parametric_actions_cartpole_embeddings_learnt_by_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/parametric_actions_cartpole_embeddings_learnt_by_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7ae5060df15c9c71ebf6e7f08cc5f037625247 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/parametric_actions_cartpole_embeddings_learnt_by_model.py @@ -0,0 +1,107 @@ +# @OldAPIStack +"""Example of handling variable length or parametric action spaces. + +This is a toy example of the action-embedding based approach for handling large +discrete action spaces (potentially infinite in size), similar to this: + + https://neuro.cs.ut.ee/the-use-of-embeddings-in-openai-five/ + +This currently works with RLlib's policy gradient style algorithms +(e.g., PG, PPO, IMPALA, A2C) and also DQN. + +Note that since the model outputs now include "-inf" tf.float32.min +values, not all algorithm options are supported at the moment. For example, +algorithms might crash if they don't properly ignore the -inf action scores. +Working configurations are given below. +""" + +import argparse +import os + +import ray +from ray import tune +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.examples.envs.classes.parametric_actions_cartpole import ( + ParametricActionsCartPoleNoEmbeddings, +) +from ray.rllib.examples._old_api_stack.models.parametric_actions_model import ( + ParametricActionsModelThatLearnsEmbeddings, +) +from ray.rllib.models import ModelCatalog +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import check_learning_achieved +from ray.tune.registry import register_env + +parser = argparse.ArgumentParser() +parser.add_argument("--run", type=str, default="PPO") +parser.add_argument( + "--framework", + choices=["tf", "tf2"], + default="tf", + help="The DL framework specifier (Torch not supported " + "due to the lack of a model).", +) +parser.add_argument("--as-test", action="store_true") +parser.add_argument("--stop-iters", type=int, default=200) +parser.add_argument("--stop-reward", type=float, default=150.0) +parser.add_argument("--stop-timesteps", type=int, default=100000) + +if __name__ == "__main__": + args = parser.parse_args() + ray.init() + + register_env("pa_cartpole", lambda _: ParametricActionsCartPoleNoEmbeddings(10)) + + ModelCatalog.register_custom_model( + "pa_model", ParametricActionsModelThatLearnsEmbeddings + ) + + if args.run == "DQN": + cfg = { + # TODO(ekl) we need to set these to prevent the masked values + # from being further processed in DistributionalQModel, which + # would mess up the masking. It is possible to support these if we + # defined a custom DistributionalQModel that is aware of masking. + "hiddens": [], + "dueling": False, + "enable_rl_module_and_learner": False, + "enable_env_runner_and_connector_v2": False, + } + else: + cfg = {} + + config = dict( + { + "env": "pa_cartpole", + "model": { + "custom_model": "pa_model", + }, + # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0. + "num_gpus": int(os.environ.get("RLLIB_NUM_GPUS", "0")), + "num_env_runners": 0, + "framework": args.framework, + "action_mask_key": "valid_avail_actions_mask", + }, + **cfg, + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + + results = tune.Tuner( + args.run, + run_config=tune.RunConfig(stop=stop, verbose=2), + param_space=config, + ).fit() + + if args.as_test: + check_learning_achieved(results, args.stop_reward) + + ray.shutdown() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc36f4cb4265c40d5e3d9762c3ce20a269e02302 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/cliff_walking_wall_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/cliff_walking_wall_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bd8f3aecedfb38f434e051d8f68aa6deb23fa37 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/cliff_walking_wall_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/random_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/random_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad2947efcb12aa5328ced0a4a56a7b8be5a81214 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/random_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a4758f81ea427f577c6e8004e4ffeb8f3bef06 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py @@ -0,0 +1,100 @@ +# @OldAPIStack +import gymnasium as gym +from typing import Dict, Union, List, Tuple, Optional +import numpy as np + +from ray.rllib.policy.policy import Policy, ViewRequirement +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.models.torch.torch_action_dist import TorchCategorical +from ray.rllib.utils.typing import AlgorithmConfigDict, TensorStructType, TensorType +from ray.rllib.utils.annotations import override +from ray.rllib.utils.debug import update_global_seed_if_necessary + + +class CliffWalkingWallPolicy(Policy): + """Optimal RLlib policy for the CliffWalkingWallEnv environment, defined in + ray/rllib/examples/env/cliff_walking_wall_env.py, with epsilon-greedy exploration. + + The policy takes a random action with probability epsilon, specified + by `config["epsilon"]`, and the optimal action with probability 1 - epsilon. + """ + + @override(Policy) + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + config: AlgorithmConfigDict, + ): + update_global_seed_if_necessary(seed=config.get("seed")) + super().__init__(observation_space, action_space, config) + + # Known optimal action dist for each of the 48 states and 4 actions + self.action_dist = np.zeros((48, 4), dtype=float) + # Starting state: go up + self.action_dist[36] = (1, 0, 0, 0) + # Cliff + Goal: never actually used, set to random + self.action_dist[37:] = (0.25, 0.25, 0.25, 0.25) + # Row 2; always go right + self.action_dist[24:36] = (0, 1, 0, 0) + # Row 0 and Row 1; go down or go right + self.action_dist[0:24] = (0, 0.5, 0.5, 0) + # Col 11; always go down, supercedes previous values + self.action_dist[[11, 23, 35]] = (0, 0, 1, 0) + assert np.allclose(self.action_dist.sum(-1), 1) + + # Epsilon-Greedy action selection + epsilon = config.get("epsilon", 0.0) + self.action_dist = self.action_dist * (1 - epsilon) + epsilon / 4 + assert np.allclose(self.action_dist.sum(-1), 1) + + # Attributes required for RLlib; note that while CliffWalkingWallPolicy + # inherits from Policy, it actually implements TorchPolicyV2. + self.view_requirements[SampleBatch.ACTION_PROB] = ViewRequirement() + self.device = "cpu" + self.model = None + self.dist_class = TorchCategorical + + @override(Policy) + def compute_actions( + self, + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + obs = np.array(obs_batch, dtype=int) + action_probs = self.action_dist[obs] + actions = np.zeros(len(obs), dtype=int) + for i in range(len(obs)): + actions[i] = np.random.choice(4, p=action_probs[i]) + return ( + actions, + [], + {SampleBatch.ACTION_PROB: action_probs[np.arange(len(obs)), actions]}, + ) + + @override(Policy) + def compute_log_likelihoods( + self, + actions: Union[List[TensorType], TensorType], + obs_batch: Union[List[TensorType], TensorType], + **kwargs, + ) -> TensorType: + obs = np.array(obs_batch, dtype=int) + actions = np.array(actions, dtype=int) + # Compute action probs for all possible actions + action_probs = self.action_dist[obs] + # Take the action_probs corresponding to the specified actions + action_probs = action_probs[np.arange(len(obs)), actions] + # Ignore RuntimeWarning thrown by np.log(0) if action_probs is 0 + with np.errstate(divide="ignore"): + return np.log(action_probs) + + def action_distribution_fn( + self, model, obs_batch: TensorStructType, **kwargs + ) -> Tuple[TensorType, type, List[TensorType]]: + obs = np.array(obs_batch[SampleBatch.OBS], dtype=int) + action_probs = self.action_dist[obs] + # Ignore RuntimeWarning thrown by np.log(0) if action_probs is 0 + with np.errstate(divide="ignore"): + return np.log(action_probs), TorchCategorical, None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/random_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/random_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c410ba0ec464e73fe380741180e71b56c9967a5b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/_old_api_stack/policy/random_policy.py @@ -0,0 +1,101 @@ +# @OldAPIStack +from gymnasium.spaces import Box +import numpy as np +import random +import tree # pip install dm_tree +from typing import ( + List, + Optional, + Union, +) + +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import ModelWeights, TensorStructType, TensorType + + +class RandomPolicy(Policy): + """Hand-coded policy that returns random actions.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # Whether for compute_actions, the bounds given in action_space + # should be ignored (default: False). This is to test action-clipping + # and any Env's reaction to bounds breaches. + if self.config.get("ignore_action_bounds", False) and isinstance( + self.action_space, Box + ): + self.action_space_for_sampling = Box( + -float("inf"), + float("inf"), + shape=self.action_space.shape, + dtype=self.action_space.dtype, + ) + else: + self.action_space_for_sampling = self.action_space + + @override(Policy) + def init_view_requirements(self): + super().init_view_requirements() + # Disable for_training and action attributes for SampleBatch.INFOS column + # since it can not be properly batched. + vr = self.view_requirements[SampleBatch.INFOS] + vr.used_for_training = False + vr.used_for_compute_actions = False + + @override(Policy) + def compute_actions( + self, + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Union[List[TensorStructType], TensorStructType] = None, + prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None, + **kwargs, + ): + # Alternatively, a numpy array would work here as well. + # e.g.: np.array([random.choice([0, 1])] * len(obs_batch)) + obs_batch_size = len(tree.flatten(obs_batch)[0]) + return ( + [self.action_space_for_sampling.sample() for _ in range(obs_batch_size)], + [], + {}, + ) + + @override(Policy) + def learn_on_batch(self, samples): + """No learning.""" + return {} + + @override(Policy) + def compute_log_likelihoods( + self, + actions, + obs_batch, + state_batches=None, + prev_action_batch=None, + prev_reward_batch=None, + **kwargs, + ): + return np.array([random.random()] * len(obs_batch)) + + @override(Policy) + def get_weights(self) -> ModelWeights: + """No weights to save.""" + return {} + + @override(Policy) + def set_weights(self, weights: ModelWeights) -> None: + """No weights to set.""" + pass + + @override(Policy) + def _get_dummy_batch_from_view_requirements(self, batch_size: int = 1): + return SampleBatch( + { + SampleBatch.OBS: tree.map_structure( + lambda s: s[None], self.observation_space.sample() + ), + } + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6afcfab42d7091a5d5f6b7b113a8b32b83bf3fe5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/autoregressive_actions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/autoregressive_actions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d983f74fb6fc3265aaaa8298bbb376937c8a3683 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/autoregressive_actions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/custom_action_distribution.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/custom_action_distribution.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..413d2c97509c0842c63f036ddc8083a5675d8844 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/custom_action_distribution.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/nested_action_spaces.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/nested_action_spaces.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bb13ea9df81edcefe4b5ea634ea09fbbd7e783b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/__pycache__/nested_action_spaces.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/autoregressive_actions.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/autoregressive_actions.py new file mode 100644 index 0000000000000000000000000000000000000000..142d4991f2f5e16cffcc2f8563ee943937da6a98 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/autoregressive_actions.py @@ -0,0 +1,108 @@ +"""Example on how to define and run with an RLModule with a dependent action space. + +This examples: + - Shows how to write a custom RLModule outputting autoregressive actions. + The RLModule class used here implements a prior distribution for the first couple + of actions and then uses the sampled actions to compute the parameters for and + sample from a posterior distribution. + - Shows how to configure a PPO algorithm to use the custom RLModule. + - Stops the training after 100k steps or when the mean episode return + exceeds -0.012 in evaluation, i.e. if the agent has learned to + synchronize its actions. + +For details on the environment used, take a look at the `CorrelatedActionsEnv` +class. To receive an episode return over 100, the agent must learn how to synchronize +its actions. + + +How to run this script +---------------------- +`python [script file name].py --num-env-runners 2` + +Control the number of `EnvRunner`s with the `--num-env-runners` flag. This +will increase the sampling speed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should reach an episode return of better than -0.5 quickly through a simple PPO +policy. The logic behind beating the env is roughly: + +OBS: optimal a1: r1: optimal a2: r2: +-1 2 0 -1.0 0 +-0.5 1/2 -0.5 -0.5/-1.5 0 +0 1 0 -1.0 0 +0.5 0/1 -0.5 -0.5/-1.5 0 +1 0 0 -1.0 0 + +Meaning, most of the time, you would receive a reward better than -0.5, but worse than +0.0. + ++--------------------------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|--------------------------------------+------------+--------+------------------+ +| PPO_CorrelatedActionsEnv_6660d_00000 | TERMINATED | 76 | 132.438 | ++--------------------------------------+------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| episode_return_mean | num_env_steps_sample | ...env_steps_sampled | +| | d_lifetime | _lifetime_throughput | +|------------------------+------------------------+------------------------| +| -0.43 | 152000 | 1283.48 | ++------------------------+------------------------+------------------------+ +""" + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.envs.classes.correlated_actions_env import CorrelatedActionsEnv +from ray.rllib.examples.rl_modules.classes.autoregressive_actions_rlm import ( + AutoregressiveActionsRLM, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + + +parser = add_rllib_example_script_args( + default_iters=1000, + default_timesteps=2000000, + default_reward=-0.45, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + if args.algo != "PPO": + raise ValueError( + "This example script only runs with PPO! Set --algo=PPO on the command " + "line." + ) + + base_config = ( + PPOConfig() + .environment(CorrelatedActionsEnv) + .training( + train_batch_size_per_learner=2000, + num_epochs=12, + minibatch_size=256, + entropy_coeff=0.005, + lr=0.0003, + ) + # Specify the RLModule class to be used. + .rl_module( + rl_module_spec=RLModuleSpec(module_class=AutoregressiveActionsRLM), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/custom_action_distribution.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/custom_action_distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..c9226d66b8c3fae21c229cba6bd0a28ed7494a32 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/custom_action_distribution.py @@ -0,0 +1,117 @@ +"""Example on how to define and run an experiment with a custom action distribution. + +The example uses an additional `temperature` parameter on top of the built-in +`TorchCategorical` class. Incoming logits (outputs from the RLModule) are divided by +this temperature before creating the underlying +torch.distributions.categorical.Categorical object. + +This examples: + - Shows how to write a custom RLlib action distribution class accepting an + additional parameter in its constructor. + - demonstrates how you can subclass the TorchRLModule base class and write your + own architecture by overriding the `setup()` method. + - shows how to set the attribute `self.action_dist_cls` in that same `setup()` + method. For an alternative way of defining action distribution classes for your + RLModules, see the `setup()` method implementation in the imported + `CustomActionDistributionRLModule` class. + - shows how you then configure an RLlib Algorithm such that it uses your custom + RLModule (instead of a default RLModule). + + +How to run this script +---------------------- +`python [script file name].py --temperature=0.8` + +Use the `--temperature` setting to change the temperature. Higher values (>>1.0) lead +to almost random behavior, lower values (<<1.0) lead to always-greedy behavior. Note +though, that both extremes hurt learning performance. + +Control the number of `EnvRunner`s with the `--num-env-runners` flag. This +will increase the sampling speed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +With a --temperature setting of 0.75, learning seems to be particularly easy with the +given other parameters: + ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_1bbe0_00000 | TERMINATED | 127.0.0.1:81594 | 22 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_env_steps_sample | +| | | d_lifetime | +|------------------+------------------------+------------------------| +| 17.6368 | 450.54 | 88000 | ++------------------+------------------------+------------------------+ +""" + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.rl_modules.classes.custom_action_distribution_rlm import ( + CustomActionDistributionRLModule, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + + +parser = add_rllib_example_script_args( + default_timesteps=200000, + default_reward=450.0, +) +parser.add_argument( + "--temperature", + type=float, + default=2.0, + help="The action distribution temperature to apply to the raw model logits. " + "Logits are first divided by the temperature, then an underlying torch.Categorical " + "distribution is created from those altered logits and used for sampling actions. " + "Set this to <<1.0 to approximate greedy behavior and to >>1.0 to approximate " + "random behavior.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + if args.algo != "PPO": + raise ValueError( + "This example script only runs with PPO! Set --algo=PPO on the command " + "line." + ) + + base_config = ( + PPOConfig() + .environment("CartPole-v1") + .training( + lr=0.0003, + num_epochs=6, + vf_loss_coeff=0.01, + ) + # Specify the RLModule class to be used. + .rl_module( + rl_module_spec=RLModuleSpec( + module_class=CustomActionDistributionRLModule, + model_config={ + "hidden_dim": 128, + "action_dist_temperature": args.temperature, + }, + ), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/nested_action_spaces.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/nested_action_spaces.py new file mode 100644 index 0000000000000000000000000000000000000000..6210fc669563233450d3c363382afd212fba13b0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/actions/nested_action_spaces.py @@ -0,0 +1,85 @@ +from gymnasium.spaces import Dict, Tuple, Box, Discrete, MultiDiscrete + +from ray.tune.registry import register_env +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.examples.envs.classes.multi_agent import ( + MultiAgentNestedSpaceRepeatAfterMeEnv, +) +from ray.rllib.examples.envs.classes.nested_space_repeat_after_me_env import ( + NestedSpaceRepeatAfterMeEnv, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + + +# Read in common example script command line arguments. +parser = add_rllib_example_script_args(default_timesteps=200000, default_reward=-500.0) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Define env-to-module-connector pipeline for the new stack. + def _env_to_module_pipeline(env, spaces, device): + return FlattenObservations(multi_agent=args.num_agents > 0) + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda c: MultiAgentNestedSpaceRepeatAfterMeEnv( + config=dict(c, **{"num_agents": args.num_agents}) + ), + ) + else: + register_env("env", lambda c: NestedSpaceRepeatAfterMeEnv(c)) + + # Define the AlgorithmConfig used. + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + "env", + env_config={ + "space": Dict( + { + "a": Tuple( + [Dict({"d": Box(-15.0, 3.0, ()), "e": Discrete(3)})] + ), + "b": Box(-10.0, 10.0, (2,)), + "c": MultiDiscrete([3, 3]), + "d": Discrete(2), + } + ), + "episode_len": 100, + }, + ) + .env_runners(env_to_module_connector=_env_to_module_pipeline) + # No history in Env (bandit problem). + .training( + gamma=0.0, + lr=0.0005, + ) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # Fix some PPO-specific settings. + if args.algo == "PPO": + base_config.training( + # We don't want high entropy in this Env. + entropy_coeff=0.00005, + num_epochs=4, + vf_loss_coeff=0.01, + ) + + # Run everything as configured. + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f2f2740d2cf742d9ee8ee379fcf43bf11ea261d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/appo_custom_algorithm_w_shared_data_actor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/appo_custom_algorithm_w_shared_data_actor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c94f009bd707f794f59b265cba1f5a4b84f67096 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/appo_custom_algorithm_w_shared_data_actor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/maml_lr_supervised_learning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/maml_lr_supervised_learning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..088d347b81da12ffa6dab19877d2bd785d6bf60e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/maml_lr_supervised_learning.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/vpg_custom_algorithm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/vpg_custom_algorithm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..540ddd31b69cff7e32b33f4498ea2e3a478f4609 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/__pycache__/vpg_custom_algorithm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/appo_custom_algorithm_w_shared_data_actor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/appo_custom_algorithm_w_shared_data_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..780ae469f1ef53c22e0bf27f3c7e8160d30054cc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/appo_custom_algorithm_w_shared_data_actor.py @@ -0,0 +1,184 @@ +"""Example of how to write a custom APPO that uses a global shared data actor. + +The actor is custom code and its remote APIs can be designed as the user requires. +It is created inside the Algorithm's `setup` method and then shared through its +reference with all of the Algorithm's other actors, like EnvRunners, Learners, and +aggregator actors. + +During sampling and through using callbacks, each EnvRunner assigns a unique ID +to each sampled episode chunk, then sends manipulated reward data for each sampled +episode chunk to the shared data actor. In particular, the manipulation consists of +each individual reward being multiplied by the EnvRunner's index (from 1 to ...). +Note that the actual reward in the episode is not altered and thus the metrics +reporting continues to show the original reward. + +In the learner connector, which creates the train batch from episode data, a custom +connector piece then gets the manipulated rewards from the shared data actor using +the episode chunk's unique ID (see above) and uses the manipulated reward for training. +Note that because of this, different EnvRunners provide different reward signals, which +should make it slightly harder for the value function to learn consistently. +Nevertheless, because the default config here only uses 2 EnvRunners, each multiplying +their rewards by 1 and 2, respectively, this effect is negligible here and the example +should learn how to solve the CartPole-1 env either way. + +This example shows: + + - how to write a custom, global shared data actor class with a custom remote API. + - how an instance of this shared data actor is created upon algorithm + initialization. + - how to distribute the actor reference of the shared actor to all other actors + in the Algorithm, for example EnvRunners, AggregatorActors, and Learners + - how to subclass an existing algorithm class (APPO) to implement a custom + Algorithm, overriding the `setup` method to control, which additional actors + should be created (and shared) by the algo, the `get_state/set_state` methods + to include the state of the new actor. + - how - through custom callbacks - the new actor can be written to and queried + from anywhere within the algorithm, for example its EnvRunner actors or Learners. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +The experiment should work regardless of whether you are using aggregator +actors or not. By default, the experiment provides one agg. actor per Learner, +but you can set `--num-aggregator-actors-per-learner=0` to have the learner +connector pipeline work directly inside the Learner actor(s). + ++-------------------------------------------------+------------+--------+ +| Trial name | status | iter | +| | | | +|-------------------------------------------------+------------+--------+ +| APPOWithSharedDataActor_CartPole-v1_4e860_00000 | TERMINATED | 7 | ++-------------------------------------------------+------------+--------+ ++------------------+------------------------+ +| total time (s) | episode_return_mean | +| | | +|------------------+------------------------+ +| 70.0315 | 468.42 | ++------------------+------------------------+ +""" + +import uuid + +import ray +from ray.rllib.algorithms.appo import APPOConfig +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core import Columns +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.examples.algorithms.classes.appo_w_shared_data_actor import ( + APPOWithSharedDataActor, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + + +parser = add_rllib_example_script_args( + default_reward=450.0, + default_iters=200, + default_timesteps=2000000, +) +parser.set_defaults( + num_aggregator_actors_per_learner=1, +) + +SPECIAL_REWARDS_KEY = "special_(double)_rewards" +ENV_RUNNER_IDX_KEY = "env_runner_index" +UNIQUE_EPISODE_CHUNK_KEY = "unique_eps_chunk" + + +# Define 2 simple EnvRunner-based callbacks: + + +def on_episode_step(*, episode, env_runner, **kwargs): + # Multiplies the received reward by the env runner index. + if SPECIAL_REWARDS_KEY not in episode.custom_data: + episode.custom_data[SPECIAL_REWARDS_KEY] = [] + episode.custom_data[SPECIAL_REWARDS_KEY].append( + episode.get_rewards(-1) * env_runner.worker_index + ) + + +def on_sample_end(*, samples, env_runner, **kwargs): + # Sends the (manipulated) reward sequence to the shared data actor for "pickup" by + # a Learner. Alternatively, one could also just store the information in the + # `custom_data` property. + for episode in samples: + # Provide a unique key for both episode AND record in the shared + # data actor. + unique_key = str(uuid.uuid4()) + + # Store the EnvRunner index and unique key in the episode. + episode.custom_data[ENV_RUNNER_IDX_KEY] = env_runner.worker_index + episode.custom_data[UNIQUE_EPISODE_CHUNK_KEY] = unique_key + + # Get the manipulated rewards from the episode .. + special_rewards = episode.custom_data.pop(SPECIAL_REWARDS_KEY) + # .. and send them under the unique key to the shared data actor. + env_runner._shared_data_actor.put.remote( + key=unique_key, + value=special_rewards, + ) + + +class ManipulatedRewardConnector(ConnectorV2): + def __call__(self, *, episodes, batch, metrics, **kwargs): + if not isinstance(episodes[0], SingleAgentEpisode): + raise ValueError("This connector only works on `SingleAgentEpisodes`.") + # Get the manipulated rewards from the shared actor and add them to the train + # batch. + for sa_episode in self.single_agent_episode_iterator(episodes): + unique_key = sa_episode.custom_data[UNIQUE_EPISODE_CHUNK_KEY] + special_rewards = ray.get( + self._shared_data_actor.get.remote(unique_key, delete=True) + ) + if special_rewards is None: + continue + + assert int(special_rewards[0]) == sa_episode.custom_data[ENV_RUNNER_IDX_KEY] + + # Add one more fake reward, b/c all episodes will be extended + # (in PPO-style algos) by one artificial timestep for GAE/v-trace + # computation purposes. + special_rewards += [0.0] + self.add_n_batch_items( + batch=batch, + column=Columns.REWARDS, + items_to_add=special_rewards[-len(sa_episode) :], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + return batch + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + APPOConfig(algo_class=APPOWithSharedDataActor) + .environment("CartPole-v1") + .callbacks( + on_episode_step=on_episode_step, + on_sample_end=on_sample_end, + ) + .training( + learner_connector=(lambda obs_sp, act_sp: ManipulatedRewardConnector()), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5490d9aa1fb00b3aea09bbf9c9583c517bb9257d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/appo_w_shared_data_actor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/appo_w_shared_data_actor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d71f763436c480cb026ae8eb71f65fb4f1783c5a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/appo_w_shared_data_actor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_differentiable_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_differentiable_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..934125410e0024cd71d3ccd4e93e083475ba6798 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_differentiable_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_differentiable_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_differentiable_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1e9dcd63950261ef919d53590cc32dd3b624384 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_differentiable_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_meta_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_meta_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4de61ecde361528d0e3e25308018b5c983ab28fd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/maml_lr_meta_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/vpg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/vpg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..434244c81d87b7289f87a4227c137801ed975d91 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/vpg.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/appo_w_shared_data_actor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/appo_w_shared_data_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..1b2a1efef43854aac5e51172eabbfad817aeddaa --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/appo_w_shared_data_actor.py @@ -0,0 +1,88 @@ +from typing import List + +import ray +from ray.rllib.algorithms import AlgorithmConfig +from ray.rllib.algorithms.appo import APPO +from ray.rllib.env.env_runner_group import EnvRunnerGroup + + +@ray.remote +class SharedDataActor: + """Simple example of an actor that's accessible from all other actors of an algo. + + Exposes remote APIs `put` and `get` to other actors for storing and retrieving + arbitrary data. + """ + + def __init__(self): + self.storage = {} + + def get(self, key, delete: bool = False): + value = self.storage.get(key) + if delete and key in self.storage: + del self.storage[key] + return value + + def put(self, key, value): + self.storage[key] = value + + def get_state(self): + return self.storage + + def set_state(self, state): + self.storage = state + + +class APPOWithSharedDataActor(APPO): + def setup(self, config: AlgorithmConfig): + # Call to parent `setup`. + super().setup(config) + + # Create shared data actor. + self.shared_data_actor = SharedDataActor.remote() + + # Share the actor with all other relevant actors. + + def _share(actor, shared_act=self.shared_data_actor): + actor._shared_data_actor = shared_act + # Also add shared actor reference to all the learner connector pieces, + # if applicable. + if hasattr(actor, "_learner_connector") and actor._learner_connector: + for conn in actor._learner_connector: + conn._shared_data_actor = shared_act + + self.env_runner_group.foreach_env_runner(func=_share) + if self.eval_env_runner_group: + self.eval_env_runner_group.foreach_env_runner(func=_share) + self.learner_group.foreach_learner(func=_share) + if self._aggregator_actor_manager: + self._aggregator_actor_manager.foreach_actor(func=_share) + + def get_state(self, *args, **kwargs): + state = super().get_state(*args, **kwargs) + # Add shared actor's state. + state["shared_data_actor"] = ray.get(self.shared_data_actor.get_state.remote()) + return state + + def set_state(self, state, *args, **kwargs): + super().set_state(state, *args, **kwargs) + # Set shared actor's state. + if "shared_data_actor" in state: + self.shared_data_actor.set_state.remote(state["shared_data_actor"]) + + def restore_env_runners(self, env_runner_group: EnvRunnerGroup) -> List[int]: + restored = super().restore_env_runners(env_runner_group) + + # For the restored EnvRunners, send them the latest shared, global state + # from the `SharedDataActor`. + for restored_idx in restored: + state_ref = self.shared_data_actor.get.remote( + key=f"EnvRunner_{restored_idx}" + ) + env_runner_group.foreach_env_runner( + lambda env_runner, state=state_ref: env_runner._global_state, + remote_worker_ids=[restored_idx], + timeout_seconds=0.0, + ) + + return restored diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_differentiable_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_differentiable_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd2844c1800086f72857931769ebbbb05b5db3b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_differentiable_learner.py @@ -0,0 +1,35 @@ +from typing import Any, Dict, TYPE_CHECKING + +from ray.rllib.core.learner.torch.torch_differentiable_learner import ( + TorchDifferentiableLearner, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModuleID, TensorType + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +torch, nn = try_import_torch() + + +class MAMLTorchDifferentiableLearner(TorchDifferentiableLearner): + """A `TorchDifferentiableLearner` to perform MAML learning. + + This `TorchDifferentiableLearner` + - defines a funcitonal MSE loss for learning simple (here non-linear) + prediction. + """ + + @override(TorchDifferentiableLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + """Defines a simple MSE prediction loss for continuous task.""" + + return nn.functional.mse_loss(fwd_out["y_pred"], batch["y"]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_differentiable_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_differentiable_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa91895f0ded2da96e3abe846b89361b473c49d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_differentiable_rlm.py @@ -0,0 +1,39 @@ +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.torch.torch_rl_module import TorchRLModule +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class DifferentiableTorchRLModule(TorchRLModule): + """Differentiable neural network to learn sinusoid curves. + + This `TorchRLModule`: + - defines a simple neural network to learn sinusoid curves with two + feed forward layern and ReLU activations, + - defines a differentiable `forward` call by overriding the `_forward` + method (which is implicitly used by the module's `forward` method); this + enables `torch.func.functional_call?` to work. + """ + + def setup(self): + """Sets up a simple neural network + + The network contains two hidden layers and ReLU activations. Note, + input and output are single dimensional b/c the sinusoid curve is. + """ + self.net = nn.Sequential( + nn.Linear(1, 40), nn.ReLU(), nn.Linear(40, 40), nn.ReLU(), nn.Linear(40, 1) + ) + + def _forward(self, batch, **kwargs): + """Defines method to be called for general forward path. + + Note, it is important that the `RLModule.forward` method contains the + logic to be used for training forward pass b/c otherwise the functional + call via `torch.func.functional_call` will not work. See for reference + https://pytorch.org/docs/stable/generated/torch.func.functional_call.html. + """ + outs = {} + outs["y_pred"] = self.net(batch[Columns.OBS]) + return outs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_meta_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_meta_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..ef5643e83f6eafe57443db7946d61d2c9f43ff86 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/maml_lr_meta_learner.py @@ -0,0 +1,38 @@ +from typing import Any, Dict, List, TYPE_CHECKING + +from ray.rllib.core.learner.torch.torch_meta_learner import TorchMetaLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModuleID, TensorType + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +torch, nn = try_import_torch() + + +class MAMLTorchMetaLearner(TorchMetaLearner): + """A `TorchMetaLearner` to perform MAML learning. + + This `TorchMetaLearner` + - defines a MSE loss for learning simple (here non-linear) prediction. + """ + + @override(TorchMetaLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + others_loss_per_module: List[Dict[ModuleID, TensorType]] = None, + ) -> TensorType: + """Defines a simple MSE prediction loss for continuous task. + + Note, MAML does not need the losses from the registered differentiable + learners (contained in `others_loss_per_module`) b/c it computes a test + loss on an unseen data batch. + """ + # Use a simple MSE loss for the meta learning task. + return torch.nn.functional.mse_loss(fwd_out["y_pred"], batch["y"]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/vpg.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/vpg.py new file mode 100644 index 0000000000000000000000000000000000000000..2d31199271152034412bb7a7829d3be9875860b9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/classes/vpg.py @@ -0,0 +1,176 @@ +import tree # pip install dm_tree + +from ray.rllib.algorithms import Algorithm +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + ENV_RUNNER_SAMPLING_TIMER, + LEARNER_RESULTS, + LEARNER_UPDATE_TIMER, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + SYNCH_WORKER_WEIGHTS_TIMER, + TIMERS, +) + + +class VPGConfig(AlgorithmConfig): + """A simple VPG (vanilla policy gradient) algorithm w/o value function support. + + Use for testing purposes only! + + This Algorithm should use the VPGTorchLearner and VPGTorchRLModule + """ + + # A test setting to activate metrics on mean weights. + report_mean_weights: bool = True + + def __init__(self, algo_class=None): + super().__init__(algo_class=algo_class or VPG) + + # VPG specific settings. + self.num_episodes_per_train_batch = 10 + # Note that we don't have to set this here, because we tell the EnvRunners + # explicitly to sample entire episodes. However, for good measure, we change + # this setting here either way. + self.batch_mode = "complete_episodes" + + # VPG specific defaults (from AlgorithmConfig). + self.num_env_runners = 1 + + @override(AlgorithmConfig) + def training( + self, *, num_episodes_per_train_batch=NotProvided, **kwargs + ) -> "VPGConfig": + """Sets the training related configuration. + + Args: + num_episodes_per_train_batch: The number of complete episodes per train + batch. VPG requires entire episodes to be sampled from the EnvRunners. + For environments with varying episode lengths, this leads to varying + batch sizes (in timesteps) as well possibly causing slight learning + instabilities. However, for simplicity reasons, we stick to collecting + always exactly n episodes per training update. + + Returns: + This updated AlgorithmConfig object. + """ + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + + if num_episodes_per_train_batch is not NotProvided: + self.num_episodes_per_train_batch = num_episodes_per_train_batch + + return self + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self): + if self.framework_str == "torch": + from ray.rllib.examples.rl_modules.classes.vpg_torch_rlm import ( + VPGTorchRLModule, + ) + + spec = RLModuleSpec( + module_class=VPGTorchRLModule, + model_config={"hidden_dim": 64}, + ) + else: + raise ValueError(f"Unsupported framework: {self.framework_str}") + + return spec + + @override(AlgorithmConfig) + def get_default_learner_class(self): + if self.framework_str == "torch": + from ray.rllib.examples.learners.classes.vpg_torch_learner import ( + VPGTorchLearner, + ) + + return VPGTorchLearner + else: + raise ValueError(f"Unsupported framework: {self.framework_str}") + + +class VPG(Algorithm): + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return VPGConfig() + + @override(Algorithm) + def training_step(self) -> None: + """Override of the training_step method of `Algorithm`. + + Runs the following steps per call: + - Sample B timesteps (B=train batch size). Note that we don't sample complete + episodes due to simplicity. For an actual VPG algo, due to the loss computation, + you should always sample only completed episodes. + - Send the collected episodes to the VPG LearnerGroup for model updating. + - Sync the weights from LearnerGroup to all EnvRunners. + """ + # Sample. + with self.metrics.log_time((TIMERS, ENV_RUNNER_SAMPLING_TIMER)): + episodes, env_runner_results = self._sample_episodes() + # Merge results from n parallel sample calls into self's metrics logger. + self.metrics.aggregate(env_runner_results, key=ENV_RUNNER_RESULTS) + + # Just for demonstration purposes, log the number of time steps sampled in this + # `training_step` round. + # Mean over a window of 100: + self.metrics.log_value( + "episode_timesteps_sampled_mean_win100", + sum(map(len, episodes)), + reduce="mean", + window=100, + ) + # Exponential Moving Average (EMA) with coeff=0.1: + self.metrics.log_value( + "episode_timesteps_sampled_ema", + sum(map(len, episodes)), + ema_coeff=0.1, # <- weight of new value; weight of old avg=1.0-ema_coeff + ) + + # Update model. + with self.metrics.log_time((TIMERS, LEARNER_UPDATE_TIMER)): + learner_results = self.learner_group.update( + episodes=episodes, + timesteps={ + NUM_ENV_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME) + ) + ), + }, + ) + # Merge results from m parallel update calls into self's metrics logger. + self.metrics.aggregate(learner_results, key=LEARNER_RESULTS) + + # Sync weights. + with self.metrics.log_time((TIMERS, SYNCH_WORKER_WEIGHTS_TIMER)): + self.env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + + def _sample_episodes(self): + # How many episodes to sample from each EnvRunner? + num_episodes_per_env_runner = self.config.num_episodes_per_train_batch // ( + self.config.num_env_runners or 1 + ) + # Send parallel remote requests to sample and get the metrics. + sampled_data = self.env_runner_group.foreach_env_runner( + # Return tuple of [episodes], [metrics] from each EnvRunner. + lambda env_runner: ( + env_runner.sample(num_episodes=num_episodes_per_env_runner), + env_runner.get_metrics(), + ), + # Loop over remote EnvRunners' `sample()` method in parallel or use the + # local EnvRunner if there aren't any remote ones. + local_env_runner=self.env_runner_group.num_remote_workers() <= 0, + ) + # Return one list of episodes and a list of metrics dicts (one per EnvRunner). + episodes = tree.flatten([s[0] for s in sampled_data]) + stats_dicts = [s[1] for s in sampled_data] + + return episodes, stats_dicts diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/maml_lr_supervised_learning.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/maml_lr_supervised_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..24a3e8ab3952b5f25a358c0908e788edc4a123a8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/maml_lr_supervised_learning.py @@ -0,0 +1,443 @@ +"""Example of how to use `TorchMetaLearner` and `DifferentiableLearner` for MAML. + +Meta-learning, or “learning to learn,” trains models to quickly adapt to new tasks +using only a few examples. One prominent method is Model-Agnostic Meta-Learning +(MAML), which is compatible with any model trained via gradient descent. MAML has +been successfully applied across domains such as classification, regression, and +reinforcement learning. + +In this MAML example, the goal is to train a model that can adapt to an infinite +number of tasks, where each task corresponds to a sinusoidal function with randomly +sampled amplitude and phase. Because each new task introduces a shift in data +distribution, traditional learning algorithms would fail to generalize — they’d +overfit to the training task and struggle on unseen ones. Meta-learning addresses +this by optimizing the model parameters such that they can be fine-tuned rapidly +for any new task. + +During training, a DifferentiableLearner performs an inner-loop update using the +training error for each task. The outer-loop TorchMetaLearner then evaluates the +model’s performance on held-out data (the task's test set) and updates the meta- +parameters so that they lead to better generalization across all tasks. This bi- +level optimization ensures that gradients across tasks remain close, enabling +fast adaptation. + +At inference time, the trained model can adapt to a new task using just a small +batch of examples — performing few-shot learning to adjust quickly and accurately. + +This example shows: +- how to implement MAML with RLlib in just a few lines of code. +- how to define a `TorchDifferentiableLearner` to register a custom train loss + function. +- how to define a `TorchMetaLearner` class to implement a custom meta (test) train + loss function. +- how to configure both learners top be used with each others via the + `DifferentiableAlgorithmConfig` and `DifferentiableLearnerConfig`. +- how to update the `RLModule` in a meta-learning fashion. +- how to fine-tune an `RLModule` with gradient descent within a few iterations with + only using the meta (test) loss. + +See :py:class:`~ray.rllib.examples.learners.classes.lr_meta_learner.LRTorchMetaLearner` # noqa +class for details on how to override the main `TorchMetaLearner`. And see +:py:class:`~ray.rllib.examples.learners.classes.lr_differentiable_learner.LRTorchDifferentiableLearner` # noqa +class for an example of how to override the main `TorchDifferentiableLearner`. + +Note, the meta-learner needs a long-enough training (`default_iters`=~70,000) to learn +to adapt quickly to new tasks. + +How to run this script +---------------------- +`python [script file name].py --iters=70000 --meta-train-batch-size=5 --fine-tune-batch-size=5` + +Use the `--meta-train-batch-size` to set the training/testing batch size in meta-learning and +the `--fine-tune-batch-size` to adjust the number of samples used in all updates during +few-shot learning. + +To suppress plotting (plotting is the default) use `--no-plot` and for taking a longer +look at the plot increase the seconds for which plotting is paused at the end of the +script by `--pause-plot-secs`. + +Results to expect +----------------- +You should expect to see sometimes alternating test losses ("Total Loss") due to new +(unseen) tasks during meta learning. In few-shot learning after the meta-learning the +(few shot) loss should decrease almost monotonically. In the plot you can expect to see +a decent adaption to the new task after fine-tuning updates of the `RLModule` weights. + +With `--iters=70_000`, `--meta-train-batch-size=5`, `--fine-tune-batch-size=5`, +`--fine-tune-lr=0.01`, `--fine-tune-iters=10`, `--meta-lr=0.001`, `--noise-std=0.0`, +and no seed defined. +------------------------- + +Iteration: 68000 +Total loss: 0.013758559711277485 +------------------------- + +Iteration: 69000 +Total loss: 0.7246640920639038 +------------------------- + +Iteration: 70000 +Total loss: 3.091259002685547 + +Few shot loss: 2.754437208175659 +Few shot loss: 2.7399725914001465 +Few shot loss: 2.499554395675659 +Few shot loss: 2.1763901710510254 +Few shot loss: 1.793503999710083 +Few shot loss: 1.4362313747406006 +Few shot loss: 1.083552598953247 +Few shot loss: 0.7845061421394348 +Few shot loss: 0.5579453110694885 +Few shot loss: 0.4087105393409729 +""" +import gymnasium as gym +import matplotlib.pyplot as plt +import numpy as np + +from ray.rllib.algorithms.algorithm_config import DifferentiableAlgorithmConfig +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.differentiable_learner_config import ( + DifferentiableLearnerConfig, +) +from ray.rllib.core.learner.training_data import TrainingData +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.algorithms.classes.maml_lr_differentiable_learner import ( + MAMLTorchDifferentiableLearner, +) +from ray.rllib.examples.algorithms.classes.maml_lr_meta_learner import ( + MAMLTorchMetaLearner, +) +from ray.rllib.examples.algorithms.classes.maml_lr_differentiable_rlm import ( + DifferentiableTorchRLModule, +) +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import add_rllib_example_script_args + +# Import torch. +torch, _ = try_import_torch() + +# Implement generation of data from sinusoid curves. +def generate_sinusoid_task(batch_size, noise_std=0.1, return_params=False): + """Generate a sinusoid task with random amplitude and phase. + + Args: + batch_size: The number of data points to be generated. + noise_std: An optional standard deviation to be used in the sinusoid + data generation. Defines a linear error term added to the sine + curve. + return_params: If the sampled amplitude and phase should be returned. + + Returns: + Torch tensors with the support data and the labels of a sinusoid + curve. + """ + # Sample the amplitude and the phase for a task. + amplitude = np.random.uniform(0.1, 5.0) + phase = np.random.uniform(0.0, np.pi) + + # Sample the support. + x = np.random.uniform(-5.0, 5.0, (batch_size, 1)) + + # Generate the labels. + y = amplitude * np.sin(x - phase) + + # Add noise. + y += noise_std * np.random.random((batch_size, 1)) + + # If sampled parameters should be returned. + if return_params: + # Return torch tensors. + return ( + torch.tensor(x, dtype=torch.float32), + torch.tensor(y, dtype=torch.float32), + amplitude, + phase, + ) + # Otherwise, return only the sampled data. + else: + return ( + torch.tensor(x, dtype=torch.float32), + torch.tensor(y, dtype=torch.float32), + ) + + +def sample_task(batch_size=10, noise_std=0.1, training_data=False, return_params=False): + """Samples training batches for meta learner and differentiable learner. + + Args: + batch_size: The batch size for both meta learning and task learning. + noise_std: An optional standard deviation to be used in the sinusoid + data generation. Defines a linear error term added to the sine + curve. + training_data: Whether data should be returned as `TrainingData`. + Otherwise, a `MultiAgentBatch` is returned. Default is `False`. + return_params: If the sampled amplitude and phase should be returned. + + Returns: + A tuple with training batches for the meta learner and the differentiable + learner. If `training_data` is `True`, the data is wrapped into + `TrainingData`, otherwise both batches are `MultiAgentBatch`es. + + """ + # Generate training data for meta learner and differentiable learner. + train_batch = {} + generated_data = generate_sinusoid_task( + batch_size * 2, noise_std=noise_std, return_params=return_params + ) + train_batch[Columns.OBS], train_batch["y"] = generated_data[:2] + + # Convert to `MultiAgentBatch`. + meta_train_batch = MultiAgentBatch( + env_steps=batch_size, + policy_batches={ + DEFAULT_MODULE_ID: SampleBatch( + {k: train_batch[k][:batch_size] for k in train_batch} + ) + }, + ) + task_train_batch = MultiAgentBatch( + env_steps=batch_size, + policy_batches={ + DEFAULT_MODULE_ID: SampleBatch( + {k: train_batch[k][batch_size:] for k in train_batch} + ) + }, + ) + # If necessary convert to `TrainingData`. + if training_data: + meta_train_batch = TrainingData( + batch=meta_train_batch, + ) + task_train_batch = TrainingData( + batch=task_train_batch, + ) + + # If amplitude and phase should be returned add them to the return tuple. + if return_params: + return meta_train_batch, task_train_batch, *generated_data[2:] + # Otherwise return solely train data. + else: + return meta_train_batch, task_train_batch + + +# Define arguments. +parser = add_rllib_example_script_args(default_iters=70_000) + +parser.add_argument( + "--meta-train-batch-size", + type=int, + default=5, + help="The number of samples per train and test update (meta-learning).", +) +parser.add_argument( + "--meta-lr", + type=float, + default=0.001, + help="The learning rate to be used for meta learning (in the `MetaLearner`).", +) +parser.add_argument( + "--fine-tune-batch-size", + type=int, + default=10, + help="The number of samples for the fine-tuning updates.", +) +parser.add_argument( + "--noise-std", + type=float, + default=0.0, + help="The standard deviation for noise added to the single tasks.", +) +parser.add_argument( + "--seed", + type=int, + default=None, + help="An optional random seed. If not set, the experiment is not reproducable.", +) +parser.add_argument( + "--fine-tune-iters", + type=int, + default=10, + help="The number of updates in fine-tuning.", +) +parser.add_argument( + "--fine-tune-lr", + type=float, + default=0.01, + help="The learning rate to be used in fine-tuning the model in the test phase.", +) +parser.add_argument( + "--no-plot", + action="store_true", + help=( + "If plotting should suppressed. Otherwise user action is needed to close " + "the plot early." + ), +) +parser.add_argument( + "--pause-plot-secs", + type=int, + default=1000, + help=( + "The number of seconds to keep the plot open. Note the plot can always be " + "closed by the user when open." + ), +) + +# Parse the arguments. +args = parser.parse_args() + +# If a random seed is provided set it for torch and numpy. +if args.seed: + torch.random.manual_seed(args.seed) + np.random.seed(args.seed) + + +if __name__ == "__main__": + # Define the `RLModule`. + module_spec = RLModuleSpec( + module_class=DifferentiableTorchRLModule, + # Note, the spaces are needed by default but are not used. + observation_space=gym.spaces.Box(-np.inf, np.inf, (1,), dtype=np.float32), + action_space=gym.spaces.Box(-np.inf, np.inf, (1,), dtype=np.float32), + ) + # `Learner`s work on `MultiRLModule`s. + multi_module_spec = MultiRLModuleSpec( + rl_module_specs={DEFAULT_MODULE_ID: module_spec} + ) + + # Build the `MultiRLModule`. + module = multi_module_spec.build() + + # Configure the `DifferentiableLearner`. + diff_learner_config = DifferentiableLearnerConfig( + learner_class=MAMLTorchDifferentiableLearner, + minibatch_size=args.meta_train_batch_size, + lr=0.01, + ) + + # Configure the `TorchMetaLearner` via the `DifferentiableAlgorithmConfig`. + config = ( + DifferentiableAlgorithmConfig() + .learners( + # Add the `DifferentiableLearnerConfig`s. + differentiable_learner_configs=[diff_learner_config], + num_gpus_per_learner=args.num_gpus_per_learner or 0, + ) + .training( + lr=args.meta_lr, + train_batch_size=args.meta_train_batch_size, + # Use the full batch in a single update. + minibatch_size=args.meta_train_batch_size, + ) + ) + + # Initialize the `TorchMetaLearner`. + meta_learner = MAMLTorchMetaLearner(config=config, module_spec=module_spec) + # Build the `TorchMetaLearner`. + meta_learner.build() + + for i in range(args.stop_iters): + # Sample the training data. + meta_training_data, task_training_data = sample_task( + args.meta_train_batch_size, noise_std=args.noise_std, training_data=True + ) + + # Update the module. + outs = meta_learner.update( + training_data=meta_training_data, + num_epochs=1, + others_training_data=[task_training_data], + ) + iter = i + 1 + if iter % 1000 == 0: + total_loss = outs["default_policy"]["total_loss"].peek() + print("-------------------------\n") + print(f"Iteration: {iter}") + print(f"Total loss: {total_loss}") + + # Generate test data. + test_batch, _, amplitude, phase = sample_task( + batch_size=args.fine_tune_batch_size, + noise_std=args.noise_std, + return_params=True, + ) + + if config.num_gpus_per_learner > 0: + test_batch = meta_learner._convert_batch_type(test_batch) + + # Run inference and plot results. + with torch.no_grad(): + # Generate a grid for the support. + x_grid = torch.tensor( + np.arange(-5.0, 5.0, 0.02), dtype=torch.float32, device=meta_learner._device + ).view(-1, 1) + # Get label prediction from the model trained by MAML. + y_pred = meta_learner.module[DEFAULT_MODULE_ID]({Columns.OBS: x_grid})["y_pred"] + + # Plot the results if requested. + if not args.no_plot: + # Sort the data by the support. + x_order = np.argsort(test_batch[DEFAULT_MODULE_ID][Columns.OBS].numpy()[:, 0]) + x_sorted = test_batch[DEFAULT_MODULE_ID][Columns.OBS].numpy()[:, 0][x_order] + y_sorted = test_batch[DEFAULT_MODULE_ID]["y"][:, 0][x_order] + + # Plot the data. + def sinusoid(t): + return amplitude * np.sin(t - phase) + + plt.ion() + plt.figure(figsize=(5, 3)) + # Plot the true sinusoid curve. + plt.plot(x_grid, sinusoid(x_grid), "r", label="Ground Truth") + # Add the sampled support values. + plt.plot(x_sorted, y_sorted, "^", color="purple") + # Add the prediction made by the model after MAML training. + plt.plot(x_grid, y_pred, ":", label="Prediction", color="#90EE90") + plt.title(f"MAML Results from {args.fine_tune_iters} fine-tuning steps.") + + # Fine-tune with the meta loss for just a few steps. + optim = meta_learner.get_optimizers_for_module(DEFAULT_MODULE_ID)[0][1] + # Set the learning rate to a larger value. + for g in optim.param_groups: + g["lr"] = args.fine_tune_lr + # Now run the fine-tune iterations and update the model via the meta-learner loss. + for i in range(args.fine_tune_iters): + # Forward pass. + fwd_out = { + DEFAULT_MODULE_ID: meta_learner.module[DEFAULT_MODULE_ID]( + test_batch[DEFAULT_MODULE_ID] + ) + } + # Compute the MSE prediction loss. + loss_per_module = meta_learner.compute_losses(fwd_out=fwd_out, batch=test_batch) + # Optimize parameters. + optim.zero_grad(set_to_none=True) + loss_per_module[DEFAULT_MODULE_ID].backward() + optim.step() + # Show the loss for few-shot learning (fine-tuning). + print(f"Few shot loss: {loss_per_module[DEFAULT_MODULE_ID].item()}") + + # Run the model again after fine-tuning. + with torch.no_grad(): + y_pred_fine_tuned = meta_learner.module[DEFAULT_MODULE_ID]( + {Columns.OBS: x_grid} + )["y_pred"] + + if not args.no_plot: + # Plot the predictions of the fine-tuned model. + plt.plot( + x_grid, + y_pred_fine_tuned, + "-.", + label="Tuned Prediction", + color="green", + mfc="gray", + ) + plt.legend() + plt.show() + + # Pause the plot until the user closes it. + plt.pause(args.pause_plot_secs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/vpg_custom_algorithm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/vpg_custom_algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..73757a8af8c1579ac600ae902414525a3624ed0f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/algorithms/vpg_custom_algorithm.py @@ -0,0 +1,116 @@ +"""Example of how to write a custom Algorithm. + +This is an end-to-end example for how to implement a custom Algorithm, including +a matching AlgorithmConfig class and Learner class. There is no particular RLModule API +needed for this algorithm, which means that any TorchRLModule returning actions +or action distribution parameters suffices. + +The RK algorithm implemented here is "vanilla policy gradient" (VPG) in its simplest +form, without a value function baseline. + +See the actual VPG algorithm class here: +https://github.com/ray-project/ray/blob/master/rllib/examples/algorithms/classes/vpg.py + +The Learner class the algorithm uses by default (if the user doesn't specify a custom +Learner): +https://github.com/ray-project/ray/blob/master/rllib/examples/learners/classes/vpg_torch_learner.py # noqa + +And the RLModule class the algorithm uses by default (if the user doesn't specify a +custom RLModule): +https://github.com/ray-project/ray/blob/master/rllib/examples/rl_modules/classes/vpg_torch_rlm.py # noqa + +This example shows: + - how to subclass the AlgorithmConfig base class to implement a custom algorithm's. + config class. + - how to subclass the Algorithm base class to implement a custom Algorithm, + including its `training_step` method. + - how to subclass the TorchLearner base class to implement a custom Learner with + loss function, overriding `compute_loss_for_module` and + `after_gradient_based_update`. + - how to define a default RLModule used by the algorithm in case the user + doesn't bring their own custom RLModule. The VPG algorithm doesn't require any + specific RLModule APIs, so any RLModule returning actions or action distribution + inputs suffices. + +We compute a plain policy gradient loss without value function baseline. +The experiment shows that even with such a simple setup, our custom algorithm is still +able to successfully learn CartPole-v1. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +With some fine-tuning of the learning rate, the batch size, and maybe the +number of env runners and number of envs per env runner, you should see decent +learning behavior on the CartPole-v1 environment: + ++-----------------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|-----------------------------+------------+--------+------------------+ +| VPG_CartPole-v1_2973e_00000 | TERMINATED | 451 | 59.5184 | ++-----------------------------+------------+--------+------------------+ ++-----------------------+------------------------+------------------------+ +| episode_return_mean | num_env_steps_sample | ...env_steps_sampled | +| | d_lifetime | _lifetime_throughput | +|-----------------------+------------------------+------------------------| +| 250.52 | 415787 | 7428.98 | ++-----------------------+------------------------+------------------------+ +""" + +from ray.rllib.examples.algorithms.classes.vpg import VPGConfig +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + + +parser = add_rllib_example_script_args( + default_reward=250.0, + default_iters=1000, + default_timesteps=1_000_000, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + VPGConfig() + .environment("CartPole-v1") + .training( + # The only VPG-specific setting. How many episodes per train batch? + num_episodes_per_train_batch=10, + # Set other config parameters. + lr=0.0005, + # Note that you don't have to set any specific Learner class, because + # our custom Algorithm already defines the default Learner class to use + # through its `get_default_learner_class` method, which returns + # `VPGTorchLearner`. + # learner_class=VPGTorchLearner, + ) + # Increase the number of EnvRunners (default is 1 for VPG) + # or the number of envs per EnvRunner. + .env_runners(num_env_runners=2, num_envs_per_env_runner=1) + # Plug in your own RLModule class. VPG doesn't require any specific + # RLModule APIs, so any RLModule returning `actions` or `action_dist_inputs` + # from the forward methods works ok. + # .rl_module( + # rl_module_spec=RLModuleSpec(module_class=...), + # ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5792b26e3b23b3d75b3691121a85fa808ac6ebec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/cartpole_dqn_export.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/cartpole_dqn_export.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae995796aa341d6067931bee4c11a23daa924bab Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/cartpole_dqn_export.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/change_config_during_training.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/change_config_during_training.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4d820fbd567214b1901203355d485e19db3bddf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/change_config_during_training.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/checkpoint_by_custom_criteria.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/checkpoint_by_custom_criteria.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd82ddbb1b0b783012f55b45819a45f457b2de15 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/checkpoint_by_custom_criteria.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/continue_training_from_checkpoint.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/continue_training_from_checkpoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e90e592e4342a370b63490d8e4b5be7df37a05fe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/continue_training_from_checkpoint.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch_lstm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch_lstm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b94dc41ad8e6c772a054b5db44d97993963feae Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch_lstm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/restore_1_of_n_agents_from_checkpoint.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/restore_1_of_n_agents_from_checkpoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19aa5fa3095816060b7df4c02753c4e8ace007db Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/__pycache__/restore_1_of_n_agents_from_checkpoint.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/cartpole_dqn_export.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/cartpole_dqn_export.py new file mode 100644 index 0000000000000000000000000000000000000000..790940082263edcfc01f56fc18d3fef07b86f933 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/cartpole_dqn_export.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python + +# @OldAPIStack + +import numpy as np +import os +import ray + +import ray._common +from ray.rllib.policy.policy import Policy +from ray.rllib.utils.framework import try_import_tf +from ray.tune.registry import get_trainable_cls + +tf1, tf, tfv = try_import_tf() + +ray.init() + + +def train_and_export_policy_and_model(algo_name, num_steps, model_dir, ckpt_dir): + cls = get_trainable_cls(algo_name) + config = cls.get_default_config() + config.api_stack( + enable_rl_module_and_learner=False, + enable_env_runner_and_connector_v2=False, + ) + # This Example is only for tf. + config.framework("tf") + # Set exporting native (DL-framework) model files to True. + config.export_native_model_files = True + config.env = "CartPole-v1" + alg = config.build() + for _ in range(num_steps): + alg.train() + + # Export Policy checkpoint. + alg.export_policy_checkpoint(ckpt_dir) + # Export tensorflow keras Model for online serving + alg.export_policy_model(model_dir) + + +def restore_saved_model(export_dir): + signature_key = ( + tf1.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + ) + g = tf1.Graph() + with g.as_default(): + with tf1.Session(graph=g) as sess: + meta_graph_def = tf1.saved_model.load( + sess, [tf1.saved_model.tag_constants.SERVING], export_dir + ) + print("Model restored!") + print("Signature Def Information:") + print(meta_graph_def.signature_def[signature_key]) + print("You can inspect the model using TensorFlow SavedModel CLI.") + print("https://www.tensorflow.org/guide/saved_model") + + +def restore_policy_from_checkpoint(export_dir): + # Load the model from the checkpoint. + policy = Policy.from_checkpoint(export_dir) + # Perform a dummy (CartPole) forward pass. + test_obs = np.array([0.1, 0.2, 0.3, 0.4]) + results = policy.compute_single_action(test_obs) + # Check results for correctness. + assert len(results) == 3 + assert results[0].shape == () # pure single action (int) + assert results[1] == [] # RNN states + assert results[2]["action_dist_inputs"].shape == (2,) # categorical inputs + + +if __name__ == "__main__": + algo = "PPO" + model_dir = os.path.join(ray._common.utils.get_user_temp_dir(), "model_export_dir") + ckpt_dir = os.path.join(ray._common.utils.get_user_temp_dir(), "ckpt_export_dir") + num_steps = 1 + train_and_export_policy_and_model(algo, num_steps, model_dir, ckpt_dir) + restore_saved_model(model_dir) + restore_policy_from_checkpoint(ckpt_dir) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/change_config_during_training.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/change_config_during_training.py new file mode 100644 index 0000000000000000000000000000000000000000..373a47b68aacd70c3c30a71c23bc5dadacebe625 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/change_config_during_training.py @@ -0,0 +1,246 @@ +"""Example showing how to continue training an Algorithm with a changed config. + +Use the setup shown in this script if you want to continue a prior experiment, but +would also like to change some of the config values you originally used. + +This example: + - runs a single- or multi-agent CartPole experiment (for multi-agent, we use + different learning rates) thereby checkpointing the state of the Algorithm every n + iterations. The config used is hereafter called "1st config". + - stops the experiment due to some episode return being achieved. + - just for testing purposes, restores the entire algorithm from the latest + checkpoint and checks, whether the state of the restored algo exactly match the + state of the previously saved one. + - then changes the original config used (learning rate and other settings) and + continues training with the restored algorithm and the changed config until a + final episode return is reached. The new config is hereafter called "2nd config". + + +How to run this script +---------------------- +`python [script file name].py --num-agents=[0 or 2] +--stop-reward-first-config=[return at which the algo on 1st config should stop training] +--stop-reward=[the final return to achieve after restoration from the checkpoint with +the 2nd config] +` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +First, you should see the initial tune.Tuner do it's thing: + +Trial status: 1 RUNNING +Current time: 2024-06-03 12:03:39. Total running time: 30s +Logical resource usage: 3.0/12 CPUs, 0/0 GPUs +╭──────────────────────────────────────────────────────────────────────── +│ Trial name status iter total time (s) +├──────────────────────────────────────────────────────────────────────── +│ PPO_CartPole-v1_7b1eb_00000 RUNNING 6 16.265 +╰──────────────────────────────────────────────────────────────────────── +───────────────────────────────────────────────────────────────────────╮ +..._sampled_lifetime ..._trained_lifetime ...episodes_lifetime │ +───────────────────────────────────────────────────────────────────────┤ + 24000 24000 340 │ +───────────────────────────────────────────────────────────────────────╯ +... + +The experiment stops at an average episode return of `--stop-reward-first-config`. + +After the validation of the last checkpoint, a new experiment is started from +scratch, but with the RLlib callback restoring the Algorithm right after +initialization using the previous checkpoint. This new experiment then runs +until `--stop-reward` is reached. + +Trial status: 1 RUNNING +Current time: 2024-06-03 12:05:00. Total running time: 1min 0s +Logical resource usage: 3.0/12 CPUs, 0/0 GPUs +╭──────────────────────────────────────────────────────────────────────── +│ Trial name status iter total time (s) +├──────────────────────────────────────────────────────────────────────── +│ PPO_CartPole-v1_7b1eb_00000 RUNNING 23 14.8372 +╰──────────────────────────────────────────────────────────────────────── +───────────────────────────────────────────────────────────────────────╮ +..._sampled_lifetime ..._trained_lifetime ...episodes_lifetime │ +───────────────────────────────────────────────────────────────────────┤ + 109078 109078 531 │ +───────────────────────────────────────────────────────────────────────╯ + +And if you are using the `--as-test` option, you should see a finel message: + +``` +`env_runners/episode_return_mean` of 450.0 reached! ok +``` +""" +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + LEARNER_RESULTS, +) +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + check, + run_rllib_example_script_experiment, +) +from ray.tune.registry import register_env + + +parser = add_rllib_example_script_args( + default_reward=450.0, default_timesteps=10000000, default_iters=2000 +) +parser.add_argument( + "--stop-reward-first-config", + type=float, + default=150.0, + help="Mean episode return after which the Algorithm on the first config should " + "stop training.", +) +# By default, set `args.checkpoint_freq` to 1 and `args.checkpoint_at_end` to True. +parser.set_defaults( + checkpoint_freq=1, + checkpoint_at_end=True, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + register_env( + "ma_cart", lambda cfg: MultiAgentCartPole({"num_agents": args.num_agents}) + ) + + # Simple generic config. + base_config = ( + PPOConfig() + .environment("CartPole-v1" if args.num_agents == 0 else "ma_cart") + .env_runners(create_env_on_local_worker=True) + .training(lr=0.0001) + # TODO (sven): Tune throws a weird error inside the "log json" callback + # when running with this option. The `perf` key in the result dict contains + # binary data (instead of just 2 float values for mem and cpu usage). + # .experimental(_use_msgpack_checkpoints=True) + ) + + # Setup multi-agent, if required. + if args.num_agents > 0: + base_config.multi_agent( + policies={ + f"p{aid}": PolicySpec( + config=AlgorithmConfig.overrides( + lr=5e-5 + * (aid + 1), # agent 1 has double the learning rate as 0. + ) + ) + for aid in range(args.num_agents) + }, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # Define some stopping criterion. Note that this criterion is an avg episode return + # to be reached. + metric = f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + stop = {metric: args.stop_reward_first_config} + + tuner_results = run_rllib_example_script_experiment( + base_config, + args, + stop=stop, + keep_ray_up=True, + ) + + # Perform a very quick test to make sure our algo (upon restoration) did not lose + # its ability to perform well in the env. + # - Extract the best checkpoint. + best_result = tuner_results.get_best_result(metric=metric, mode="max") + assert ( + best_result.metrics[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + >= args.stop_reward_first_config + ) + best_checkpoint_path = best_result.checkpoint.path + + # Rebuild the algorithm (just for testing purposes). + test_algo = base_config.build() + # Load algo's state from the best checkpoint. + test_algo.restore_from_path(best_checkpoint_path) + # Perform some checks on the restored state. + assert test_algo.training_iteration > 0 + # Evaluate on the restored algorithm. + test_eval_results = test_algo.evaluate() + assert ( + test_eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + >= args.stop_reward_first_config + ), test_eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + # Train one iteration to make sure, the performance does not collapse (e.g. due + # to the optimizer weights not having been restored properly). + test_results = test_algo.train() + assert ( + test_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + >= args.stop_reward_first_config + ), test_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + # Stop the test algorithm again. + test_algo.stop() + + # Make sure the algorithm gets restored from a checkpoint right after + # initialization. Note that this includes all subcomponents of the algorithm, + # including the optimizer states in the LearnerGroup/Learner actors. + def on_algorithm_init(algorithm, **kwargs): + module_p0 = algorithm.get_module("p0") + weight_before = convert_to_numpy(next(iter(module_p0.parameters()))) + + algorithm.restore_from_path(best_checkpoint_path) + + # Make sure weights were restored (changed). + weight_after = convert_to_numpy(next(iter(module_p0.parameters()))) + check(weight_before, weight_after, false=True) + + # Change the config. + ( + base_config + # Make sure the algorithm gets restored upon initialization. + .callbacks(on_algorithm_init=on_algorithm_init) + # Change training parameters considerably. + .training( + lr=0.0003, + train_batch_size=5000, + grad_clip=100.0, + gamma=0.996, + num_epochs=6, + vf_loss_coeff=0.01, + ) + # Make multi-CPU/GPU. + .learners(num_learners=2) + # Use more env runners and more envs per env runner. + .env_runners(num_env_runners=3, num_envs_per_env_runner=5) + ) + + # Update the stopping criterium to the final target return per episode. + stop = {metric: args.stop_reward} + + # Run a new experiment with the (RLlib) callback `on_algorithm_init` restoring + # from the best checkpoint. + # Note that the new experiment starts again from iteration=0 (unlike when you + # use `tune.Tuner.restore()` after a crash or interrupted trial). + tuner_results = run_rllib_example_script_experiment(base_config, args, stop=stop) + + # Assert that we have continued training with a different learning rate. + assert ( + tuner_results[0].metrics[LEARNER_RESULTS][DEFAULT_MODULE_ID][ + "default_optimizer_learning_rate" + ] + == base_config.lr + == 0.0003 + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/checkpoint_by_custom_criteria.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/checkpoint_by_custom_criteria.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8d30818565b37110db97b04c75697af15d6cba --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/checkpoint_by_custom_criteria.py @@ -0,0 +1,148 @@ +"""Example extracting a checkpoint from n trials using one or more custom criteria. + +This example: + - runs a CartPole experiment with three different learning rates (three tune + "trials"). During the experiment, for each trial, we create a checkpoint at each + iteration. + - at the end of the experiment, we compare the trials and pick the one that + performed best, based on the criterion: Lowest episode count per single iteration + (for CartPole, a low episode count means the episodes are very long and thus the + reward is also very high). + - from that best trial (with the lowest episode count), we then pick those + checkpoints that a) have the lowest policy loss (good) and b) have the highest value + function loss (bad). + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see the performance of the three different learning +rates used here: + ++-----------------------------+------------+-----------------+--------+--------+ +| Trial name | status | loc | lr | iter | +|-----------------------------+------------+-----------------+--------+--------+ +| PPO_CartPole-v1_d7dbe_00000 | TERMINATED | 127.0.0.1:98487 | 0.01 | 17 | +| PPO_CartPole-v1_d7dbe_00001 | TERMINATED | 127.0.0.1:98488 | 0.001 | 8 | +| PPO_CartPole-v1_d7dbe_00002 | TERMINATED | 127.0.0.1:98489 | 0.0001 | 9 | ++-----------------------------+------------+-----------------+--------+--------+ + ++------------------+-------+----------+----------------------+----------------------+ +| total time (s) | ts | reward | episode_reward_max | episode_reward_min | +|------------------+-------+----------+----------------------+----------------------+ +| 28.1068 | 39797 | 151.11 | 500 | 12 | +| 13.304 | 18728 | 158.91 | 500 | 15 | +| 14.8848 | 21069 | 167.36 | 500 | 13 | ++------------------+-------+----------+----------------------+----------------------+ + ++--------------------+ +| episode_len_mean | +|--------------------| +| 151.11 | +| 158.91 | +| 167.36 | ++--------------------+ +""" + +from ray import tune +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + LEARNER_RESULTS, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_reward=450.0, + default_timesteps=100000, + default_iters=200, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Force-set `args.checkpoint_freq` to 1. + args.checkpoint_freq = 1 + + # Simple generic config. + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("CartPole-v1") + # Run 3 trials, each w/ a different learning rate. + .training(lr=tune.grid_search([0.01, 0.001, 0.0001]), train_batch_size=2341) + ) + # Run tune for some iterations and generate checkpoints. + results = run_rllib_example_script_experiment(base_config, args) + + # Get the best of the 3 trials by using some metric. + # NOTE: Choosing the min `episodes_this_iter` automatically picks the trial + # with the best performance (over the entire run (scope="all")): + # The fewer episodes, the longer each episode lasted, the more reward we + # got each episode. + # Setting scope to "last", "last-5-avg", or "last-10-avg" will only compare + # (using `mode=min|max`) the average values of the last 1, 5, or 10 + # iterations with each other, respectively. + # Setting scope to "avg" will compare (using `mode`=min|max) the average + # values over the entire run. + metric = "env_runners/num_episodes" + # notice here `scope` is `all`, meaning for each trial, + # all results (not just the last one) will be examined. + best_result = results.get_best_result(metric=metric, mode="min", scope="all") + value_best_metric = best_result.metrics_dataframe[metric].min() + best_return_best = best_result.metrics_dataframe[ + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + ].max() + print( + f"Best trial was the one with lr={best_result.metrics['config']['lr']}. " + f"Reached lowest episode count ({value_best_metric}) in a single iteration and " + f"an average return of {best_return_best}." + ) + + # Confirm, we picked the right trial. + + assert ( + value_best_metric + == results.get_dataframe(filter_metric=metric, filter_mode="min")[metric].min() + ) + + # Get the best checkpoints from the trial, based on different metrics. + # Checkpoint with the lowest policy loss value: + if not args.old_api_stack: + policy_loss_key = f"{LEARNER_RESULTS}/{DEFAULT_MODULE_ID}/policy_loss" + else: + policy_loss_key = "info/learner/default_policy/learner_stats/policy_loss" + best_result = results.get_best_result(metric=policy_loss_key, mode="min") + ckpt = best_result.checkpoint + lowest_policy_loss = best_result.metrics_dataframe[policy_loss_key].min() + print(f"Checkpoint w/ lowest policy loss ({lowest_policy_loss}): {ckpt}") + + # Checkpoint with the highest value-function loss: + if not args.old_api_stack: + vf_loss_key = f"{LEARNER_RESULTS}/{DEFAULT_MODULE_ID}/vf_loss" + else: + vf_loss_key = "info/learner/default_policy/learner_stats/vf_loss" + best_result = results.get_best_result(metric=vf_loss_key, mode="max") + ckpt = best_result.checkpoint + highest_value_fn_loss = best_result.metrics_dataframe[vf_loss_key].max() + print(f"Checkpoint w/ highest value function loss: {ckpt}") + print(f"Highest value function loss: {highest_value_fn_loss}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/continue_training_from_checkpoint.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/continue_training_from_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..f28b720d5d96a7509f245242b15c362017f642fe --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/continue_training_from_checkpoint.py @@ -0,0 +1,267 @@ +"""Example showing how to restore an Algorithm from a checkpoint and resume training. + +Use the setup shown in this script if your experiments tend to crash after some time, +and you would therefore like to make your setup more robust and fault-tolerant. + +This example: + - runs a single- or multi-agent CartPole experiment (for multi-agent, we use + different learning rates) thereby checkpointing the state of the Algorithm every n + iterations. + - stops the experiment due to an expected crash in the algorithm's main process + after a certain number of iterations. + - just for testing purposes, restores the entire algorithm from the latest + checkpoint and checks, whether the state of the restored algo exactly match the + state of the crashed one. + - then continues training with the restored algorithm until the desired final + episode return is reached. + + +How to run this script +---------------------- +`python [script file name].py --num-agents=[0 or 2] +--stop-reward-crash=[the episode return after which the algo should crash] +--stop-reward=[the final episode return to achieve after(!) restoration from the +checkpoint] +` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +First, you should see the initial tune.Tuner do it's thing: + +Trial status: 1 RUNNING +Current time: 2024-06-03 12:03:39. Total running time: 30s +Logical resource usage: 3.0/12 CPUs, 0/0 GPUs +╭──────────────────────────────────────────────────────────────────────── +│ Trial name status iter total time (s) +├──────────────────────────────────────────────────────────────────────── +│ PPO_CartPole-v1_7b1eb_00000 RUNNING 6 15.362 +╰──────────────────────────────────────────────────────────────────────── +───────────────────────────────────────────────────────────────────────╮ +..._sampled_lifetime ..._trained_lifetime ...episodes_lifetime │ +───────────────────────────────────────────────────────────────────────┤ + 24000 24000 340 │ +───────────────────────────────────────────────────────────────────────╯ +... + +then, you should see the experiment crashing as soon as the `--stop-reward-crash` +has been reached: + +```RuntimeError: Intended crash after reaching trigger return.``` + +At some point, the experiment should resume exactly where it left off (using +the checkpoint and restored Tuner): + +Trial status: 1 RUNNING +Current time: 2024-06-03 12:05:00. Total running time: 1min 0s +Logical resource usage: 3.0/12 CPUs, 0/0 GPUs +╭──────────────────────────────────────────────────────────────────────── +│ Trial name status iter total time (s) +├──────────────────────────────────────────────────────────────────────── +│ PPO_CartPole-v1_7b1eb_00000 RUNNING 27 66.1451 +╰──────────────────────────────────────────────────────────────────────── +───────────────────────────────────────────────────────────────────────╮ +..._sampled_lifetime ..._trained_lifetime ...episodes_lifetime │ +───────────────────────────────────────────────────────────────────────┤ + 108000 108000 531 │ +───────────────────────────────────────────────────────────────────────╯ + +And if you are using the `--as-test` option, you should see a finel message: + +``` +`env_runners/episode_return_mean` of 500.0 reached! ok +``` +""" +import re +import time + +from ray import tune +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + check_learning_achieved, +) +from ray.tune.registry import get_trainable_cls, register_env +from ray.air.integrations.wandb import WandbLoggerCallback + + +parser = add_rllib_example_script_args( + default_reward=500.0, default_timesteps=10000000, default_iters=2000 +) +parser.add_argument( + "--stop-reward-crash", + type=float, + default=200.0, + help="Mean episode return after which the Algorithm should crash.", +) +# By default, set `args.checkpoint_freq` to 1 and `args.checkpoint_at_end` to True. +parser.set_defaults( + checkpoint_freq=1, + checkpoint_at_end=True, +) + + +class CrashAfterNIters(RLlibCallback): + """Callback that makes the algo crash after a certain avg. return is reached.""" + + def __init__(self): + super().__init__() + # We have to delay crashing by one iteration just so the checkpoint still + # gets created by Tune after(!) we have reached the trigger avg. return. + self._should_crash = False + + def on_train_result(self, *, algorithm, metrics_logger, result, **kwargs): + # We had already reached the mean-return to crash, the last checkpoint written + # (the one from the previous iteration) should yield that exact avg. return. + if self._should_crash: + raise RuntimeError("Intended crash after reaching trigger return.") + # Reached crashing criterion, crash on next iteration. + elif result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= args.stop_reward_crash: + print( + "Reached trigger return of " + f"{result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]}" + ) + self._should_crash = True + + +if __name__ == "__main__": + args = parser.parse_args() + + register_env( + "ma_cart", lambda cfg: MultiAgentCartPole({"num_agents": args.num_agents}) + ) + + # Simple generic config. + config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("CartPole-v1" if args.num_agents == 0 else "ma_cart") + .env_runners(create_env_on_local_worker=True) + .training(lr=0.0001) + .callbacks(CrashAfterNIters) + ) + + # Tune config. + # Need a WandB callback? + tune_callbacks = [] + if args.wandb_key: + project = args.wandb_project or ( + args.algo.lower() + "-" + re.sub("\\W+", "-", str(config.env).lower()) + ) + tune_callbacks.append( + WandbLoggerCallback( + api_key=args.wandb_key, + project=args.wandb_project, + upload_checkpoints=False, + **({"name": args.wandb_run_name} if args.wandb_run_name else {}), + ) + ) + + # Setup multi-agent, if required. + if args.num_agents > 0: + config.multi_agent( + policies={ + f"p{aid}": PolicySpec( + config=AlgorithmConfig.overrides( + lr=5e-5 + * (aid + 1), # agent 1 has double the learning rate as 0. + ) + ) + for aid in range(args.num_agents) + }, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # Define some stopping criterion. Note that this criterion is an avg episode return + # to be reached. The stop criterion does not consider the built-in crash we are + # triggering through our callback. + stop = { + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + + # Run tune for some iterations and generate checkpoints. + tuner = tune.Tuner( + trainable=config.algo_class, + param_space=config, + run_config=tune.RunConfig( + callbacks=tune_callbacks, + checkpoint_config=tune.CheckpointConfig( + checkpoint_frequency=args.checkpoint_freq, + checkpoint_at_end=args.checkpoint_at_end, + ), + stop=stop, + ), + ) + tuner_results = tuner.fit() + + # Perform a very quick test to make sure our algo (upon restoration) did not lose + # its ability to perform well in the env. + # - Extract the best checkpoint. + metric = f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + best_result = tuner_results.get_best_result(metric=metric, mode="max") + assert ( + best_result.metrics[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + >= args.stop_reward_crash + ) + # - Change our config, such that the restored algo will have an env on the local + # EnvRunner (to perform evaluation) and won't crash anymore (remove the crashing + # callback). + config.callbacks(None) + # Rebuild the algorithm (just for testing purposes). + test_algo = config.build() + # Load algo's state from best checkpoint. + test_algo.restore(best_result.checkpoint) + # Perform some checks on the restored state. + assert test_algo.training_iteration > 0 + # Evaluate on the restored algorithm. + test_eval_results = test_algo.evaluate() + assert ( + test_eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + >= args.stop_reward_crash + ), test_eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + # Train one iteration to make sure, the performance does not collapse (e.g. due + # to the optimizer weights not having been restored properly). + test_results = test_algo.train() + assert ( + test_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= args.stop_reward_crash + ), test_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + # Stop the test algorithm again. + test_algo.stop() + + # Create a new Tuner from the existing experiment path (which contains the tuner's + # own checkpoint file). Note that even the WandB logging will be continued without + # creating a new WandB run name. + restored_tuner = tune.Tuner.restore( + path=tuner_results.experiment_path, + trainable=config.algo_class, + param_space=config, + # Important to set this to True b/c the previous trial had failed (due to our + # `CrashAfterNIters` callback). + resume_errored=True, + ) + # Continue the experiment exactly where we left off. + tuner_results = restored_tuner.fit() + + # Not sure, whether this is really necessary, but we have observed the WandB + # logger sometimes not logging some of the last iterations. This sleep here might + # give it enough time to do so. + time.sleep(20) + + if args.as_test: + check_learning_achieved(tuner_results, args.stop_reward, metric=metric) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/onnx_torch_lstm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/onnx_torch_lstm.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f3a3dc2319c3c2d43c6b6c2a6eb1cc242b07a9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/onnx_torch_lstm.py @@ -0,0 +1,131 @@ +# @OldAPIStack + +import numpy as np +import onnxruntime + +import ray +import ray.rllib.algorithms.ppo as ppo +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import add_rllib_example_script_args, check +from ray.rllib.utils.torch_utils import convert_to_torch_tensor + +torch, _ = try_import_torch() + +parser = add_rllib_example_script_args() +parser.set_defaults( + num_env_runners=1, + # ONNX is not supported by RLModule API yet. + old_api_stack=True, +) + + +class ONNXCompatibleWrapper(torch.nn.Module): + def __init__(self, original_model): + super(ONNXCompatibleWrapper, self).__init__() + self.original_model = original_model + + def forward(self, a, b0, b1, c): + # Convert the separate tensor inputs back into the list format + # expected by the original model's forward method. + b = [b0, b1] + ret = self.original_model({"obs": a}, b, c) + # results, state_out_0, state_out_1 + return ret[0], ret[1][0], ret[1][1] + + +if __name__ == "__main__": + args = parser.parse_args() + + ray.init(local_mode=args.local_mode) + + # Configure our PPO Algorithm. + config = ( + ppo.PPOConfig() + .environment("CartPole-v1") + .env_runners(num_env_runners=args.num_env_runners) + .training(model={"use_lstm": True}) + ) + + B = 3 + T = 5 + LSTM_CELL = 256 + + # Input data for a python inference forward call. + test_data_python = { + "obs": np.random.uniform(0, 1.0, size=(B * T, 4)).astype(np.float32), + "state_ins": [ + np.random.uniform(0, 1.0, size=(B, LSTM_CELL)).astype(np.float32), + np.random.uniform(0, 1.0, size=(B, LSTM_CELL)).astype(np.float32), + ], + "seq_lens": np.array([T] * B, np.float32), + } + # Input data for the ONNX session. + test_data_onnx = { + "obs": test_data_python["obs"], + "state_in_0": test_data_python["state_ins"][0], + "state_in_1": test_data_python["state_ins"][1], + "seq_lens": test_data_python["seq_lens"], + } + + # Input data for compiling the ONNX model. + test_data_onnx_input = convert_to_torch_tensor(test_data_onnx) + + # Initialize a PPO Algorithm. + algo = config.build() + + # You could train the model here + # algo.train() + + # Let's run inference on the torch model + policy = algo.get_policy() + result_pytorch, _ = policy.model( + { + "obs": torch.tensor(test_data_python["obs"]), + }, + [ + torch.tensor(test_data_python["state_ins"][0]), + torch.tensor(test_data_python["state_ins"][1]), + ], + torch.tensor(test_data_python["seq_lens"]), + ) + + # Evaluate tensor to fetch numpy array + result_pytorch = result_pytorch.detach().numpy() + + # Wrap the actual ModelV2 with the torch wrapper above to make this all work with + # LSTMs (extra `state` in- and outputs and `seq_lens` inputs). + onnx_compatible = ONNXCompatibleWrapper(policy.model) + exported_model_file = "model.onnx" + input_names = [ + "obs", + "state_in_0", + "state_in_1", + "seq_lens", + ] + + # This line will export the model to ONNX. + torch.onnx.export( + onnx_compatible, + tuple(test_data_onnx_input[n] for n in input_names), + exported_model_file, + export_params=True, + opset_version=11, + do_constant_folding=True, + input_names=input_names, + output_names=[ + "output", + "state_out_0", + "state_out_1", + ], + dynamic_axes={k: {0: "batch_size"} for k in input_names}, + ) + # Start an inference session for the ONNX model. + session = onnxruntime.InferenceSession(exported_model_file, None) + result_onnx = session.run(["output"], test_data_onnx) + + # These results should be equal! + print("PYTORCH", result_pytorch) + print("ONNX", result_onnx[0]) + + check(result_pytorch, result_onnx[0]) + print("Model outputs are equal. PASSED") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/restore_1_of_n_agents_from_checkpoint.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/restore_1_of_n_agents_from_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..938489060653a990fe6101ade48a65c9c83ba78c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/checkpoints/restore_1_of_n_agents_from_checkpoint.py @@ -0,0 +1,170 @@ +"""Example demonstrating how to load module weights for 1 of n agents from a checkpoint. + +This example: + - Runs a multi-agent `Pendulum-v1` experiment with >= 2 policies, p0, p1, etc.. + - Saves a checkpoint of the `MultiRLModule` every `--checkpoint-freq` + iterations. + - Stops the experiments after the agents reach a combined return of -800. + - Picks the best checkpoint by combined return and restores p0 from it. + - Runs a second experiment with the restored `RLModule` for p0 and + a fresh `RLModule` for the other policies. + - Stops the second experiment after the agents reach a combined return of -800. + + +How to run this script +---------------------- +`python [script file name].py --num-agents=2 +--checkpoint-freq=20 --checkpoint-at-end` + +Control the number of agents and policies (RLModules) via --num-agents and +--num-policies. + +Control the number of checkpoints by setting `--checkpoint-freq` to a value > 0. +Note that the checkpoint frequency is per iteration and this example needs at +least a single checkpoint to load the RLModule weights for policy 0. +If `--checkpoint-at-end` is set, a checkpoint will be saved at the end of the +experiment. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect a reward of -400.0 eventually being achieved by a simple +single PPO policy. In the second run of the experiment, the MultiRLModule weights +for policy 0 are restored from the checkpoint of the first run. The reward for a +single agent should be -400.0 again, but the training time should be shorter +(around 30 iterations instead of 190) due to the fact that one policy is already +an expert from the get go. +""" + +from pathlib import Path + +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.core import ( + COMPONENT_LEARNER, + COMPONENT_LEARNER_GROUP, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentPendulum +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + check, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +parser = add_rllib_example_script_args( + # Pendulum-v1 sum of 2 agents (each agent reaches -250). + default_reward=-500.0, +) +parser.set_defaults( + checkpoint_freq=1, + num_agents=2, +) +# TODO (sven): This arg is currently ignored (hard-set to 2). +parser.add_argument("--num-policies", type=int, default=2) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + if args.num_agents > 1: + register_env( + "env", + lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}), + ) + else: + raise ValueError( + f"`num_agents` must be > 1, but is {args.num_agents}." + "Read the script docstring for more information." + ) + + assert args.checkpoint_freq > 0, ( + "This example requires at least one checkpoint to load the RLModule " + "weights for policy 0." + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env") + .training( + train_batch_size_per_learner=512, + minibatch_size=64, + lambda_=0.1, + gamma=0.95, + lr=0.0003, + vf_clip_param=10.0, + ) + .rl_module( + model_config=DefaultModelConfig(fcnet_activation="relu"), + ) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # Augment the base config with further settings and train the agents. + results = run_rllib_example_script_experiment(base_config, args, keep_ray_up=True) + + # Now swap in the RLModule weights for policy 0. + chkpt_path = results.get_best_result().checkpoint.path + p_0_module_state_path = ( + Path(chkpt_path) # <- algorithm's checkpoint dir + / COMPONENT_LEARNER_GROUP # <- learner group + / COMPONENT_LEARNER # <- learner + / COMPONENT_RL_MODULE # <- MultiRLModule + / "p0" # <- (single) RLModule + ) + + class LoadP0OnAlgoInitCallback(DefaultCallbacks): + def on_algorithm_init(self, *, algorithm, **kwargs): + module_p0 = algorithm.get_module("p0") + weight_before = convert_to_numpy(next(iter(module_p0.parameters()))) + algorithm.restore_from_path( + p_0_module_state_path, + component=( + COMPONENT_LEARNER_GROUP + + "/" + + COMPONENT_LEARNER + + "/" + + COMPONENT_RL_MODULE + + "/p0" + ), + ) + # Make sure weights were updated. + weight_after = convert_to_numpy(next(iter(module_p0.parameters()))) + check(weight_before, weight_after, false=True) + + base_config.callbacks(LoadP0OnAlgoInitCallback) + + # Define stopping criteria. + stop = { + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": -800.0, + f"{ENV_RUNNER_RESULTS}/{NUM_ENV_STEPS_SAMPLED_LIFETIME}": 100000, + TRAINING_ITERATION: 100, + } + + # Run the experiment again with the restored MultiRLModule. + run_rllib_example_script_experiment(base_config, args, stop=stop) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b2ae6905fafd844545e8abca2d9e28655fc130b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/count_based_curiosity.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/count_based_curiosity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbb27d39bdc33b8c8cc7c00eac2d11b905960d42 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/count_based_curiosity.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41864eec55e24bd7d3240053e327922c81ba180d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/flatten_observations_dict_space.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/flatten_observations_dict_space.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e94116172001e1f07c0c6f77bdbdaccd9ffb2c3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/flatten_observations_dict_space.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/frame_stacking.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/frame_stacking.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce404aca8e35fbf9c5b263bb36533efc8ecc336f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/frame_stacking.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/mean_std_filtering.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/mean_std_filtering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56010a90bc42c0463b95dee7ea0e20024489afea Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/mean_std_filtering.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/multi_agent_observation_preprocessor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/multi_agent_observation_preprocessor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b35c7ebe2d2d8b1fa2ed270a8278ac40fc2b3649 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/multi_agent_observation_preprocessor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/prev_actions_prev_rewards.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/prev_actions_prev_rewards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26fa2460a9584a15bdd19203e4abbde99d27d430 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/prev_actions_prev_rewards.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/single_agent_observation_preprocessor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/single_agent_observation_preprocessor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ce1721eef0d90dd3b36ff699f3c471dc4f661e4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/__pycache__/single_agent_observation_preprocessor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff23278bed28d232c66ee0c5e6721463069f1486 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/add_other_agents_row_index_to_xy_pos.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/add_other_agents_row_index_to_xy_pos.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..022086f353a6e6c9776cbaa4f508c7df6a463adb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/add_other_agents_row_index_to_xy_pos.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/count_based_curiosity.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/count_based_curiosity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82193766ac8604f1c78017ff7617de7ba73dda8f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/count_based_curiosity.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c642b9bd17332ae4a91f221579c1dd2f5b2c73b0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/protobuf_cartpole_observation_decoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/protobuf_cartpole_observation_decoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fce1d426ce086afc4ab9c8a60869b6902831041 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/__pycache__/protobuf_cartpole_observation_decoder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/add_other_agents_row_index_to_xy_pos.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/add_other_agents_row_index_to_xy_pos.py new file mode 100644 index 0000000000000000000000000000000000000000..a1e3d49ce001b0c5373c92df7a452bb2099dec2a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/add_other_agents_row_index_to_xy_pos.py @@ -0,0 +1,114 @@ +from typing import Any + +import gymnasium as gym +import numpy as np + +from ray.rllib.connectors.env_to_module.observation_preprocessor import ( + MultiAgentObservationPreprocessor, +) +from ray.rllib.utils.annotations import override + + +class AddOtherAgentsRowIndexToXYPos(MultiAgentObservationPreprocessor): + """Adds other agent's row index to an x/y-observation for an agent. + + Run this connector with this env: + :py:class:`~ray.rllib.examples.env.classes.multi_agent.double_row_corridor_env.DoubleRowCorridorEnv` # noqa + + In this env, 2 agents walk around in a grid-world and must, each separately, reach + their individual goal position to receive a final reward. However, if they collide + while search for these goal positions, another larger reward is given to both + agents. Thus, optimal policies aim at seeking the other agent first, and only then + proceeding to their agent's goal position. + + Each agents' observation space is a 2-tuple encoding the x/y position + (x=row, y=column). + This connector converts these observations to: + A dict for `agent_0` of structure: + { + "agent": Discrete index encoding the position of the agent, + "other_agent_row": Discrete(2), indicating whether the other agent is in row 0 + or row 1, + } + And a 3-tuple for `agent_1`, encoding the x/y position of `agent_1` plus the row + index (0 or 1) of `agent_0`. + + Note that the row information for the respective other agent, which this connector + provides, is needed for learning an optimal policy for any of the agents, because + the env rewards the first collision between the two agents. Hence, an agent needs to + have information on which row the respective other agent is currently in, so it can + change to this row and try to collide with this other agent. + """ + + @override(MultiAgentObservationPreprocessor) + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ) -> gym.Space: + """Maps the original (input) observation space to the new one. + + Original observation space is `Dict({agent_n: Box(4,), ...})`. + Converts the space for `self.agent` into information specific to this agent, + plus the current row of the respective other agent. + Output observation space is then: + `Dict({`agent_n`: Dict(Discrete, Discrete), ...}), where the 1st Discrete + is the position index of the agent and the 2nd Discrete encodes the current row + of the other agent (0 or 1). If the other agent is already done with the episode + (has reached its goal state) a special value of 2 is used. + """ + agent_0_space = input_observation_space.spaces["agent_0"] + self._env_corridor_len = agent_0_space.high[1] + 1 # Box.high is inclusive. + # Env has always 2 rows (and `self._env_corridor_len` columns). + num_discrete = int(2 * self._env_corridor_len) + spaces = { + "agent_0": gym.spaces.Dict( + { + # Exact position of this agent (as an int index). + "agent": gym.spaces.Discrete(num_discrete), + # Row (0 or 1) of other agent. Or 2, if other agent is already done. + "other_agent_row": gym.spaces.Discrete(3), + } + ), + "agent_1": gym.spaces.Box( + 0, + agent_0_space.high[1], # 1=column + shape=(3,), + dtype=np.float32, + ), + } + return gym.spaces.Dict(spaces) + + @override(MultiAgentObservationPreprocessor) + def preprocess(self, observations, episode) -> Any: + # Observations: dict of keys "agent_0" and "agent_1", mapping to the respective + # x/y positions of these agents (x=row, y=col). + # For example: [1.0, 4.0] means the agent is in row 1 and column 4. + + new_obs = {} + # 2=agent is already done + row_agent_0 = observations.get("agent_0", [2])[0] + row_agent_1 = observations.get("agent_1", [2])[0] + + if "agent_0" in observations: + # Compute `agent_0` and `agent_1` enhanced observation. + index_obs_agent_0 = ( + observations["agent_0"][0] * self._env_corridor_len + + observations["agent_0"][1] + ) + new_obs["agent_0"] = { + "agent": index_obs_agent_0, + "other_agent_row": row_agent_1, + } + + if "agent_1" in observations: + new_obs["agent_1"] = np.array( + [ + observations["agent_1"][0], + observations["agent_1"][1], + row_agent_0, + ], + dtype=np.float32, + ) + + return new_obs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/count_based_curiosity.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/count_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..5985d3deee02eb0a990ec5256855d4951f471d35 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/count_based_curiosity.py @@ -0,0 +1,92 @@ +from collections import Counter +from typing import Any, List, Optional + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.typing import EpisodeType + + +class CountBasedCuriosity(ConnectorV2): + """Learner ConnectorV2 piece to compute intrinsic rewards based on obs counts. + + Add this connector piece to your Learner pipeline, through your algo config: + ``` + config.training( + learner_connector=lambda obs_sp, act_sp: CountBasedCuriosity() + ) + ``` + + Intrinsic rewards are computed on the Learner side based on naive observation + counts, which is why this connector should only be used for simple environments + with a reasonable number of possible observations. The intrinsic reward for a given + timestep is: + r(i) = intrinsic_reward_coeff * (1 / C(obs(i))) + where C is the total (lifetime) count of the obs at timestep i. + + The intrinsic reward is added to the extrinsic reward and saved back into the + episode (under the main "rewards" key). + + Note that the computation and saving back to the episode all happens before the + actual train batch is generated from the episode data. Thus, the Learner and the + RLModule used do not take notice of the extra reward added. + + If you would like to use a more sophisticated mechanism for intrinsic reward + computations, take a look at the `EuclidianDistanceBasedCuriosity` connector piece + at `ray.rllib.examples.connectors.classes.euclidian_distance_based_curiosity` + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + intrinsic_reward_coeff: float = 1.0, + **kwargs, + ): + """Initializes a CountBasedCuriosity instance. + + Args: + intrinsic_reward_coeff: The weight with which to multiply the intrinsic + reward before adding (and saving) it back to the main (extrinsic) + reward of the episode at each timestep. + """ + super().__init__(input_observation_space, input_action_space) + + # Naive observation counter. + self._counts = Counter() + self.intrinsic_reward_coeff = intrinsic_reward_coeff + + def __call__( + self, + *, + rl_module: RLModule, + batch: Any, + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Loop through all episodes and change the reward to + # [reward + intrinsic reward] + for sa_episode in self.single_agent_episode_iterator( + episodes=episodes, agents_that_stepped_only=False + ): + # Loop through all observations, except the last one. + observations = sa_episode.get_observations(slice(None, -1)) + # Get all respective extrinsic rewards. + rewards = sa_episode.get_rewards() + + for i, (obs, rew) in enumerate(zip(observations, rewards)): + # Add 1 to obs counter. + obs = tuple(obs) + self._counts[obs] += 1 + # Compute the count-based intrinsic reward and add it to the extrinsic + # reward. + rew += self.intrinsic_reward_coeff * (1 / self._counts[obs]) + # Store the new reward back to the episode (under the correct + # timestep/index). + sa_episode.set_rewards(new_data=rew, at_indices=i) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/euclidian_distance_based_curiosity.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/euclidian_distance_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..c50a2caae5d744e40a95f1c78608ca0f99050398 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/euclidian_distance_based_curiosity.py @@ -0,0 +1,122 @@ +from collections import deque +from typing import Any, List, Optional + +import gymnasium as gym +import numpy as np + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.typing import EpisodeType + + +class EuclidianDistanceBasedCuriosity(ConnectorV2): + """Learner ConnectorV2 piece computing intrinsic rewards with euclidian distance. + + Add this connector piece to your Learner pipeline, through your algo config: + ``` + config.training( + learner_connector=lambda obs_sp, act_sp: EuclidianDistanceBasedCuriosity() + ) + ``` + + Intrinsic rewards are computed on the Learner side based on comparing the euclidian + distance of observations vs already seen ones. A configurable number of observations + will be stored in a FIFO buffer and all incoming observations have their distance + measured against those. + + The minimum distance measured is the intrinsic reward for the incoming obs + (multiplied by a fixed coeffieicnt and added to the "main" extrinsic reward): + r(i) = intrinsic_reward_coeff * min(ED(o, o(i)) for o in stored_obs)) + where `ED` is the euclidian distance and `stored_obs` is the buffer. + + The intrinsic reward is then added to the extrinsic reward and saved back into the + episode (under the main "rewards" key). + + Note that the computation and saving back to the episode all happens before the + actual train batch is generated from the episode data. Thus, the Learner and the + RLModule used do not take notice of the extra reward added. + + Only one observation per incoming episode will be stored as a new one in the buffer. + Thereby, we pick the observation with the largest `min(ED)` value over all already + stored observations to be stored per episode. + + If you would like to use a simpler, count-based mechanism for intrinsic reward + computations, take a look at the `CountBasedCuriosity` connector piece + at `ray.rllib.examples.connectors.classes.count_based_curiosity` + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + intrinsic_reward_coeff: float = 1.0, + max_buffer_size: int = 100, + **kwargs, + ): + """Initializes a CountBasedCuriosity instance. + + Args: + intrinsic_reward_coeff: The weight with which to multiply the intrinsic + reward before adding (and saving) it back to the main (extrinsic) + reward of the episode at each timestep. + """ + super().__init__(input_observation_space, input_action_space) + + # Create an observation buffer + self.obs_buffer = deque(maxlen=max_buffer_size) + self.intrinsic_reward_coeff = intrinsic_reward_coeff + + self._test = 0 + + def __call__( + self, + *, + rl_module: RLModule, + batch: Any, + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + if self._test > 10: + return batch + self._test += 1 + # Loop through all episodes and change the reward to + # [reward + intrinsic reward] + for sa_episode in self.single_agent_episode_iterator( + episodes=episodes, agents_that_stepped_only=False + ): + # Loop through all obs, except the last one. + observations = sa_episode.get_observations(slice(None, -1)) + # Get all respective (extrinsic) rewards. + rewards = sa_episode.get_rewards() + + max_dist_obs = None + max_dist = float("-inf") + for i, (obs, rew) in enumerate(zip(observations, rewards)): + # Compare obs to all stored observations and compute euclidian distance. + min_dist = 0.0 + if self.obs_buffer: + min_dist = min( + np.sqrt(np.sum((obs - stored_obs) ** 2)) + for stored_obs in self.obs_buffer + ) + if min_dist > max_dist: + max_dist = min_dist + max_dist_obs = obs + + # Compute our euclidian distance-based intrinsic reward and add it to + # the main (extrinsic) reward. + rew += self.intrinsic_reward_coeff * min_dist + # Store the new reward back to the episode (under the correct + # timestep/index). + sa_episode.set_rewards(new_data=rew, at_indices=i) + + # Add the one observation of this episode with the largest (min) euclidian + # dist to all already stored obs to the buffer (maybe throwing out the + # oldest obs in there). + if max_dist_obs is not None: + self.obs_buffer.append(max_dist_obs) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/protobuf_cartpole_observation_decoder.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/protobuf_cartpole_observation_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..af7e81d481de2d4d63eb1569129834d01832b5e7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/classes/protobuf_cartpole_observation_decoder.py @@ -0,0 +1,82 @@ +from typing import Any, List, Optional + +import gymnasium as gym +import numpy as np + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.examples.envs.classes.utils.cartpole_observations_proto import ( + CartPoleObservation, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType + + +class ProtobufCartPoleObservationDecoder(ConnectorV2): + """Env-to-module ConnectorV2 piece decoding protobuf obs into CartPole-v1 obs. + + Add this connector piece to your env-to-module pipeline, through your algo config: + ``` + config.env_runners( + env_to_module_connector=( + lambda env, spaces, device: ProtobufCartPoleObservationDecoder() + ) + ) + ``` + + The incoming observation space must be a 1D Box of dtype uint8 + (which is the same as a binary string). The outgoing observation space is the + normal CartPole-v1 1D space: Box(-inf, inf, (4,), float32). + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + # Make sure the incoming observation space is a protobuf (binary string). + assert ( + isinstance(input_observation_space, gym.spaces.Box) + and len(input_observation_space.shape) == 1 + and input_observation_space.dtype.name == "uint8" + ) + # Return CartPole-v1's natural observation space. + return gym.spaces.Box(float("-inf"), float("inf"), (4,), np.float32) + + def __call__( + self, + *, + rl_module: RLModule, + batch: Any, + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Loop through all episodes and change the observation from a binary string + # to an actual 1D np.ndarray (normal CartPole-v1 obs). + for sa_episode in self.single_agent_episode_iterator(episodes=episodes): + # Get last obs (binary string). + obs = sa_episode.get_observations(-1) + obs_bytes = obs.tobytes() + obs_protobuf = CartPoleObservation() + obs_protobuf.ParseFromString(obs_bytes) + + # Set up the natural CartPole-v1 observation tensor from the protobuf + # values. + new_obs = np.array( + [ + obs_protobuf.x_pos, + obs_protobuf.x_veloc, + obs_protobuf.angle_pos, + obs_protobuf.angle_veloc, + ], + np.float32, + ) + + # Write the new observation (1D tensor) back into the Episode. + sa_episode.set_observations(new_data=new_obs, at_indices=-1) + + # Return `data` as-is. + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/count_based_curiosity.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/count_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..ad09e4ceb6bf2665d0766ebe218d071ca2ada19f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/count_based_curiosity.py @@ -0,0 +1,14 @@ +"""Placeholder for training with count-based curiosity. + +The actual script can be found at a different location (see code below). +""" + +if __name__ == "__main__": + import subprocess + import sys + + # Forward to "python ../curiosity/[same script name].py [same options]" + command = [sys.executable, "../curiosity/", sys.argv[0]] + sys.argv[1:] + + # Run the script. + subprocess.run(command, capture_output=True) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/euclidian_distance_based_curiosity.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/euclidian_distance_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..6e52de76791304545eebcf1aea76fe93cb2c6f39 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/euclidian_distance_based_curiosity.py @@ -0,0 +1,14 @@ +"""Placeholder for training with euclidian distance-based curiosity. + +The actual script can be found at a different location (see code below). +""" + +if __name__ == "__main__": + import subprocess + import sys + + # Forward to "python ../curiosity/[same script name].py [same options]" + command = [sys.executable, "../curiosity/", sys.argv[0]] + sys.argv[1:] + + # Run the script. + subprocess.run(command, capture_output=True) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/flatten_observations_dict_space.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/flatten_observations_dict_space.py new file mode 100644 index 0000000000000000000000000000000000000000..f194c6be65b111f057ae2767277251ab41142580 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/flatten_observations_dict_space.py @@ -0,0 +1,153 @@ +"""Example using a ConnectorV2 to flatten arbitrarily nested dict or tuple observations. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how the `FlattenObservation` ConnectorV2 piece can be added to the + env-to-module pipeline. + - demonstrates that by using this connector, any arbitrarily nested dict or tuple + observations is properly flattened into a simple 1D tensor, for easier RLModule + processing. + - shows how - in a multi-agent setup - individual agents can be specified, whose + observations should be flattened (while other agents' observations will always + be left as-is). + - uses a variant of the CartPole-v1 environment, in which the 4 observation items + (x-pos, x-veloc, angle, and angle-veloc) are taken apart and put into a nested dict + with the structure: + { + "x-pos": [x-pos], + "angular-pos": { + "value": [angle], + "some_random_stuff": [random Discrete(3)], # <- should be ignored by algo + }, + "velocs": Tuple([x-veloc], [angle-veloc]), + } + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- + ++---------------------+------------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+------------+----------------+--------+------------------+ +| PPO_env_a2fd6_00000 | TERMINATED | 127.0.0.1:7409 | 25 | 24.1426 | ++---------------------+------------+----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| num_env_steps_sample | num_env_steps_traine | episode_return_mean | +| d_lifetime | d_lifetime | | ++------------------------+------------------------+------------------------| +| 100000 | 100000 | 421.42 | ++------------------------+------------------------+------------------------+ +""" +from ray.tune.registry import register_env +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.cartpole_with_dict_observation_space import ( + CartPoleWithDictObservationSpace, +) +from ray.rllib.examples.envs.classes.multi_agent import ( + MultiAgentCartPoleWithDictObservationSpace, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + + +# Read in common example script command line arguments. +parser = add_rllib_example_script_args(default_timesteps=200000, default_reward=400.0) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Define env-to-module-connector pipeline for the new stack. + def _env_to_module_pipeline(env, spaces, device): + return FlattenObservations(multi_agent=args.num_agents > 0) + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda _: MultiAgentCartPoleWithDictObservationSpace( + config={"num_agents": args.num_agents} + ), + ) + else: + register_env("env", lambda _: CartPoleWithDictObservationSpace()) + + # Define the AlgorithmConfig used. + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env") + .env_runners(env_to_module_connector=_env_to_module_pipeline) + .training( + gamma=0.99, + lr=0.0003, + ) + .rl_module( + model_config=DefaultModelConfig( + fcnet_hiddens=[32], + fcnet_activation="linear", + vf_share_layers=True, + ), + ) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # PPO-specific settings (for better learning behavior only). + if args.algo == "PPO": + base_config.training( + num_epochs=6, + vf_loss_coeff=0.01, + ) + # IMPALA-specific settings (for better learning behavior only). + elif args.algo == "IMPALA": + base_config.training( + lr=0.0005, + vf_loss_coeff=0.05, + entropy_coeff=0.0, + ) + + # Run everything as configured. + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/frame_stacking.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/frame_stacking.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb83725b6087d94329489e2465d87cd3c7a2638 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/frame_stacking.py @@ -0,0 +1,227 @@ +"""Example using 2 ConnectorV2 for observation frame-stacking in Atari environments. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how the `FrameStackingEnvToModule` ConnectorV2 piece can be added to the + env-to-module pipeline. + - shows how the `FrameStackingLearner` ConnectorV2 piece can be added to the + learner connector pipeline. + - demonstrates that using these two pieces (rather than performing framestacking + already inside the environment using a gymnasium wrapper) increases overall + performance by about 5%. + + +How to run this script +---------------------- +`python [script file name].py --num-frames=4 --env=ALE/Pong-v5` + +Use the `--num-frames` option to define the number of observations to framestack. +If you don't want to use Connectors to perform the framestacking, set the +`--use-gym-wrapper-framestacking` flag to perform framestacking already inside a +gymnasium observation wrapper. In this case though, be aware that the tensors being +sent through the network are `--num-frames` x larger than if you use the Connector +setup. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- + +With `--num-frames=4` and using the two extra ConnectorV2 pieces (in the env-to-module +and learner connector pipelines), you should see something like this using: +`--env ALE/Pong-v5 --num-learners=4 --num-gpus-per-learner=1 --num-env-runners=95` ++---------------------------+------------+--------+------------------+... +| Trial name | status | iter | total time (s) | +| | | | | +|---------------------------+------------+--------+------------------+... +| PPO_atari-env_2fc4a_00000 | TERMINATED | 200 | 335.837 | ++---------------------------+------------+--------+------------------+... + +Note that the time to run these 200 iterations is about ~5% faster than when +performing framestacking already inside the environment (using a +`gymnasium.wrappers.ObservationWrapper`), due to the additional network traffic +needed (sending back 4x[obs] batches instead of 1x[obs] to the learners). + +Thus, with the `--use-gym-wrapper-framestacking` option (all other options being equal), +the output looks like this: ++---------------------------+------------+--------+------------------+... +| Trial name | status | iter | total time (s) | +| | | | | +|---------------------------+------------+--------+------------------+... +| PPO_atari-env_2fc4a_00000 | TERMINATED | 200 | 351.505 | ++---------------------------+------------+--------+------------------+... +""" +import gymnasium as gym + +from ray.rllib.connectors.env_to_module.frame_stacking import FrameStackingEnvToModule +from ray.rllib.connectors.learner.frame_stacking import FrameStackingLearner +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.env.wrappers.atari_wrappers import wrap_atari_for_new_api_stack +from ray.rllib.examples.envs.classes.multi_agent import make_multi_agent +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +# Read in common example script command line arguments. +parser = add_rllib_example_script_args( + default_timesteps=5000000, default_reward=20.0, default_iters=200 +) +# Use Pong by default. +parser.set_defaults( + env="ale_py:ALE/Pong-v5", +) +parser.add_argument( + "--num-frames", + type=int, + default=4, + help="The number of observation frames to stack.", +) +parser.add_argument( + "--use-gym-wrapper-framestacking", + action="store_true", + help="Whether to use RLlib's Atari wrapper's framestacking capabilities (as " + "opposed to doing it via a specific ConenctorV2 pipeline).", +) + + +if __name__ == "__main__": + from ray import tune + + args = parser.parse_args() + + # Define our custom connector pipelines. + def _make_env_to_module_connector(env, spaces, device): + # Create the env-to-module connector. We return an individual connector piece + # here, which RLlib automatically integrates into a pipeline (and + # add its default connector piece to the end of that pipeline). + # The default pipeline automatically fixes the input- and output spaces of the + # individual connector pieces in it. + # Note that since the frame stacking connector does NOT write information + # back to the episode (in order to save memory and network traffic), we + # also need to perform the same procedure on the Learner end (see below + # where we set up the Learner pipeline). + return FrameStackingEnvToModule( + num_frames=args.num_frames, + multi_agent=args.num_agents > 0, + ) + + def _make_learner_connector(input_observation_space, input_action_space): + # Create the learner connector. + return FrameStackingLearner( + num_frames=args.num_frames, + multi_agent=args.num_agents > 0, + ) + + # Create a custom Atari setup (w/o the usual RLlib-hard-coded framestacking in it). + # We would like our frame stacking connector to do this job. + def _env_creator(cfg): + return wrap_atari_for_new_api_stack( + gym.make(args.env, **cfg, **{"render_mode": "rgb_array"}), + # Perform framestacking either through ConnectorV2 or right here through + # the observation wrapper. + framestack=( + args.num_frames if args.use_gym_wrapper_framestacking else None + ), + ) + + if args.num_agents > 0: + tune.register_env( + "atari-env", + lambda cfg: make_multi_agent(_env_creator)( + dict(cfg, **{"num_agents": args.num_agents}) + ), + ) + else: + tune.register_env("atari-env", _env_creator) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + "atari-env", + env_config={ + # Make analogous to old v4 + NoFrameskip. + "frameskip": 1, + "full_action_space": False, + "repeat_action_probability": 0.0, + }, + clip_rewards=True, + ) + .env_runners( + # ... new EnvRunner and our frame stacking env-to-module connector. + env_to_module_connector=( + None + if args.use_gym_wrapper_framestacking + else _make_env_to_module_connector + ), + num_envs_per_env_runner=2, + ) + .training( + # Use our frame stacking learner connector. + learner_connector=( + None if args.use_gym_wrapper_framestacking else _make_learner_connector + ), + entropy_coeff=0.01, + # Linearly adjust learning rate based on number of GPUs. + lr=0.00015 * (args.num_learners or 1), + grad_clip=100.0, + grad_clip_by="global_norm", + ) + .rl_module( + model_config=DefaultModelConfig( + vf_share_layers=True, + conv_filters=[(16, 4, 2), (32, 4, 2), (64, 4, 2), (128, 4, 2)], + conv_activation="relu", + head_fcnet_hiddens=[256], + ), + ) + ) + + # PPO specific settings. + if args.algo == "PPO": + base_config.training( + num_epochs=10, + minibatch_size=64, + lambda_=0.95, + kl_coeff=0.5, + clip_param=0.1, + vf_clip_param=10.0, + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # Run everything as configured. + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/mean_std_filtering.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/mean_std_filtering.py new file mode 100644 index 0000000000000000000000000000000000000000..201ce369113897a7cff239d3f608b8137aa7bce0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/mean_std_filtering.py @@ -0,0 +1,193 @@ +"""Example using a ConnectorV2 for processing observations with a mean/std filter. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how the `MeanStdFilter` ConnectorV2 piece can be added to the env-to-module + pipeline. + - demonstrates that using such a filter enhances learning behavior (or even makes + if possible to learn overall) in some environments, especially those with lopsided + observation spaces, for example `Box(-3000, -1000, ...)`. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +Running this example with the mean-std filter results in the normally expected Pendulum +learning behavior: ++-------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-------------------------------+------------+-----------------+--------+ +| PPO_lopsided-pend_f9c96_00000 | TERMINATED | 127.0.0.1:43612 | 77 | ++-------------------------------+------------+-----------------+--------+ ++------------------+------------------------+-----------------------+ +| total time (s) | num_env_steps_sample | episode_return_mean | +| | d_lifetime | | +|------------------+------------------------+-----------------------| +| 30.7466 | 40040 | -276.3 | ++------------------+------------------------+-----------------------+ + +If you try using the `--disable-mean-std-filter` (all other things being equal), you +will either see no learning progress at all (or a very slow one), but more likely some +numerical instability related error will be thrown: + +ValueError: Expected parameter loc (Tensor of shape (64, 1)) of distribution + Normal(loc: torch.Size([64, 1]), scale: torch.Size([64, 1])) to satisfy the + constraint Real(), but found invalid values: +tensor([[nan], + [nan], + [nan], + ... +""" +import gymnasium as gym +import numpy as np + +from ray.rllib.connectors.env_to_module.mean_std_filter import MeanStdFilter +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentPendulum +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +torch, _ = try_import_torch() + +parser = add_rllib_example_script_args( + default_iters=500, + default_timesteps=500000, + default_reward=-300.0, +) +parser.add_argument( + "--disable-mean-std-filter", + action="store_true", + help="Run w/o a mean/std env-to-module connector piece (filter).", +) + + +class LopsidedObs(gym.ObservationWrapper): + def __init__(self, env): + super().__init__(env) + self.observation_space = gym.spaces.Box(-4000.0, -1456.0, (3,), np.float32) + + def observation(self, observation): + # Lopside [-1.0, 1.0] Pendulum observations + return ((observation + 1.0) / 2.0) * (4000.0 - 1456.0) - 4000.0 + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "lopsided-pend", + lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}), + ) + else: + register_env("lopsided-pend", lambda _: LopsidedObs(gym.make("Pendulum-v1"))) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("lopsided-pend") + .env_runners( + num_envs_per_env_runner=1 if args.num_agents > 0 else 20, + # Define a single connector piece to be prepended to the env-to-module + # connector pipeline. + # Alternatively, return a list of n ConnectorV2 pieces (which will then be + # included in an automatically generated EnvToModulePipeline or return a + # EnvToModulePipeline directly. + env_to_module_connector=( + None + if args.disable_mean_std_filter + else lambda env, spaces, device: ( + MeanStdFilter(multi_agent=args.num_agents > 0) + ) + ), + ) + .training( + train_batch_size_per_learner=512, + gamma=0.95, + # Linearly adjust learning rate based on number of GPUs. + lr=0.0003 * (args.num_learners or 1), + vf_loss_coeff=0.01, + ) + .rl_module( + model_config=DefaultModelConfig( + fcnet_activation="relu", + fcnet_kernel_initializer=torch.nn.init.xavier_uniform_, + fcnet_bias_initializer=torch.nn.init.constant_, + fcnet_bias_initializer_kwargs={"val": 0.0}, + ), + ) + # In case you would like to run with a evaluation EnvRunners, make sure your + # `evaluation_config` key contains the `use_worker_filter_stats=False` setting + # (see below). This setting makes sure that the mean/std stats collected by the + # evaluation EnvRunners are NOT used for the training EnvRunners (unless you + # really want to mix these stats). It's normally a good idea to keep the stats + # collected during evaluation completely out of the training data (already for + # better reproducibility alone). + # .evaluation( + # evaluation_num_env_runners=1, + # evaluation_interval=1, + # evaluation_config={ + # "explore": False, + # # Do NOT use the eval EnvRunners' ConnectorV2 states. Instead, before + # # each round of evaluation, broadcast the latest training + # # EnvRunnerGroup's ConnectorV2 states (merged from all training remote + # # EnvRunners) to the eval EnvRunnerGroup (and discard the eval + # # EnvRunners' stats). + # "use_worker_filter_stats": False, + # }, + # ) + ) + + # PPO specific settings. + if args.algo == "PPO": + base_config.training( + minibatch_size=64, + lambda_=0.1, + vf_clip_param=10.0, + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/multi_agent_observation_preprocessor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/multi_agent_observation_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..9d057dd258c569d88de1c80178e356ae2a9be512 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/multi_agent_observation_preprocessor.py @@ -0,0 +1,138 @@ +"""Example of a ConnectorV2 mapping global observations to n per-module observations. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how the custom `AddOtherAgentsRowIndexToXYPos` ConnectorV2 piece can be + added to the env-to-module pipeline. It serves as a multi-agent observation + preprocessor and makes sure than both agents' observations contain necessary + information about the respective other agent. Without this extra information, the + agents won't be able to learn to solve the problem optimally. + - demonstrates that using various such observation mapping connector pieces allows + users to map from global, multi-agent observations to individual modules' + observations. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see the algo reach an episode return of slightly above 20.0, which proves +that both agents learn how to utilize the other agents' row-index (0 or 1) in order +to collide with the other agent and receive an extra +5 reward. Without this collision +during the episode (if one agent reaches its goal, it's removed from the scene and no +collision can occur any longer), the maximum return per agent is under 10.0. + ++--------------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|--------------------------------------+------------+-----------------+--------+ +| PPO_DoubleRowCorridorEnv_ba678_00000 | TERMINATED | 127.0.0.1:73310 | 37 | ++--------------------------------------+------------+-----------------+--------+ ++------------------+-------+-------------------+-------------+-------------+ +| total time (s) | ts | combined return | return p1 | return p0 | +|------------------+-------+-------------------+-------------+-------------| +| 41.5389 | 19998 | 23.072 | 11.418 | 11.654 | ++------------------+-------+-------------------+-------------+-------------+ +""" +from ray.rllib.examples.envs.classes.multi_agent.double_row_corridor_env import ( + DoubleRowCorridorEnv, +) +from ray.rllib.examples.connectors.classes.add_other_agents_row_index_to_xy_pos import ( + AddOtherAgentsRowIndexToXYPos, +) +from ray.rllib.connectors.env_to_module.flatten_observations import ( + FlattenObservations, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +torch, _ = try_import_torch() + +parser = add_rllib_example_script_args( + default_iters=200, + default_timesteps=200000, + default_reward=22.0, +) +parser.set_defaults( + num_agents=2, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment(DoubleRowCorridorEnv) + .env_runners( + num_envs_per_env_runner=20, + # Define a list of two connector piece to be prepended to the env-to-module + # connector pipeline: + # 1) The custom connector piece: A MultiAgentObservationPreprocessor, which + # enhances each agents' individual observations through adding the + # respective other agent's row index to the observation. + # 2) A FlattenObservations connector to flatten the integer observations + # for `agent_0`, which the AddOtherAgentsRowIndexToXYPos outputs. + env_to_module_connector=lambda env, spaces, device: [ + AddOtherAgentsRowIndexToXYPos(), + # Only flatten agent_0's observations (b/c these are ints that need to + # be one-hot'd). + FlattenObservations(multi_agent=True, agent_ids=["agent_0"]), + ], + ) + .training( + train_batch_size_per_learner=512, + gamma=0.95, + # Linearly adjust learning rate based on number of GPUs. + lr=0.0003 * (args.num_learners or 1), + vf_loss_coeff=0.01, + ) + .multi_agent( + policies={"p0", "p1"}, + policy_mapping_fn=lambda aid, eps, **kw: "p0" if aid == "agent_0" else "p1", + ) + ) + + # PPO specific settings. + if args.algo == "PPO": + base_config.training( + minibatch_size=64, + lambda_=0.1, + vf_clip_param=10.0, + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/prev_actions_prev_rewards.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/prev_actions_prev_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..16b978bf44ae131d57166f806ed42427796c8edd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/prev_actions_prev_rewards.py @@ -0,0 +1,163 @@ +"""Example using a ConnectorV2 to add previous rewards/actions to an RLModule's input. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how the `PrevActionsPrevRewards` ConnectorV2 piece can be added to the + env-to-module pipeline to extract previous rewards and/or actions from the ongoing + episodes. + - shows how this connector creates and wraps this new information (rewards and + actions) together with the original observations into the RLModule's input dict + under a new `gym.spaces.Dict` structure (for example, if your observation space + is `O=Box(shape=(3,))` and you add the most recent 1 reward, the new observation + space will be `Dict({"_original_obs": O, "prev_n_rewards": Box(shape=())})`. + - demonstrates how to use RLlib's `FlattenObservations` right after the + `PrevActionsPrevRewards` to flatten that new dict observation structure again into + a single 1D tensor. + - uses the StatelessCartPole environment, a CartPole-v1 derivative that's missing + both x-veloc and angle-veloc observation components and is therefore non-Markovian + (only partially observable). An LSTM default model is used for training. Adding + the additional context to the observations (for example, prev. actions) helps the + LSTM to more quickly learn in this environment. + + +How to run this script +---------------------- +`python [script file name].py --num-frames=4 --env=ALE/Pong-v5` + +Use the `--num-frames` option to define the number of observations to framestack. +If you don't want to use Connectors to perform the framestacking, set the +`--use-gym-wrapper-framestacking` flag to perform framestacking already inside a +gymnasium observation wrapper. In this case though, be aware that the tensors being +sent through the network are `--num-frames` x larger than if you use the Connector +setup. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- + +You should see something similar to this in your terminal output when running +ths script as described above: + ++---------------------+------------+-----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+------------+-----------------+--------+------------------+ +| PPO_env_0edd2_00000 | TERMINATED | 127.0.0.1:12632 | 17 | 42.6898 | ++---------------------+------------+-----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| num_env_steps_sample | num_env_steps_traine | episode_return_mean | +| d_lifetime | d_lifetime | | +|------------------------+------------------------+------------------------| +| 68000 | 68000 | 205.22 | ++------------------------+------------------------+------------------------+ +""" +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.connectors.env_to_module import ( + FlattenObservations, + PrevActionsPrevRewards, +) +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.stateless_cartpole import StatelessCartPole +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentStatelessCartPole +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune import register_env + +torch, nn = try_import_torch() + + +parser = add_rllib_example_script_args( + default_reward=200.0, default_timesteps=1000000, default_iters=2000 +) +parser.add_argument("--n-prev-rewards", type=int, default=1) +parser.add_argument("--n-prev-actions", type=int, default=1) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Define our custom connector pipelines. + def _env_to_module(env, spaces, device): + # Create the env-to-module connector pipeline. + return [ + PrevActionsPrevRewards( + multi_agent=args.num_agents > 0, + n_prev_rewards=args.n_prev_rewards, + n_prev_actions=args.n_prev_actions, + ), + FlattenObservations(multi_agent=args.num_agents > 0), + ] + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda _: MultiAgentStatelessCartPole( + config={"num_agents": args.num_agents} + ), + ) + else: + register_env("env", lambda _: StatelessCartPole()) + + config = ( + PPOConfig() + .environment("env") + .env_runners(env_to_module_connector=_env_to_module) + .training( + num_epochs=6, + lr=0.0003, + train_batch_size=4000, + vf_loss_coeff=0.01, + ) + .rl_module( + model_config=DefaultModelConfig( + use_lstm=True, + max_seq_len=20, + fcnet_hiddens=[32], + fcnet_activation="linear", + fcnet_kernel_initializer=nn.init.xavier_uniform_, + fcnet_bias_initializer=nn.init.constant_, + fcnet_bias_initializer_kwargs={"val": 0.0}, + vf_share_layers=True, + ), + ) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + config = config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + run_rllib_example_script_experiment(config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/single_agent_observation_preprocessor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/single_agent_observation_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..9a20419da12a1eaa5168473d5efc452e9dbc6592 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/connectors/single_agent_observation_preprocessor.py @@ -0,0 +1,155 @@ +"""Example using a `SingleAgentObservationPreprocessor` to preprocess observations. + +The custom preprocessor here is part of the env-to-module connector pipeline and +alters the CartPole-v1 environment observations from the Markovian 4-tuple (x-pos, +angular-pos, x-velocity, angular-velocity) to a non-Markovian, simpler 2-tuple (only +x-pos and angular-pos). The resulting problem can only be solved through a +memory/stateful model, for example an LSTM. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how to write a custom `SingleAgentObservationPreprocessor` ConnectorV2 + piece. + - shows how to add this custom class to the env-to-module pipeline through the + algorithm config. + - demonstrates that by using this connector, the normal CartPole observation + changes from a Markovian (fully observable) to a non-Markovian (partially + observable) observation. Only stateful, memory enhanced models can solve the + resulting RL problem. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- + +You should see something like this at the end in your console output. +Note that your setup wouldn't be able to solve the environment, preprocessed through +your custom `SingleAgentObservationPreprocessor`, without the help of the configured +LSTM since you convert the env from a Markovian one to a partially observable, +non-Markovian one. ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_0ecb5_00000 | TERMINATED | 127.0.0.1:57921 | 9 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_env_steps_sample | +| | | d_lifetime | +|------------------+------------------------+------------------------| +| 26.2305 | 224.38 | 36000 | ++------------------+------------------------+------------------------+ +""" +import gymnasium as gym +import numpy as np +from ray.rllib.env.single_agent_episode import SingleAgentEpisode + +from ray.rllib.connectors.env_to_module.observation_preprocessor import ( + SingleAgentObservationPreprocessor, +) +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + + +# Read in common example script command line arguments. +parser = add_rllib_example_script_args(default_timesteps=200000, default_reward=200.0) + + +class ReduceCartPoleObservationsToNonMarkovian(SingleAgentObservationPreprocessor): + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + # The new observation space only has a shape of (2,), not (4,). + return gym.spaces.Box( + -5.0, + 5.0, + (input_observation_space.shape[0] - 2,), + np.float32, + ) + + def preprocess(self, observation, episode: SingleAgentEpisode): + # Extract only the positions (x-position and angular-position). + return np.array([observation[0], observation[2]], np.float32) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Define the AlgorithmConfig used. + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + # You use the normal CartPole-v1 env here and your env-to-module preprocessor + # converts this into a non-Markovian version of CartPole. + .environment("CartPole-v1") + .env_runners( + env_to_module_connector=( + lambda env, spaces, device: ReduceCartPoleObservationsToNonMarkovian() + ), + ) + .training( + gamma=0.99, + lr=0.0003, + ) + .rl_module( + model_config=DefaultModelConfig( + # Solve the non-Markovian env through using an LSTM-enhanced model. + use_lstm=True, + vf_share_layers=True, + ), + ) + ) + + # PPO-specific settings (for better learning behavior only). + if args.algo == "PPO": + base_config.training( + num_epochs=6, + vf_loss_coeff=0.01, + ) + # IMPALA-specific settings (for better learning behavior only). + elif args.algo == "IMPALA": + base_config.training( + lr=0.0005, + vf_loss_coeff=0.05, + entropy_coeff=0.0, + ) + + # Run everything as configured. + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55e53a48ac6f57355e70d7b19d387bd37342d712 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/count_based_curiosity.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/count_based_curiosity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57b6f822626aef04bddf3880b55dc3aa4fd18459 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/count_based_curiosity.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79307f36e1199d5006e53acadf53451dcda7961e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/euclidian_distance_based_curiosity.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/intrinsic_curiosity_model_based_curiosity.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/intrinsic_curiosity_model_based_curiosity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66dce4903ce40927e6f2c1dd7232c69e4dd0ef9e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/__pycache__/intrinsic_curiosity_model_based_curiosity.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/count_based_curiosity.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/count_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..7f2900b42a7dd7227d65e3122cc5748b326ad1b5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/count_based_curiosity.py @@ -0,0 +1,136 @@ +"""Example of using a count-based curiosity mechanism to learn in sparse-rewards envs. + +This example: + - demonstrates how to define your own count-based curiosity ConnectorV2 piece + that computes intrinsic rewards based on simple observation counts and adds these + intrinsic rewards to the "main" (extrinsic) rewards. + - shows how this connector piece overrides the main (extrinsic) rewards in the + episode and thus demonstrates how to do reward shaping in general with RLlib. + - shows how to plug this connector piece into your algorithm's config. + - uses Tune and RLlib to learn the env described above and compares 2 + algorithms, one that does use curiosity vs one that does not. + +We use a FrozenLake (sparse reward) environment with a map size of 8x8 and a time step +limit of 14 to make it almost impossible for a non-curiosity based policy to learn. + + +How to run this script +---------------------- +`python [script file name].py` + +Use the `--no-curiosity` flag to disable curiosity learning and force your policy +to be trained on the task w/o the use of intrinsic rewards. With this option, the +algorithm should NOT succeed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only a PPO policy that uses curiosity can +actually learn. + +Policy using count-based curiosity: ++-------------------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|-------------------------------+------------+--------+------------------+ +| PPO_FrozenLake-v1_109de_00000 | TERMINATED | 48 | 44.46 | ++-------------------------------+------------+--------+------------------+ ++------------------------+-------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetime | num_env_steps_traine | +| | | d_lifetime | +|------------------------+-------------------------+------------------------| +| 0.99 | 12960 | 194000 | ++------------------------+-------------------------+------------------------+ + +Policy NOT using curiosity: +[DOES NOT LEARN AT ALL] +""" +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.connectors.classes.count_based_curiosity import ( + CountBasedCuriosity, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_reward=0.99, default_iters=200, default_timesteps=1000000 +) +parser.add_argument( + "--intrinsic-reward-coeff", + type=float, + default=1.0, + help="The weight with which to multiply intrinsic rewards before adding them to " + "the extrinsic ones (default is 1.0).", +) +parser.add_argument( + "--no-curiosity", + action="store_true", + help="Whether to NOT use count-based curiosity.", +) + +ENV_OPTIONS = { + "is_slippery": False, + # Use this hard-to-solve 8x8 map with lots of holes (H) to fall into and only very + # few valid paths from the starting state (S) to the goal state (G). + "desc": [ + "SFFHFFFH", + "FFFHFFFF", + "FFFHHFFF", + "FFFFFFFH", + "HFFHFFFF", + "HHFHFFHF", + "FFFHFHHF", + "FHFFFFFG", + ], + # Limit the number of steps the agent is allowed to make in the env to + # make it almost impossible to learn without (count-based) curiosity. + "max_episode_steps": 14, +} + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + "FrozenLake-v1", + env_config=ENV_OPTIONS, + ) + .env_runners( + num_envs_per_env_runner=5, + # Flatten discrete observations (into one-hot vectors). + env_to_module_connector=lambda env, spaces, device: FlattenObservations(), + ) + .training( + # The main code in this example: We add the `CountBasedCuriosity` connector + # piece to our Learner connector pipeline. + # This pipeline is fed with collected episodes (either directly from the + # EnvRunners in on-policy fashion or from a replay buffer) and converts + # these episodes into the final train batch. The added piece computes + # intrinsic rewards based on simple observation counts and add them to + # the "main" (extrinsic) rewards. + learner_connector=( + None if args.no_curiosity else lambda *ags, **kw: CountBasedCuriosity() + ), + num_epochs=10, + vf_loss_coeff=0.01, + ) + .rl_module(model_config=DefaultModelConfig(vf_share_layers=True)) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/euclidian_distance_based_curiosity.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/euclidian_distance_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..4e54c8ad7287e2e9f33d3deaae2413e41c12b488 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/euclidian_distance_based_curiosity.py @@ -0,0 +1,126 @@ +"""Example of a euclidian-distance curiosity mechanism to learn in sparse-rewards envs. + +This example: + - demonstrates how to define your own euclidian-distance-based curiosity ConnectorV2 + piece that computes intrinsic rewards based on the delta between incoming + observations and some set of already stored (prior) observations. Thereby, the + further away the incoming observation is from the already stored ones, the higher + its corresponding intrinsic reward. + - shows how this connector piece adds the intrinsic reward to the corresponding + "main" (extrinsic) reward and overrides the value in the "rewards" key in the + episode. It thus demonstrates how to do reward shaping in general with RLlib. + - shows how to plug this connector piece into your algorithm's config. + - uses Tune and RLlib to learn the env described above and compares 2 + algorithms, one that does use curiosity vs one that does not. + +We use the MountainCar-v0 environment, a sparse-reward env that is very hard to learn +for a regular PPO algorithm. + + +How to run this script +---------------------- +`python [script file name].py` + +Use the `--no-curiosity` flag to disable curiosity learning and force your policy +to be trained on the task w/o the use of intrinsic rewards. With this option, the +algorithm should NOT succeed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only a PPO policy that uses curiosity can +actually learn. + +Policy using count-based curiosity: ++-------------------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|-------------------------------+------------+--------+------------------+ +| PPO_FrozenLake-v1_109de_00000 | TERMINATED | 48 | 44.46 | ++-------------------------------+------------+--------+------------------+ ++------------------------+-------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetime | num_env_steps_traine | +| | | d_lifetime | +|------------------------+-------------------------+------------------------| +| 0.99 | 12960 | 194000 | ++------------------------+-------------------------+------------------------+ + +Policy NOT using curiosity: +[DOES NOT LEARN AT ALL] +""" +from ray.rllib.connectors.env_to_module import MeanStdFilter +from ray.rllib.examples.connectors.classes.euclidian_distance_based_curiosity import ( + EuclidianDistanceBasedCuriosity, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +# TODO (sven): SB3's PPO learns MountainCar-v0 until a reward of ~-110. +# We might have to play around some more with different initializations, etc.. +# to get to these results as well. +parser = add_rllib_example_script_args( + default_reward=-140.0, default_iters=2000, default_timesteps=1000000 +) +parser.set_defaults( + num_env_runners=4, +) +parser.add_argument( + "--intrinsic-reward-coeff", + type=float, + default=0.0001, + help="The weight with which to multiply intrinsic rewards before adding them to " + "the extrinsic ones (default is 0.0001).", +) +parser.add_argument( + "--no-curiosity", + action="store_true", + help="Whether to NOT use count-based curiosity.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("MountainCar-v0") + .env_runners( + env_to_module_connector=lambda env, spaces, device: MeanStdFilter(), + num_envs_per_env_runner=5, + ) + .training( + # The main code in this example: We add the + # `EuclidianDistanceBasedCuriosity` connector piece to our Learner connector + # pipeline. This pipeline is fed with collected episodes (either directly + # from the EnvRunners in on-policy fashion or from a replay buffer) and + # converts these episodes into the final train batch. The added piece + # computes intrinsic rewards based on simple observation counts and add them + # to the "main" (extrinsic) rewards. + learner_connector=( + None + if args.no_curiosity + else lambda *ags, **kw: EuclidianDistanceBasedCuriosity() + ), + # train_batch_size_per_learner=512, + grad_clip=20.0, + entropy_coeff=0.003, + gamma=0.99, + lr=0.0002, + lambda_=0.98, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/intrinsic_curiosity_model_based_curiosity.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/intrinsic_curiosity_model_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..342a1a56fb733e2770458fad84e5398ff21f7143 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curiosity/intrinsic_curiosity_model_based_curiosity.py @@ -0,0 +1,312 @@ +"""Example of implementing and training with an intrinsic curiosity model (ICM). + +This type of curiosity-based learning trains a simplified model of the environment +dynamics based on three networks: +1) Embedding observations into latent space ("feature" network). +2) Predicting the action, given two consecutive embedded observations +("inverse" network). +3) Predicting the next embedded obs, given an obs and action +("forward" network). + +The less the ICM is able to predict the actually observed next feature vector, +given obs and action (through the forwards network), the larger the +"intrinsic reward", which will be added to the extrinsic reward of the agent. + +Therefore, if a state transition was unexpected, the agent becomes +"curious" and will further explore this transition leading to better +exploration in sparse rewards environments. + +For more details, see here: +[1] Curiosity-driven Exploration by Self-supervised Prediction +Pathak, Agrawal, Efros, and Darrell - UC Berkeley - ICML 2017. +https://arxiv.org/pdf/1705.05363.pdf + +This example: + - demonstrates how to write a custom RLModule, representing the ICM from the paper + above. Note that this custom RLModule does not belong to any individual agent. + - demonstrates how to write a custom (PPO) TorchLearner that a) adds the ICM to its + MultiRLModule, b) trains the regular PPO Policy plus the ICM module, using the + PPO parent loss and the ICM's RLModule's own loss function. + +We use a FrozenLake (sparse reward) environment with a custom map size of 12x12 and a +hard time step limit of 22 to make it almost impossible for a non-curiosity based +learners to learn a good policy. + + +How to run this script +---------------------- +`python [script file name].py` + +Use the `--no-curiosity` flag to disable curiosity learning and force your policy +to be trained on the task w/o the use of intrinsic rewards. With this option, the +algorithm should NOT succeed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only a PPO policy that uses curiosity can +actually learn. + +Policy using ICM-based curiosity: ++-------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|-------------------------------+------------+-----------------+--------+ +| PPO_FrozenLake-v1_52ab2_00000 | TERMINATED | 127.0.0.1:73318 | 392 | ++-------------------------------+------------+-----------------+--------+ ++------------------+--------+----------+--------------------+ +| total time (s) | ts | reward | episode_len_mean | +|------------------+--------+----------+--------------------| +| 236.652 | 786000 | 1.0 | 22.0 | ++------------------+--------+----------+--------------------+ + +Policy NOT using curiosity: +[DOES NOT LEARN AT ALL] +""" +from collections import defaultdict + +import numpy as np + +from ray import tune +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.examples.learners.classes.intrinsic_curiosity_learners import ( + DQNTorchLearnerWithCuriosity, + PPOTorchLearnerWithCuriosity, +) +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.learners.classes.intrinsic_curiosity_learners import ( + ICM_MODULE_ID, +) +from ray.rllib.examples.rl_modules.classes.intrinsic_curiosity_model_rlm import ( + IntrinsicCuriosityModel, +) +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +parser = add_rllib_example_script_args( + default_iters=2000, + default_timesteps=10000000, + default_reward=0.9, +) + + +class MeasureMaxDistanceToStart(RLlibCallback): + """Callback measuring the dist of the agent to its start position in FrozenLake-v1. + + Makes the naive assumption that the start position ("S") is in the upper left + corner of the used map. + Uses the MetricsLogger to record the (euclidian) distance value. + """ + + def __init__(self): + super().__init__() + self.max_dists = defaultdict(float) + self.max_dists_lifetime = 0.0 + + def on_episode_step( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ): + num_rows = env.envs[0].unwrapped.nrow + num_cols = env.envs[0].unwrapped.ncol + obs = np.argmax(episode.get_observations(-1)) + row = obs // num_cols + col = obs % num_rows + curr_dist = (row**2 + col**2) ** 0.5 + if curr_dist > self.max_dists[episode.id_]: + self.max_dists[episode.id_] = curr_dist + + def on_episode_end( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ): + # Compute current maximum distance across all running episodes + # (including the just ended one). + max_dist = max(self.max_dists.values()) + metrics_logger.log_value( + key="max_dist_travelled_across_running_episodes", + value=max_dist, + window=10, + ) + if max_dist > self.max_dists_lifetime: + self.max_dists_lifetime = max_dist + del self.max_dists[episode.id_] + + def on_sample_end( + self, + *, + env_runner, + metrics_logger, + samples, + **kwargs, + ): + metrics_logger.log_value( + key="max_dist_travelled_lifetime", + value=self.max_dists_lifetime, + window=1, + ) + + +if __name__ == "__main__": + args = parser.parse_args() + + if args.algo not in ["DQN", "PPO"]: + raise ValueError( + "Curiosity example only implemented for either DQN or PPO! See the " + ) + + base_config = ( + tune.registry.get_trainable_cls(args.algo) + .get_default_config() + .environment( + "FrozenLake-v1", + env_config={ + # Use a 12x12 map. + "desc": [ + "SFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFG", + ], + "is_slippery": False, + # Limit the number of steps the agent is allowed to make in the env to + # make it almost impossible to learn without the curriculum. + "max_episode_steps": 22, + }, + ) + .callbacks(MeasureMaxDistanceToStart) + .env_runners( + num_envs_per_env_runner=5 if args.algo == "PPO" else 1, + env_to_module_connector=lambda env, spaces, device: FlattenObservations(), + ) + .training( + learner_config_dict={ + # Intrinsic reward coefficient. + "intrinsic_reward_coeff": 0.05, + # Forward loss weight (vs inverse dynamics loss). Total ICM loss is: + # L(total ICM) = ( + # `forward_loss_weight` * L(forward) + # + (1.0 - `forward_loss_weight`) * L(inverse_dyn) + # ) + "forward_loss_weight": 0.2, + } + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + # The "main" RLModule (policy) to be trained by our algo. + DEFAULT_MODULE_ID: RLModuleSpec( + **( + {"model_config": {"vf_share_layers": True}} + if args.algo == "PPO" + else {} + ), + ), + # The intrinsic curiosity model. + ICM_MODULE_ID: RLModuleSpec( + module_class=IntrinsicCuriosityModel, + # Only create the ICM on the Learner workers, NOT on the + # EnvRunners. + learner_only=True, + # Configure the architecture of the ICM here. + model_config={ + "feature_dim": 288, + "feature_net_hiddens": (256, 256), + "feature_net_activation": "relu", + "inverse_net_hiddens": (256, 256), + "inverse_net_activation": "relu", + "forward_net_hiddens": (256, 256), + "forward_net_activation": "relu", + }, + ), + } + ), + # Use a different learning rate for training the ICM. + algorithm_config_overrides_per_module={ + ICM_MODULE_ID: AlgorithmConfig.overrides(lr=0.0005) + }, + ) + ) + + # Set PPO-specific hyper-parameters. + if args.algo == "PPO": + base_config.training( + num_epochs=6, + # Plug in the correct Learner class. + learner_class=PPOTorchLearnerWithCuriosity, + train_batch_size_per_learner=2000, + lr=0.0003, + ) + elif args.algo == "DQN": + base_config.training( + # Plug in the correct Learner class. + learner_class=DQNTorchLearnerWithCuriosity, + train_batch_size_per_learner=128, + lr=0.00075, + replay_buffer_config={ + "type": "PrioritizedEpisodeReplayBuffer", + "capacity": 500000, + "alpha": 0.6, + "beta": 0.4, + }, + # Epsilon exploration schedule for DQN. + epsilon=[[0, 1.0], [500000, 0.05]], + n_step=(3, 5), + double_q=True, + dueling=True, + ) + + success_key = f"{ENV_RUNNER_RESULTS}/max_dist_travelled_across_running_episodes" + stop = { + success_key: 12.0, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + } + + run_rllib_example_script_experiment( + base_config, + args, + stop=stop, + success_metric={success_key: stop[success_key]}, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd2c2e29df357dff51f34a87ab55a19469d929a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/curriculum_learning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/curriculum_learning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e132bec7485cd06bf2b73d705b7111baf8dc629 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/curriculum_learning.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/pong_curriculum_learning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/pong_curriculum_learning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..854cd4bc99fcb34d50b0afd5183ae07ffcef4501 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/__pycache__/pong_curriculum_learning.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/curriculum_learning.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/curriculum_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a71de6789f003e29ba535da976793d0bcb126f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/curriculum_learning.py @@ -0,0 +1,249 @@ +"""Example of using an env-task curriculum by implementing a custom callback. + +This example: + - demonstrates how to define your own curriculum-capable environments using + gymnasium's FrozenLake env. + - defines a custom callback that gets called once per iteration and - if necessary - + changes the maps used by FrozenLake on all EnvRunners to a new task (by moving the + goal position further and further away from the starting position). + - also demonstrates an alternative approach via reloading/recreating an entirely new + env inside all EnvRunners. + - uses Tune and RLlib to curriculum-learn the env described above and compares 2 + algorithms, one that does use curriculum learning vs one that does not. + +We use a FrozenLake (sparse reward) environment with a map size of 8x8 and a time step +limit of 16 to make it almost impossible for a non-curriculum policy to learn. + + +How to run this script +---------------------- +`python [script file name].py` + +Use the `--no-curriculum` flag to disable curriculum learning and force your policy +to be trained on the hardest task right away. With this option, the algorithm should NOT +succeed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only PPO policy that uses a curriculum can +actually learn, whereas the one that is thrown into the toughest task right from the +start never learns anything. + +Policy using the curriculum: ++-------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|-------------------------------+------------+-----------------+--------+ +| PPO_FrozenLake-v1_93ca4_00000 | TERMINATED | 127.0.0.1:73318 | 41 | ++-------------------------------+------------+-----------------+--------+ ++------------------+--------+----------+--------------------+ +| total time (s) | ts | reward | episode_len_mean | +|------------------+--------+----------+--------------------| +| 97.652 | 164000 | 1 | 14.0348 | ++------------------+--------+----------+--------------------+ + +Policy NOT using the curriculum (trying to solve the hardest task right away): +[DOES NOT LEARN AT ALL] +""" +from functools import partial + +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args(default_iters=100, default_timesteps=600000) +parser.add_argument( + "--upgrade-task-threshold", + type=float, + default=0.99, + help="The mean episode return, upon reaching of which we increase the task by one.", +) +parser.add_argument( + "--no-curriculum", + action="store_true", + help="Whether to NOT use curriculum learning (and instead trying to solve the " + "hardest task right away).", +) + +# __curriculum_learning_example_env_options__ +ENV_OPTIONS = { + "is_slippery": False, + # Limit the number of steps the agent is allowed to make in the env to + # make it almost impossible to learn without the curriculum. + "max_episode_steps": 16, +} + +# Our 3 tasks: 0=easiest, 1=medium, 2=hard +ENV_MAPS = [ + # 0 + [ + "SFFHFFFH", + "FFFHFFFF", + "FFGFFFFF", + "FFFFFFFF", + "HFFFFFFF", + "HHFFFFHF", + "FFFFFHHF", + "FHFFFFFF", + ], + # 1 + [ + "SFFHFFFH", + "FFFHFFFF", + "FFFFFFFF", + "FFFFFFFF", + "HFFFFFFF", + "HHFFGFHF", + "FFFFFHHF", + "FHFFFFFF", + ], + # 2 + [ + "SFFHFFFH", + "FFFHFFFF", + "FFFFFFFF", + "FFFFFFFF", + "HFFFFFFF", + "HHFFFFHF", + "FFFFFHHF", + "FHFFFFFG", + ], +] +# __END_curriculum_learning_example_env_options__ + + +# Simple function sent to an EnvRunner to change the map of all its gym. Envs from +# the current one to a new (tougher) one, in which the goal position is further away +# from the starting position. Note that a map is a list of strings, each one +# representing one row in the map. Each character in the strings represent a single +# field (S=starting position, H=hole (bad), F=frozen/free field (ok), G=goal (great!)). +def _remote_fn(env_runner, new_task: int): + # We recreate the entire env object by changing the env_config on the worker, + # then calling its `make_env()` method. + env_runner.config.environment(env_config={"desc": ENV_MAPS[new_task]}) + env_runner.make_env() + + +class EnvTaskCallback(RLlibCallback): + """Custom callback implementing `on_train_result()` for changing the envs' maps.""" + + def on_algorithm_init( + self, + *, + algorithm: "Algorithm", + **kwargs, + ) -> None: + # Set the initial task to 0. + algorithm._counters["current_env_task"] = 0 + + def on_train_result( + self, + *, + algorithm: Algorithm, + metrics_logger=None, + result: dict, + **kwargs, + ) -> None: + # Hack: Store the current task inside a counter in our Algorithm. + # W/o a curriculum, the task is always 2 (hardest). + if args.no_curriculum: + algorithm._counters["current_env_task"] = 2 + current_task = algorithm._counters["current_env_task"] + + # If episode return is consistently `args.upgrade_task_threshold`, we switch + # to a more difficult task (if possible). If we already mastered the most + # difficult task, we publish our victory in the result dict. + result["task_solved"] = 0.0 + current_return = result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + if current_return > args.upgrade_task_threshold: + if current_task < 2: + new_task = current_task + 1 + print( + f"Switching task/map on all EnvRunners to #{new_task} (0=easiest, " + f"2=hardest), b/c R={current_return} on current task." + ) + algorithm.env_runner_group.foreach_env_runner( + func=partial(_remote_fn, new_task=new_task) + ) + algorithm._counters["current_env_task"] = new_task + + # Hardest task was solved (1.0) -> report this in the results dict. + elif current_return == 1.0: + result["task_solved"] = 1.0 + # Emergency brake: If return is 0.0 AND we are already at a harder task (1 or + # 2), we go back to task=0. + elif current_return == 0.0 and current_task > 0: + print( + "Emergency brake: Our policy seemed to have collapsed -> Setting task " + "back to 0." + ) + algorithm.env_runner_group.foreach_env_runner( + func=partial(_remote_fn, new_task=0) + ) + algorithm._counters["current_env_task"] = 0 + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + # Plug in our curriculum callbacks that controls when we should upgrade the env + # task based on the received return for the current task. + .callbacks(EnvTaskCallback) + .environment( + "FrozenLake-v1", + env_config={ + # w/ curriculum: start with task=0 (easiest) + # w/o curriculum: start directly with hardest task 2. + "desc": ENV_MAPS[2 if args.no_curriculum else 0], + **ENV_OPTIONS, + }, + ) + .env_runners( + num_envs_per_env_runner=5, + env_to_module_connector=lambda env, spaces, device: FlattenObservations(), + ) + .training( + num_epochs=6, + vf_loss_coeff=0.01, + lr=0.0002, + ) + .rl_module(model_config=DefaultModelConfig(vf_share_layers=True)) + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + # Reward directly does not matter to us as we would like to continue + # after the policy reaches a return of ~1.0 on the 0-task (easiest). + # But we DO want to stop, once the entire task is learned (policy achieves + # return of 1.0 on the most difficult task=2). + "task_solved": 1.0, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + } + + run_rllib_example_script_experiment( + base_config, args, stop=stop, success_metric={"task_solved": 1.0} + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/pong_curriculum_learning.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/pong_curriculum_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..07881d3275d5964cfbf84b335731a392e6412f18 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/curriculum/pong_curriculum_learning.py @@ -0,0 +1,281 @@ +"""Example of using curriculum learning for Atari Pong by implementing a custom callback. + +This example: + - demonstrates how to define a curriculum for an agent playing gymnasium's Atari + Pong. + - defines a custom callback that gets called once per iteration and - if the agent + performs well enough - increases the task difficulty, i.e. the `frameskip` for all + environments on all EnvRunners (the agent must act now faster). + - also demonstrates how to provide the callback with varying curriculum parameters + (like threshold maps, returns at which the curriculum ends, etc.). + - uses Ray Tune and RLlib to curriculum-learn Atari Pong with a high frameskip. + +We use Atari Pong with a framestack of 4 images (i.e. observation dimensions of 64x64x4) +and start with a frameskip of 1. At a return of 15.0 we increase the frameskip to 2, at +a return of 17.0 to 3, at 19.0 to 4, and the task is solved at a frameskip of 21.0. + +How to run this script +---------------------- +`python [script file name].py` + +Use the `--solved-return` flag to define the threshold at which curriculum learning ends. +Note that a PPO agent on Atari Pong will need a long time to learn. + +To ensure the agent has not collapsed, but rather made had a bad seed, we only decrease +the frameskip when the agent performed worse than the next lower threshold. The margin by +which the agent has to be worse is defined by the `--demotion-margin` argument and defaults +to 2.0. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +""" + +import functools +import gymnasium as gym +from typing import Callable + +from ray import tune +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.connectors.env_to_module.frame_stacking import FrameStackingEnvToModule +from ray.rllib.connectors.learner.frame_stacking import FrameStackingLearner +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.env.wrappers.atari_wrappers import wrap_atari_for_new_api_stack +from ray.rllib.utils.metrics import ENV_RUNNER_RESULTS, EPISODE_RETURN_MEAN +from ray.rllib.utils.test_utils import add_rllib_example_script_args + + +parser = add_rllib_example_script_args( + default_reward=float("inf"), + default_timesteps=3000000, + default_iters=100000000000, +) +parser.set_defaults( + env="ale_py:ALE/Pong-v5", +) +parser.add_argument( + "--solved-return", + type=float, + default=21.0, + help=("The mean episode return at which we consider the task to be fully solved."), +) +parser.add_argument( + "--demotion-margin", + type=float, + default=2.0, + help=( + "The margin below the next lower task threshold, beneath which the agent " + " is considered to have collapsed, prompting a downgrade of the task." + ), +) +# Use `parser` to add your own custom command line options to this script +# and (if needed) use their values to set up `config` below. +args = parser.parse_args() + +NUM_LEARNERS = args.num_learners or 1 +ENV = args.env + + +class PongEnvTaskCallback(RLlibCallback): + """Custom callback changing the frameskip in Atari Pong dependent on return.""" + + def __init__( + self, + task_threshold_map: dict, + remote_fn: Callable, + demotion_margin: float = 0.0, + solved_return: float = float("inf"), + ): + self.task_threshold_map = task_threshold_map + self.remote_fn = remote_fn + self.demotion_margin = demotion_margin + self.solved_return = solved_return + + def on_algorithm_init( + self, + *, + algorithm: "Algorithm", + **kwargs, + ) -> None: + # Set the initial task to 1, which corresponds to a frameskip of 1. + algorithm.metrics.log_value("current_env_task", 1, reduce="sum") + + def on_train_result( + self, + *, + algorithm: Algorithm, + metrics_logger=None, + result: dict, + **kwargs, + ) -> None: + # Store the current task inside the metrics logger in our Algorithm. + current_task = metrics_logger.peek("current_env_task") + + # If episode return is consistently above `task_threshold_map[current_task]`, + # we switch to a more difficult task (i.e. higher `frameskip`` if possible). + # If we already mastered the most difficult task, we publish our victory in + # the result dict. + result["task_solved"] = 0.0 + + # Note, in the first callback executions there may be no completed episode + # (and therefore no episode return) reported. In this case we will skip the + # the logic to manage task difficulty. + if EPISODE_RETURN_MEAN in result[ENV_RUNNER_RESULTS]: + current_return = result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + else: + return + + # Get the threshold of the current task from the threshold map. + threshold = self.task_threshold_map.get(current_task, float("inf")) + + # Check, if curriculum is solved. + final_task = max(self.task_threshold_map.keys()) + if current_task == final_task and current_return >= self.solved_return: + # Hardest task was solved -> report this in the results dict. + result["task_solved"] = 1.0 + + # Check promotion (increasing task). Note, we could use here also a promotion_patience + # that ensures that the return is collected in a stable manner instead of a lucky shot. + if ( + current_return >= threshold + ): # & result[ENV_RUNNER_RESULTS][NUM_EPISODES] > promotion_patience. + next_task = current_task + 1 + if next_task in self.task_threshold_map: + print( + f"Switching task on all EnvRunners up to #{next_task} (1=easiest, " + f"4=hardest), b/c R={current_return} on current task." + ) + # Increase task. + algorithm.env_runner_group.foreach_env_runner( + func=functools.partial(self.remote_fn, new_task=next_task) + ) + metrics_logger.log_value("current_env_task", next_task, window=1) + + # Check demotion (decreasing task). The demotion is used to avoid decreasing the task + # in case of an unlucky episode run. Only if the return is singificantly lower we + # decrease the task. + previous_task = current_task - 1 + if previous_task in self.task_threshold_map: + previous_threshold = self.task_threshold_map[previous_task] + if current_return < previous_threshold - self.demotion_margin: + print( + f"Switching task on all EnvRunners back to #{previous_task} (1=easiest, " + f"4=hardest), b/c R={current_return} on current task." + ) + # Decrease to previous level. + algorithm.env_runner_group.foreach_env_runner( + func=functools.partial(self.remote_fn, new_task=previous_task) + ) + metrics_logger.log_value("current_env_task", previous_task, window=1) + + +# These tags allow extracting portions of this script on Anyscale. +# ws-template-code-start +def _make_env_to_module_connector(env, spaces, device): + return FrameStackingEnvToModule(num_frames=4) + + +def _make_learner_connector(input_observation_space, input_action_space): + return FrameStackingLearner(num_frames=4) + + +# Create a custom Atari setup (w/o the usual RLlib-hard-coded framestacking in it). +# We would like our frame stacking connector to do this job. +def _env_creator(cfg): + return wrap_atari_for_new_api_stack( + gym.make(ENV, **cfg, render_mode="rgb_array"), + # Perform frame-stacking through ConnectorV2 API. + framestack=None, + ) + + +# Simple function sent to an EnvRunner to change the map of all its gym. Envs from +# the current one to a new (tougher) one, in which the frameskip is higher +# and the agent must therefore act faster. +def _remote_fn(env_runner, new_task: int): + # Override the env_config with the new setting. + env_runner.config.env_config.update( + { + "frameskip": new_task, + } + ) + # We recreate the entire env object by changing the env_config on the worker, + # then calling its `make_env()` method. + env_runner.make_env() + + +# Task threshold map keeps track of thresholds for each task. If the threshold has +# been surpassed the task difficulty is increased. +task_threshold_map = { + # Frameskip: Return. + 1: 15.0, + 2: 17.0, + 3: 19.0, + 4: float("inf"), +} + +tune.register_env("env", _env_creator) + +config = ( + PPOConfig() + .environment( + "env", + env_config={ + # Make analogous to old v4 + NoFrameskip. + "frameskip": 1, + "full_action_space": False, + "repeat_action_probability": 0.0, + }, + clip_rewards=True, + ) + .env_runners( + env_to_module_connector=_make_env_to_module_connector, + ) + .training( + learner_connector=_make_learner_connector, + train_batch_size_per_learner=4000, + minibatch_size=128, + lambda_=0.95, + kl_coeff=0.5, + clip_param=0.1, + vf_clip_param=10.0, + entropy_coeff=0.01, + num_epochs=10, + lr=0.00015 * NUM_LEARNERS, + grad_clip=100.0, + grad_clip_by="global_norm", + ) + .rl_module( + model_config=DefaultModelConfig( + conv_filters=[[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]], + conv_activation="relu", + head_fcnet_hiddens=[256], + vf_share_layers=True, + ), + ) + .callbacks( + functools.partial( + PongEnvTaskCallback, + task_threshold_map=task_threshold_map, + remote_fn=_remote_fn, + # Avoids downgrading the task to early when the agent had an unlucky run. + demotion_margin=args.demotion_margin, + # The return at which the task is learned. + solved_return=args.solved_return, + ) + ) +) + +if __name__ == "__main__": + from ray.rllib.utils.test_utils import run_rllib_example_script_experiment + + run_rllib_example_script_experiment(config, args=args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..767a769e766ceaadcb7ef54ee1bdac89c2d84b8f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/__pycache__/deterministic_sampling_and_training.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/__pycache__/deterministic_sampling_and_training.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c2f0d5318f61ec3ea0cf7f2c64f73c2e5a00451 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/__pycache__/deterministic_sampling_and_training.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/deterministic_sampling_and_training.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/deterministic_sampling_and_training.py new file mode 100644 index 0000000000000000000000000000000000000000..11319c4da1126e623d3d60041366067b7de394f1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/debugging/deterministic_sampling_and_training.py @@ -0,0 +1,154 @@ +"""Example of how to seed your experiment with the `config.debugging(seed=...)` option. + +This example shows: + - how to seed an experiment, both on the Learner and on the EnvRunner side. + - that different experiments run with the exact same seed always yield the exact + same results (use the `--as-test` option to enforce assertions on the results). + Results checked range from EnvRunner stats, such as episode return, to Learner + stats, such as losses and gradient averages. + +Note that some algorithms, such as APPO which rely on asynchronous sampling in +combination with Ray network communication always behave stochastically, no matter +whether you set a seed or not. Therefore, make sure your `--algo` option is set to +a non-asynchronous algorithm, like "PPO" or "DQN". + + +How to run this script +---------------------- +`python [script file name].py --seed 1234` + +Use the `--num-learners=2` option to run with multiple Learner workers and, if GPUs +are available, place these workers on multiple GPUs. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0 --num-learners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect to see 2 experiments running and finishing in your console. +After the second experiment, you should see the confirmation that both experiments +yielded the exact same metrics. + ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_fb6d2_00000 | TERMINATED | 127.0.0.1:86298 | 3 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_env_steps_sample | +| | | d_lifetime | +|------------------+------------------------+------------------------| +| 6.2416 | 67.52 | 12004 | ++------------------+------------------------+------------------------+ + +... + +Determinism works! ok +""" +import ray +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + LEARNER_RESULTS, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + check, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + + +parser = add_rllib_example_script_args(default_iters=3) +parser.set_defaults( + # Test by default with more than one Env per EnvRunner. + num_envs_per_env_runner=2, +) +parser.add_argument("--seed", type=int, default=42) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda _: MultiAgentCartPole(config={"num_agents": args.num_agents}), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env" if args.num_agents > 0 else "CartPole-v1") + # Make sure every environment gets a fixed seed. + .debugging(seed=args.seed) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + results1 = run_rllib_example_script_experiment( + base_config, + args, + keep_ray_up=True, + success_metric={ENV_RUNNER_RESULTS + "/" + EPISODE_RETURN_MEAN: 10.0}, + ) + results2 = run_rllib_example_script_experiment( + base_config, + args, + keep_ray_up=True, + success_metric={ENV_RUNNER_RESULTS + "/" + EPISODE_RETURN_MEAN: 10.0}, + ) + + if args.as_test: + results1 = results1.get_best_result().metrics + results2 = results2.get_best_result().metrics + + # Test EnvRunner behaviors. + check( + results1[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN], + results2[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN], + ) + # As well as training behavior (minibatch sequence during SGD + # iterations). + for key in [ + # Losses and coefficients. + "curr_kl_coeff", + "vf_loss", + "policy_loss", + "entropy", + "total_loss", + "module_train_batch_size_mean", + # Optimizer stuff. + "gradients_default_optimizer_global_norm", + ]: + if args.num_agents > 0: + for aid in range(args.num_agents): + check( + results1[LEARNER_RESULTS][f"p{aid}"][key], + results2[LEARNER_RESULTS][f"p{aid}"][key], + ) + else: + check( + results1[LEARNER_RESULTS][DEFAULT_MODULE_ID][key], + results2[LEARNER_RESULTS][DEFAULT_MODULE_ID][key], + ) + + print("Determinism works! ok") + + ray.shutdown() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a93c5e7afd39d475f608f57cc78a43308e7eb02d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/agents_act_in_sequence.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/agents_act_in_sequence.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ea3a00f754eeebc167347cb7b5f7c2875622d0e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/agents_act_in_sequence.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/agents_act_simultaneously.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/agents_act_simultaneously.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8802a37ec30e5da89e4dbd6635f503a740e34d6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/agents_act_simultaneously.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/async_gym_env_vectorization.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/async_gym_env_vectorization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..766c1aa3c94d270f2d303aa8039d41cc860d8348 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/async_gym_env_vectorization.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/custom_env_render_method.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/custom_env_render_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39bcae5992b71f39e181755566ebed941a35db3f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/custom_env_render_method.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/custom_gym_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/custom_gym_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..182860403677b1d9074f4aa25bc7e78b670fe5b5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/custom_gym_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_connecting_to_rllib_w_tcp_client.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_connecting_to_rllib_w_tcp_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fed2de6ddbba1a41cee432c476df5c5f66768165 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_connecting_to_rllib_w_tcp_client.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_rendering_and_recording.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_rendering_and_recording.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87a13b0d3e02dcdfa41f525aa1d6fe66f39d22ec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_rendering_and_recording.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_w_protobuf_observations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_w_protobuf_observations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e15c2790d9b1be89b74cce68201bbb7b1906db0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/env_w_protobuf_observations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/greyscale_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/greyscale_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93b7b7d1215545cef0a3875decd130a5301e9cbb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/greyscale_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/unity3d_env_local.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/unity3d_env_local.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0be86bb2ac2d693e53d44d07fd1ec9dd2f7dafa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/__pycache__/unity3d_env_local.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/agents_act_in_sequence.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/agents_act_in_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..5760f39f64c8104ae073b9b5dbe076b512ab1f76 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/agents_act_in_sequence.py @@ -0,0 +1,86 @@ +"""Example of running a multi-agent experiment w/ agents taking turns (sequence). + +This example: + - demonstrates how to write your own (multi-agent) environment using RLlib's + MultiAgentEnv API. + - shows how to implement the `reset()` and `step()` methods of the env such that + the agents act in a fixed sequence (taking turns). + - shows how to configure and setup this environment class within an RLlib + Algorithm config. + - runs the experiment with the configured algo, trying to solve the environment. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see results similar to the following in your console output: ++---------------------------+----------+--------+------------------+--------+ +| Trial name | status | iter | total time (s) | ts | +|---------------------------+----------+--------+------------------+--------+ +| PPO_TicTacToe_957aa_00000 | RUNNING | 25 | 96.7452 | 100000 | ++---------------------------+----------+--------+------------------+--------+ ++-------------------+------------------+------------------+ +| combined return | return player2 | return player1 | +|-------------------+------------------+------------------| +| -2 | 1.15 | -0.85 | ++-------------------+------------------+------------------+ + +Note that even though we are playing a zero-sum game, the overall return should start +at some negative values due to the misplacement penalty of our (simplified) TicTacToe +game. +""" +from ray.rllib.examples.envs.classes.multi_agent.tic_tac_toe import TicTacToe +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env # noqa + + +parser = add_rllib_example_script_args( + default_reward=-4.0, default_iters=50, default_timesteps=100000 +) +parser.set_defaults( + num_agents=2, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents == 2, "Must set --num-agents=2 when running this script!" + + # You can also register the env creator function explicitly with: + # register_env("tic_tac_toe", lambda cfg: TicTacToe()) + + # Or allow the RLlib user to set more c'tor options via their algo config: + # config.environment(env_config={[c'tor arg name]: [value]}) + # register_env("tic_tac_toe", lambda cfg: TicTacToe(cfg)) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment(TicTacToe) + .multi_agent( + # Define two policies. + policies={"player1", "player2"}, + # Map agent "player1" to policy "player1" and agent "player2" to policy + # "player2". + policy_mapping_fn=lambda agent_id, episode, **kw: agent_id, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/agents_act_simultaneously.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/agents_act_simultaneously.py new file mode 100644 index 0000000000000000000000000000000000000000..146182544880950489440ea499e37f832779a911 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/agents_act_simultaneously.py @@ -0,0 +1,109 @@ +"""Example of running a multi-agent experiment w/ agents always acting simultaneously. + +This example: + - demonstrates how to write your own (multi-agent) environment using RLlib's + MultiAgentEnv API. + - shows how to implement the `reset()` and `step()` methods of the env such that + the agents act simultaneously. + - shows how to configure and setup this environment class within an RLlib + Algorithm config. + - runs the experiment with the configured algo, trying to solve the environment. + + +How to run this script +---------------------- +`python [script file name].py --sheldon-cooper-mode` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see results similar to the following in your console output: + ++-----------------------------------+----------+--------+------------------+-------+ +| Trial name | status | iter | total time (s) | ts | +|-----------------------------------+----------+--------+------------------+-------+ +| PPO_RockPaperScissors_8cef7_00000 | RUNNING | 3 | 16.5348 | 12000 | ++-----------------------------------+----------+--------+------------------+-------+ ++-------------------+------------------+------------------+ +| combined return | return player2 | return player1 | +|-------------------+------------------+------------------| +| 0 | -0.15 | 0.15 | ++-------------------+------------------+------------------+ + +Note that b/c we are playing a zero-sum game, the overall return remains 0.0 at +all times. +""" +from ray.rllib.examples.envs.classes.multi_agent.rock_paper_scissors import ( + RockPaperScissors, +) +from ray.rllib.connectors.env_to_module.flatten_observations import FlattenObservations +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env # noqa + + +parser = add_rllib_example_script_args( + default_reward=0.9, default_iters=50, default_timesteps=100000 +) +parser.set_defaults( + num_agents=2, +) +parser.add_argument( + "--sheldon-cooper-mode", + action="store_true", + help="Whether to add two more actions to the game: Lizard and Spock. " + "Watch here for more details :) https://www.youtube.com/watch?v=x5Q6-wMx-K8", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents == 2, "Must set --num-agents=2 when running this script!" + + # You can also register the env creator function explicitly with: + # register_env("env", lambda cfg: RockPaperScissors({"sheldon_cooper_mode": False})) + + # Or you can hard code certain settings into the Env's constructor (`config`). + # register_env( + # "rock-paper-scissors-w-sheldon-mode-activated", + # lambda config: RockPaperScissors({**config, **{"sheldon_cooper_mode": True}}), + # ) + + # Or allow the RLlib user to set more c'tor options via their algo config: + # config.environment(env_config={[c'tor arg name]: [value]}) + # register_env("rock-paper-scissors", lambda cfg: RockPaperScissors(cfg)) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + RockPaperScissors, + env_config={"sheldon_cooper_mode": args.sheldon_cooper_mode}, + ) + .env_runners( + env_to_module_connector=( + lambda env, spaces, device: FlattenObservations(multi_agent=True) + ), + ) + .multi_agent( + # Define two policies. + policies={"player1", "player2"}, + # Map agent "player1" to policy "player1" and agent "player2" to policy + # "player2". + policy_mapping_fn=lambda agent_id, episode, **kw: agent_id, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/async_gym_env_vectorization.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/async_gym_env_vectorization.py new file mode 100644 index 0000000000000000000000000000000000000000..20ec218176b3ae1964c9c2eb23e34156e0e9cc2e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/async_gym_env_vectorization.py @@ -0,0 +1,141 @@ +"""Example demo'ing async gym vector envs, in which sub-envs have their own process. + +Setting up env vectorization works through setting the `config.num_envs_per_env_runner` +value to > 1. However, by default the n sub-environments are stepped through +sequentially, rather than in parallel. + +This script shows the effect of setting the `config.gym_env_vectorize_mode` from its +default value of "SYNC" (all sub envs are located in the same EnvRunner process) +to "ASYNC" (all sub envs in each EnvRunner get their own process). + +This example: + - shows, which config settings to change in order to switch from sub-envs being + stepped in sequence to each sub-envs owning its own process (and compute resource) + and thus the vector being stepped in parallel. + - shows, how this setup can increase EnvRunner performance significantly, especially + for heavier, slower environments. + - uses an artificially slow CartPole-v1 environment for demonstration purposes. + + +How to run this script +---------------------- +`python [script file name].py ` + +Use the `--vectorize-mode=BOTH` option to run both modes (SYNC and ASYNC) +through Tune at the same time and get a better comparison of the throughputs +achieved. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see results similar to the following in your console output +when using the + ++--------------------------+------------+------------------------+------+ +| Trial name | status | gym_env_vectorize_mode | iter | +| | | | | +|--------------------------+------------+------------------------+------+ +| PPO_slow-env_6ddf4_00000 | TERMINATED | SYNC | 4 | +| PPO_slow-env_6ddf4_00001 | TERMINATED | ASYNC | 4 | ++--------------------------+------------+------------------------+------+ ++------------------+----------------------+------------------------+ +| total time (s) | episode_return_mean | num_env_steps_sample | +| | | d_lifetime | +|------------------+----------------------+------------------------+ +| 60.8794 | 73.53 | 16040 | +| 19.1203 | 73.86 | 16037 | ++------------------+----------------------+------------------------+ + +You can see that the ASYNC mode, given that the env is sufficiently slow, +achieves much better results when using vectorization. + +You should see no difference, however, when only using +`--num-envs-per-env-runner=1`. +""" +import time + +import gymnasium as gym + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray import tune + +parser = add_rllib_example_script_args(default_reward=60.0) +parser.set_defaults( + env="CartPole-v1", + num_envs_per_env_runner=6, +) +parser.add_argument( + "--vectorize-mode", + type=str, + default="ASYNC", + help="The value `gym.envs.registration.VectorizeMode` to use for env " + "vectorization. SYNC steps through all sub-envs in sequence. ASYNC (default) " + "parallelizes sub-envs through multiprocessing and can speed up EnvRunners " + "significantly. Use the special value `BOTH` to run both ASYNC and SYNC through a " + "Tune grid-search.", +) + + +class SlowEnv(gym.ObservationWrapper): + def observation(self, observation): + time.sleep(0.005) + return observation + + +if __name__ == "__main__": + args = parser.parse_args() + + if args.no_tune and args.vectorize_mode == "BOTH": + raise ValueError( + "Can't run this script with both --no-tune and --vectorize-mode=BOTH!" + ) + + # Wrap the env with the slowness wrapper. + def _env_creator(cfg): + return SlowEnv(gym.make(args.env, **cfg)) + + tune.register_env("slow-env", _env_creator) + + if args.vectorize_mode == "BOTH" and args.no_tune: + raise ValueError( + "`--vectorize-mode=BOTH` and `--no-tune` not allowed in combination!" + ) + + base_config = ( + PPOConfig() + .environment("slow-env") + .env_runners( + gym_env_vectorize_mode=( + tune.grid_search(["SYNC", "ASYNC"]) + if args.vectorize_mode == "BOTH" + else args.vectorize_mode + ), + ) + ) + + results = run_rllib_example_script_experiment(base_config, args) + + # Compare the throughputs and assert that ASYNC is much faster than SYNC. + if args.vectorize_mode == "BOTH": + throughput_sync = ( + results[0].metrics["num_env_steps_sampled_lifetime"] + / results[0].metrics["time_total_s"] + ) + throughput_async = ( + results[1].metrics["num_env_steps_sampled_lifetime"] + / results[1].metrics["time_total_s"] + ) + assert throughput_async > throughput_sync diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eccd263693446156b6b43431d01a2ce41f8acf93 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/action_mask_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/action_mask_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fe9f1e388fde74bdcec893623950b758740ba37 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/action_mask_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_crashing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_crashing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..762a6bb30b1cc96d1a6bdc9366bddb8dac561ab8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_crashing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_sparse_rewards.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_sparse_rewards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a2346b6ef87ef9ddb9a0e261d63fe863de8cad4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_sparse_rewards.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_dict_observation_space.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_dict_observation_space.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87e3561c69275b2bd976be028c4de09986f868f8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_dict_observation_space.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_large_observation_space.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_large_observation_space.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dac8ae78751e345c3e7b1494cdb97b34f18951e0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_large_observation_space.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_protobuf_observation_space.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_protobuf_observation_space.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47ed253bda79ce825258595c1cf9d89b3381b5b0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cartpole_with_protobuf_observation_space.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cliff_walking_wall_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cliff_walking_wall_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..960637041cdd978da8264ddaa3a8d4aefed890f1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/cliff_walking_wall_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/correlated_actions_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/correlated_actions_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0a672c72c916c026adc94d81b8967430d005a65 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/correlated_actions_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/d4rl_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/d4rl_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfda7901e884b86b858bb088ecd95758c6e00b1b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/d4rl_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/debug_counter_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/debug_counter_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfbf78223d6d7ccb56fdb2638a947442a00393b1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/debug_counter_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/deterministic_envs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/deterministic_envs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4972adf4d246e6775457d9b1592d6c665ef28999 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/deterministic_envs.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/dm_control_suite.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/dm_control_suite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a08acdd9b8c5a40d9ee6e3994c71b85a895c1efc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/dm_control_suite.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/env_using_remote_actor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/env_using_remote_actor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3193ff83b2d7e404e896200b23ffd908ae409df0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/env_using_remote_actor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/env_with_subprocess.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/env_with_subprocess.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a27b3602350ceb2238612342871c5e6ccf0fe1b8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/env_with_subprocess.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/fast_image_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/fast_image_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bf73c6d489f73c76af4daf09406412b0f3aa3bb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/fast_image_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/gpu_requiring_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/gpu_requiring_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c7e5ce3464b2bd06d5ac4dde964fd665566f585 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/gpu_requiring_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/look_and_push.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/look_and_push.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebca93e6c91926baab2c3fde56769733bae4a0b8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/look_and_push.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/memory_leaking_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/memory_leaking_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34220c4b5c64f9d6d4288ff4aec167f92fe624cc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/memory_leaking_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/mock_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/mock_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..304361328d7626bbb4dde8eb8dc2d16460eff816 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/mock_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/nested_space_repeat_after_me_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/nested_space_repeat_after_me_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2c57b00d6453c8ccb28ab8556b713f7f04690e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/nested_space_repeat_after_me_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/parametric_actions_cartpole.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/parametric_actions_cartpole.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36f6ab3a1a32f29fe4e25d7cc1c975d0721a082a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/parametric_actions_cartpole.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/random_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/random_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7436492ccf967f1ca084e929cf01bccfd67ae25d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/random_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/recommender_system_envs_with_recsim.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/recommender_system_envs_with_recsim.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a642a0bec51f4b1b26da5b86795a6e7a03aa575c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/recommender_system_envs_with_recsim.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/repeat_after_me_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/repeat_after_me_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c48b242f21c3dd975cb04e8617215c7934f9293f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/repeat_after_me_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/repeat_initial_obs_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/repeat_initial_obs_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd50fda61e79220f7a18e4661c814d99160dd856 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/repeat_initial_obs_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/simple_corridor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/simple_corridor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12ed392a8902592b2f8931f3366742cf2bf46d33 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/simple_corridor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/simple_rpg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/simple_rpg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5f6ece3c571d180a5cfecb81e7238f340019399 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/simple_rpg.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/six_room_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/six_room_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..011b6f048e17a22bf1044829b963a6b36c6e980c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/six_room_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/stateless_cartpole.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/stateless_cartpole.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3cdcf6806ff143650b73f8c636fd1f5c66712e3d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/stateless_cartpole.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/stateless_pendulum.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/stateless_pendulum.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0192397b4fbb326691931a0a21a3d6728cc0cbbb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/stateless_pendulum.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/transformed_action_space_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/transformed_action_space_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c5f217e7a93b4929bc6c06af5608b86823c1b83 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/transformed_action_space_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/windy_maze_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/windy_maze_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fa948b8869ecee7fdff2414fc4e223b0da94e32 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/__pycache__/windy_maze_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/action_mask_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/action_mask_env.py new file mode 100644 index 0000000000000000000000000000000000000000..7c67db342f72805fff52672ccb767b62a92c3167 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/action_mask_env.py @@ -0,0 +1,42 @@ +from gymnasium.spaces import Box, Dict, Discrete +import numpy as np + +from ray.rllib.examples.envs.classes.random_env import RandomEnv + + +class ActionMaskEnv(RandomEnv): + """A randomly acting environment that publishes an action-mask each step.""" + + def __init__(self, config): + super().__init__(config) + # Masking only works for Discrete actions. + assert isinstance(self.action_space, Discrete) + # Add action_mask to observations. + self.observation_space = Dict( + { + "action_mask": Box(0.0, 1.0, shape=(self.action_space.n,)), + "observations": self.observation_space, + } + ) + self.valid_actions = None + + def reset(self, *, seed=None, options=None): + obs, info = super().reset() + self._fix_action_mask(obs) + return obs, info + + def step(self, action): + # Check whether action is valid. + if not self.valid_actions[action]: + raise ValueError( + f"Invalid action ({action}) sent to env! " + f"valid_actions={self.valid_actions}" + ) + obs, rew, done, truncated, info = super().step(action) + self._fix_action_mask(obs) + return obs, rew, done, truncated, info + + def _fix_action_mask(self, obs): + # Fix action-mask: Everything larger 0.5 is 1.0, everything else 0.0. + self.valid_actions = np.round(obs["action_mask"]) + obs["action_mask"] = self.valid_actions diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_crashing.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_crashing.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5e4f14b4f4dd386242d0105e2fd5b52103bcc8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_crashing.py @@ -0,0 +1,182 @@ +import logging +from gymnasium.envs.classic_control import CartPoleEnv +import numpy as np +import time + +from ray.rllib.examples.envs.classes.multi_agent import make_multi_agent +from ray.rllib.utils.annotations import override +from ray.rllib.utils.error import EnvError + +logger = logging.getLogger(__name__) + + +class CartPoleCrashing(CartPoleEnv): + """A CartPole env that crashes (or stalls) from time to time. + + Useful for testing faulty sub-env (within a vectorized env) handling by + EnvRunners. + + After crashing, the env expects a `reset()` call next (calling `step()` will + result in yet another error), which may or may not take a very long time to + complete. This simulates the env having to reinitialize some sub-processes, e.g. + an external connection. + + The env can also be configured to stall (and do nothing during a call to `step()`) + from time to time for a configurable amount of time. + """ + + def __init__(self, config=None): + super().__init__() + + self.config = config if config is not None else {} + + # Crash probability (in each `step()`). + self.p_crash = config.get("p_crash", 0.005) + # Crash probability when `reset()` is called. + self.p_crash_reset = config.get("p_crash_reset", 0.0) + # Crash exactly after every n steps. If a 2-tuple, will uniformly sample + # crash timesteps from in between the two given values. + self.crash_after_n_steps = config.get("crash_after_n_steps") + self._crash_after_n_steps = None + assert ( + self.crash_after_n_steps is None + or isinstance(self.crash_after_n_steps, int) + or ( + isinstance(self.crash_after_n_steps, tuple) + and len(self.crash_after_n_steps) == 2 + ) + ) + # Only ever crash, if on certain worker indices. + faulty_indices = config.get("crash_on_worker_indices", None) + if faulty_indices and config.worker_index not in faulty_indices: + self.p_crash = 0.0 + self.p_crash_reset = 0.0 + self.crash_after_n_steps = None + + # Stall probability (in each `step()`). + self.p_stall = config.get("p_stall", 0.0) + # Stall probability when `reset()` is called. + self.p_stall_reset = config.get("p_stall_reset", 0.0) + # Stall exactly after every n steps. + self.stall_after_n_steps = config.get("stall_after_n_steps") + self._stall_after_n_steps = None + # Amount of time to stall. If a 2-tuple, will uniformly sample from in between + # the two given values. + self.stall_time_sec = config.get("stall_time_sec") + assert ( + self.stall_time_sec is None + or isinstance(self.stall_time_sec, (int, float)) + or ( + isinstance(self.stall_time_sec, tuple) and len(self.stall_time_sec) == 2 + ) + ) + + # Only ever stall, if on certain worker indices. + faulty_indices = config.get("stall_on_worker_indices", None) + if faulty_indices and config.worker_index not in faulty_indices: + self.p_stall = 0.0 + self.p_stall_reset = 0.0 + self.stall_after_n_steps = None + + # Timestep counter for the ongoing episode. + self.timesteps = 0 + + # Time in seconds to initialize (in this c'tor). + sample = 0.0 + if "init_time_s" in config: + sample = ( + config["init_time_s"] + if not isinstance(config["init_time_s"], tuple) + else np.random.uniform( + config["init_time_s"][0], config["init_time_s"][1] + ) + ) + + print(f"Initializing crashing env (with init-delay of {sample}sec) ...") + time.sleep(sample) + + # Make sure envs don't crash at the same time. + self._rng = np.random.RandomState() + + @override(CartPoleEnv) + def reset(self, *, seed=None, options=None): + # Reset timestep counter for the new episode. + self.timesteps = 0 + self._crash_after_n_steps = None + + # Should we crash? + if self._should_crash(p=self.p_crash_reset): + raise EnvError( + f"Simulated env crash on worker={self.config.worker_index} " + f"env-idx={self.config.vector_index} during `reset()`! " + "Feel free to use any other exception type here instead." + ) + # Should we stall for a while? + self._stall_if_necessary(p=self.p_stall_reset) + + return super().reset() + + @override(CartPoleEnv) + def step(self, action): + # Increase timestep counter for the ongoing episode. + self.timesteps += 1 + + # Should we crash? + if self._should_crash(p=self.p_crash): + raise EnvError( + f"Simulated env crash on worker={self.config.worker_index} " + f"env-idx={self.config.vector_index} during `step()`! " + "Feel free to use any other exception type here instead." + ) + # Should we stall for a while? + self._stall_if_necessary(p=self.p_stall) + + return super().step(action) + + def _should_crash(self, p): + rnd = self._rng.rand() + if rnd < p: + print("Crashing due to p(crash)!") + return True + elif self.crash_after_n_steps is not None: + if self._crash_after_n_steps is None: + self._crash_after_n_steps = ( + self.crash_after_n_steps + if not isinstance(self.crash_after_n_steps, tuple) + else np.random.randint( + self.crash_after_n_steps[0], self.crash_after_n_steps[1] + ) + ) + if self._crash_after_n_steps == self.timesteps: + print("Crashing due to n timesteps reached!") + return True + + return False + + def _stall_if_necessary(self, p): + stall = False + if self._rng.rand() < p: + stall = True + elif self.stall_after_n_steps is not None: + if self._stall_after_n_steps is None: + self._stall_after_n_steps = ( + self.stall_after_n_steps + if not isinstance(self.stall_after_n_steps, tuple) + else np.random.randint( + self.stall_after_n_steps[0], self.stall_after_n_steps[1] + ) + ) + if self._stall_after_n_steps == self.timesteps: + stall = True + + if stall: + sec = ( + self.stall_time_sec + if not isinstance(self.stall_time_sec, tuple) + else np.random.uniform(self.stall_time_sec[0], self.stall_time_sec[1]) + ) + print(f" -> will stall for {sec}sec ...") + time.sleep(sec) + + +MultiAgentCartPoleCrashing = make_multi_agent(lambda config: CartPoleCrashing(config)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_sparse_rewards.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_sparse_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..d68f7614c1033ad8c60fe5736e66bdf88f14fc45 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_sparse_rewards.py @@ -0,0 +1,51 @@ +from copy import deepcopy + +import gymnasium as gym +import numpy as np +from gymnasium.spaces import Box, Dict, Discrete + + +class CartPoleSparseRewards(gym.Env): + """Wrapper for gym CartPole environment where reward is accumulated to the end.""" + + def __init__(self, config=None): + self.env = gym.make("CartPole-v1") + self.action_space = Discrete(2) + self.observation_space = Dict( + { + "obs": self.env.observation_space, + "action_mask": Box( + low=0, high=1, shape=(self.action_space.n,), dtype=np.int8 + ), + } + ) + self.running_reward = 0 + + def reset(self, *, seed=None, options=None): + self.running_reward = 0 + obs, infos = self.env.reset() + return { + "obs": obs, + "action_mask": np.array([1, 1], dtype=np.int8), + }, infos + + def step(self, action): + obs, rew, terminated, truncated, info = self.env.step(action) + self.running_reward += rew + score = self.running_reward if terminated else 0 + return ( + {"obs": obs, "action_mask": np.array([1, 1], dtype=np.int8)}, + score, + terminated, + truncated, + info, + ) + + def set_state(self, state): + self.running_reward = state[1] + self.env = deepcopy(state[0]) + obs = np.array(list(self.env.unwrapped.state)) + return {"obs": obs, "action_mask": np.array([1, 1], dtype=np.int8)} + + def get_state(self): + return deepcopy(self.env), self.running_reward diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_dict_observation_space.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_dict_observation_space.py new file mode 100644 index 0000000000000000000000000000000000000000..6ad54e26148cd72efa763a985b326c4e5b041668 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_dict_observation_space.py @@ -0,0 +1,74 @@ +import gymnasium as gym +from gymnasium.envs.classic_control import CartPoleEnv +import numpy as np + + +class CartPoleWithDictObservationSpace(CartPoleEnv): + """CartPole gym environment that has a dict observation space. + + However, otherwise, the information content in each observation remains the same. + + https://github.com/Farama-Foundation/Gymnasium/blob/main/gymnasium/envs/classic_control/cartpole.py # noqa + + The new observation space looks as follows (a little quirky, but this is + for testing purposes only): + + gym.spaces.Dict({ + "x-pos": [x-pos], + "angular-pos": gym.spaces.Dict({"test": [angular-pos]}), + "velocs": gym.spaces.Tuple([x-veloc, angular-veloc]), + }) + """ + + def __init__(self, config=None): + super().__init__() + + # Fix our observation-space as described above. + low = self.observation_space.low + high = self.observation_space.high + + # Test as many quirks and oddities as possible: Dict, Dict inside a Dict, + # Tuple inside a Dict, and both (1,)-shapes as well as ()-shapes for Boxes. + # Also add a random discrete variable here. + self.observation_space = gym.spaces.Dict( + { + "x-pos": gym.spaces.Box(low[0], high[0], (1,), dtype=np.float32), + "angular-pos": gym.spaces.Dict( + { + "value": gym.spaces.Box(low[2], high[2], (), dtype=np.float32), + # Add some random non-essential information. + "some_random_stuff": gym.spaces.Discrete(3), + } + ), + "velocs": gym.spaces.Tuple( + [ + # x-veloc + gym.spaces.Box(low[1], high[1], (1,), dtype=np.float32), + # angular-veloc + gym.spaces.Box(low[3], high[3], (), dtype=np.float32), + ] + ), + } + ) + + def step(self, action): + next_obs, reward, done, truncated, info = super().step(action) + return self._compile_current_obs(next_obs), reward, done, truncated, info + + def reset(self, *, seed=None, options=None): + init_obs, init_info = super().reset(seed=seed, options=options) + return self._compile_current_obs(init_obs), init_info + + def _compile_current_obs(self, original_cartpole_obs): + # original_cartpole_obs is [x-pos, x-veloc, angle, angle-veloc] + return { + "x-pos": np.array([original_cartpole_obs[0]], np.float32), + "angular-pos": { + "value": np.array(original_cartpole_obs[2]), + "some_random_stuff": np.random.randint(3), + }, + "velocs": ( + np.array([original_cartpole_obs[1]], np.float32), + np.array(original_cartpole_obs[3], np.float32), + ), + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_large_observation_space.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_large_observation_space.py new file mode 100644 index 0000000000000000000000000000000000000000..162db205658bb9bb78426300b23a6d90913fc89f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_large_observation_space.py @@ -0,0 +1,69 @@ +import gymnasium as gym +from gymnasium.envs.classic_control import CartPoleEnv +import numpy as np + + +class CartPoleWithLargeObservationSpace(CartPoleEnv): + """CartPole gym environment that has a large dict observation space. + + However, otherwise, the information content in each observation remains the same. + + https://github.com/Farama-Foundation/Gymnasium/blob/main/gymnasium/envs/classic_control/cartpole.py # noqa + + The new observation space looks as follows (a little quirky, but this is + for testing purposes only): + + gym.spaces.Dict({ + "1": gym.spaces.Tuple(( + gym.spaces.Discrete(100), + gym.spaces.Box(0, 256, shape=(30,), dtype=float32), + )), + "2": gym.spaces.Tuple(( + gym.spaces.Discrete(100), + gym.spaces.Box(0, 256, shape=(30,), dtype=float32), + )), + "3": ... + "actual-obs": gym.spaces.Box(-inf, inf, (4,), float32), + }) + """ + + def __init__(self, config=None): + super().__init__() + + # Fix our observation-space as described above. + low = self.observation_space.low + high = self.observation_space.high + + # Test as many quirks and oddities as possible: Dict, Dict inside a Dict, + # Tuple inside a Dict, and both (1,)-shapes as well as ()-shapes for Boxes. + # Also add a random discrete variable here. + spaces = { + str(i): gym.spaces.Tuple( + ( + gym.spaces.Discrete(100), + gym.spaces.Box(0, 256, shape=(30,), dtype=np.float32), + ) + ) + for i in range(100) + } + spaces.update( + { + "actually-useful-stuff": ( + gym.spaces.Box(low[0], high[0], (4,), np.float32) + ) + } + ) + self.observation_space = gym.spaces.Dict(spaces) + + def step(self, action): + next_obs, reward, done, truncated, info = super().step(action) + return self._compile_current_obs(next_obs), reward, done, truncated, info + + def reset(self, *, seed=None, options=None): + init_obs, init_info = super().reset(seed=seed, options=options) + return self._compile_current_obs(init_obs), init_info + + def _compile_current_obs(self, original_cartpole_obs): + return { + str(i): self.observation_space.spaces[str(i)].sample() for i in range(100) + } | {"actually-useful-stuff": original_cartpole_obs} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_protobuf_observation_space.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_protobuf_observation_space.py new file mode 100644 index 0000000000000000000000000000000000000000..f88b802d37a08ddf2c0972ace4eba8e8315521ea --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cartpole_with_protobuf_observation_space.py @@ -0,0 +1,79 @@ +import gymnasium as gym +from gymnasium.envs.classic_control import CartPoleEnv +import numpy as np + +from ray.rllib.examples.envs.classes.utils.cartpole_observations_proto import ( + CartPoleObservation, +) + + +class CartPoleWithProtobufObservationSpace(CartPoleEnv): + """CartPole gym environment that has a protobuf observation space. + + Sometimes, it is more performant for an environment to publish its observations + as a protobuf message (instead of a heavily nested Dict). + + The protobuf message used here is originally defined in the + `./utils/cartpole_observations.proto` file. We converted this file into a python + importable module by compiling it with: + + `protoc --python_out=. cartpole_observations.proto` + + .. which yielded the `cartpole_observations_proto.py` file in the same directory + (we import this file's `CartPoleObservation` message here). + + The new observation space is a (binary) Box(0, 255, ([len of protobuf],), uint8). + + A ConnectorV2 pipeline or simpler gym.Wrapper will have to be used to convert this + observation format into an NN-readable (e.g. float32) 1D tensor. + """ + + def __init__(self, config=None): + super().__init__() + dummy_obs = self._convert_observation_to_protobuf( + np.array([1.0, 1.0, 1.0, 1.0]) + ) + bin_length = len(dummy_obs) + self.observation_space = gym.spaces.Box(0, 255, (bin_length,), np.uint8) + + def step(self, action): + observation, reward, terminated, truncated, info = super().step(action) + proto_observation = self._convert_observation_to_protobuf(observation) + return proto_observation, reward, terminated, truncated, info + + def reset(self, **kwargs): + observation, info = super().reset(**kwargs) + proto_observation = self._convert_observation_to_protobuf(observation) + return proto_observation, info + + def _convert_observation_to_protobuf(self, observation): + x_pos, x_veloc, angle_pos, angle_veloc = observation + + # Create the Protobuf message + cartpole_observation = CartPoleObservation() + cartpole_observation.x_pos = x_pos + cartpole_observation.x_veloc = x_veloc + cartpole_observation.angle_pos = angle_pos + cartpole_observation.angle_veloc = angle_veloc + + # Serialize to binary string. + return np.frombuffer(cartpole_observation.SerializeToString(), np.uint8) + + +if __name__ == "__main__": + env = CartPoleWithProtobufObservationSpace() + obs, info = env.reset() + + # Test loading a protobuf object with data from the obs binary string + # (uint8 ndarray). + byte_str = obs.tobytes() + obs_protobuf = CartPoleObservation() + obs_protobuf.ParseFromString(byte_str) + print(obs_protobuf) + + terminated = truncated = False + while not terminated and not truncated: + action = env.action_space.sample() + obs, reward, terminated, truncated, info = env.step(action) + + print(obs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cliff_walking_wall_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cliff_walking_wall_env.py new file mode 100644 index 0000000000000000000000000000000000000000..496e86e3f90782a6227c570c157e74c3c03741a6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/cliff_walking_wall_env.py @@ -0,0 +1,71 @@ +import gymnasium as gym +from gymnasium import spaces + +ACTION_UP = 0 +ACTION_RIGHT = 1 +ACTION_DOWN = 2 +ACTION_LEFT = 3 + + +class CliffWalkingWallEnv(gym.Env): + """Modified version of the CliffWalking environment from Farama-Foundation's + Gymnasium with walls instead of a cliff. + + ### Description + The board is a 4x12 matrix, with (using NumPy matrix indexing): + - [3, 0] or obs==36 as the start at bottom-left + - [3, 11] or obs==47 as the goal at bottom-right + - [3, 1..10] or obs==37...46 as the cliff at bottom-center + + An episode terminates when the agent reaches the goal. + + ### Actions + There are 4 discrete deterministic actions: + - 0: move up + - 1: move right + - 2: move down + - 3: move left + You can also use the constants ACTION_UP, ACTION_RIGHT, ... defined above. + + ### Observations + There are 3x12 + 2 possible states, not including the walls. If an action + would move an agent into one of the walls, it simply stays in the same position. + + ### Reward + Each time step incurs -1 reward, except reaching the goal which gives +10 reward. + """ + + def __init__(self, seed=42) -> None: + self.observation_space = spaces.Discrete(48) + self.action_space = spaces.Discrete(4) + self.observation_space.seed(seed) + self.action_space.seed(seed) + + def reset(self, *, seed=None, options=None): + self.position = 36 + return self.position, {} + + def step(self, action): + x = self.position // 12 + y = self.position % 12 + # UP + if action == ACTION_UP: + x = max(x - 1, 0) + # RIGHT + elif action == ACTION_RIGHT: + if self.position != 36: + y = min(y + 1, 11) + # DOWN + elif action == ACTION_DOWN: + if self.position < 25 or self.position > 34: + x = min(x + 1, 3) + # LEFT + elif action == ACTION_LEFT: + if self.position != 47: + y = max(y - 1, 0) + else: + raise ValueError(f"action {action} not in {self.action_space}") + self.position = x * 12 + y + done = self.position == 47 + reward = -1 if not done else 10 + return self.position, reward, done, False, {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/correlated_actions_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/correlated_actions_env.py new file mode 100644 index 0000000000000000000000000000000000000000..8b0bdb882fc0bb05fe801ed4999fa8a1a74f5585 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/correlated_actions_env.py @@ -0,0 +1,79 @@ +from typing import Any, Dict, Optional + +import gymnasium as gym +import numpy as np + + +class CorrelatedActionsEnv(gym.Env): + """Environment that can only be solved through an autoregressive action model. + + In each step, the agent observes a random number (between -1 and 1) and has + to choose two actions, a1 (discrete, 0, 1, or 2) and a2 (cont. between -1 and 1). + + The reward is constructed such that actions need to be correlated to succeed. It's + impossible for the network to learn each action head separately. + + There are two reward components: + The first is the negative absolute value of the delta between 1.0 and the sum of + obs + a1. For example, if obs is -0.3 and a1 was sampled to be 1, then the value of + the first reward component is: + r1 = -abs(1.0 - [obs+a1]) = -abs(1.0 - (-0.3 + 1)) = -abs(0.3) = -0.3 + The second reward component is computed as the negative absolute value + of `obs + a1 + a2`. For example, if obs is 0.5, a1 was sampled to be 0, + and a2 was sampled to be -0.7, then the value of the second reward component is: + r2 = -abs(obs + a1 + a2) = -abs(0.5 + 0 - 0.7)) = -abs(-0.2) = -0.2 + + Because of this specific reward function, the agent must learn to optimally sample + a1 based on the observation and to optimally sample a2, based on the observation + AND the sampled value of a1. + + One way to effectively learn this is through correlated action + distributions, e.g., in examples/actions/auto_regressive_actions.py + + The game ends after the first step. + """ + + def __init__(self, config=None): + super().__init__() + # Observation space (single continuous value between -1. and 1.). + self.observation_space = gym.spaces.Box(-1.0, 1.0, shape=(1,), dtype=np.float32) + + # Action space (discrete action a1 and continuous action a2). + self.action_space = gym.spaces.Tuple( + [gym.spaces.Discrete(3), gym.spaces.Box(-2.0, 2.0, (1,), np.float32)] + ) + + # Internal state for the environment (e.g., could represent a factor + # influencing the relationship) + self.obs = None + + def reset( + self, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None + ): + """Reset the environment to an initial state.""" + super().reset(seed=seed, options=options) + + # Randomly initialize the observation between -1 and 1. + self.obs = np.random.uniform(-1, 1, size=(1,)) + + return self.obs, {} + + def step(self, action): + """Apply the autoregressive action and return step information.""" + + # Extract individual action components, a1 and a2. + a1, a2 = action + a2 = a2[0] # dissolve shape=(1,) + + # r1 depends on how well a1 is aligned to obs: + r1 = -abs(1.0 - (self.obs[0] + a1)) + # r2 depends on how well a2 is aligned to both, obs and a1. + r2 = -abs(self.obs[0] + a1 + a2) + + reward = r1 + r2 + + # Optionally: add some noise or complexity to the reward function + # reward += np.random.normal(0, 0.01) # Small noise can be added + + # Terminate after each step (no episode length in this simple example) + return self.obs, reward, True, False, {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/d4rl_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/d4rl_env.py new file mode 100644 index 0000000000000000000000000000000000000000..768c66db48bae7dcbd45240c8b55cd80caa51865 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/d4rl_env.py @@ -0,0 +1,46 @@ +""" +8 Environments from D4RL Environment. +Use fully qualified class-path in your configs: +e.g. "env": "ray.rllib.examples.envs.classes.d4rl_env.halfcheetah_random". +""" + +import gymnasium as gym + +try: + import d4rl + + _ = d4rl.__name__ # Fool LINTer. +except ImportError: + d4rl = None + + +def halfcheetah_random(): + return gym.make("halfcheetah-random-v0") + + +def halfcheetah_medium(): + return gym.make("halfcheetah-medium-v0") + + +def halfcheetah_expert(): + return gym.make("halfcheetah-expert-v0") + + +def halfcheetah_medium_replay(): + return gym.make("halfcheetah-medium-replay-v0") + + +def hopper_random(): + return gym.make("hopper-random-v0") + + +def hopper_medium(): + return gym.make("hopper-medium-v0") + + +def hopper_expert(): + return gym.make("hopper-expert-v0") + + +def hopper_medium_replay(): + return gym.make("hopper-medium-replay-v0") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/debug_counter_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/debug_counter_env.py new file mode 100644 index 0000000000000000000000000000000000000000..404833e18d8d81bb6cfd3b7318a80233524262c5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/debug_counter_env.py @@ -0,0 +1,92 @@ +import gymnasium as gym +import numpy as np + +from ray.rllib.env.multi_agent_env import MultiAgentEnv + + +class DebugCounterEnv(gym.Env): + """Simple Env that yields a ts counter as observation (0-based). + + Actions have no effect. + The episode length is always 15. + Reward is always: current ts % 3. + """ + + def __init__(self, config=None): + config = config or {} + self.action_space = gym.spaces.Discrete(2) + self.observation_space = gym.spaces.Box(0, 100, (1,), dtype=np.float32) + self.start_at_t = int(config.get("start_at_t", 0)) + self.i = self.start_at_t + + def reset(self, *, seed=None, options=None): + self.i = self.start_at_t + return self._get_obs(), {} + + def step(self, action): + self.i += 1 + terminated = False + truncated = self.i >= 15 + self.start_at_t + return self._get_obs(), float(self.i % 3), terminated, truncated, {} + + def _get_obs(self): + return np.array([self.i], dtype=np.float32) + + +class MultiAgentDebugCounterEnv(MultiAgentEnv): + def __init__(self, config): + super().__init__() + self.num_agents = config["num_agents"] + self.base_episode_len = config.get("base_episode_len", 103) + + # Observation dims: + # 0=agent ID. + # 1=episode ID (0.0 for obs after reset). + # 2=env ID (0.0 for obs after reset). + # 3=ts (of the agent). + self.observation_space = gym.spaces.Dict( + { + aid: gym.spaces.Box(float("-inf"), float("inf"), (4,)) + for aid in range(self.num_agents) + } + ) + + # Actions are always: + # (episodeID, envID) as floats. + self.action_space = gym.spaces.Dict( + { + aid: gym.spaces.Box(-float("inf"), float("inf"), shape=(2,)) + for aid in range(self.num_agents) + } + ) + + self.timesteps = [0] * self.num_agents + self.terminateds = set() + self.truncateds = set() + + def reset(self, *, seed=None, options=None): + self.timesteps = [0] * self.num_agents + self.terminateds = set() + self.truncateds = set() + return { + i: np.array([i, 0.0, 0.0, 0.0], dtype=np.float32) + for i in range(self.num_agents) + }, {} + + def step(self, action_dict): + obs, rew, terminated, truncated = {}, {}, {}, {} + for i, action in action_dict.items(): + self.timesteps[i] += 1 + obs[i] = np.array([i, action[0], action[1], self.timesteps[i]]) + rew[i] = self.timesteps[i] % 3 + terminated[i] = False + truncated[i] = ( + True if self.timesteps[i] > self.base_episode_len + i else False + ) + if terminated[i]: + self.terminateds.add(i) + if truncated[i]: + self.truncateds.add(i) + terminated["__all__"] = len(self.terminateds) == self.num_agents + truncated["__all__"] = len(self.truncateds) == self.num_agents + return obs, rew, terminated, truncated, {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/deterministic_envs.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/deterministic_envs.py new file mode 100644 index 0000000000000000000000000000000000000000..51f41f29fb3b0981f4d97106b678eec4e230eccc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/deterministic_envs.py @@ -0,0 +1,13 @@ +import gymnasium as gym + + +def create_cartpole_deterministic(config): + env = gym.make("CartPole-v1") + env.reset(seed=config.get("seed", 0)) + return env + + +def create_pendulum_deterministic(config): + env = gym.make("Pendulum-v1") + env.reset(seed=config.get("seed", 0)) + return env diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/dm_control_suite.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/dm_control_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..8a1425fac214b8a28d4e169a363a8f5dfcaa9dc5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/dm_control_suite.py @@ -0,0 +1,131 @@ +from ray.rllib.env.wrappers.dm_control_wrapper import DMCEnv + +""" +8 Environments from Deepmind Control Suite +""" + + +def acrobot_swingup( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "acrobot", + "swingup", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) + + +def walker_walk( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "walker", + "walk", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) + + +def hopper_hop( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "hopper", + "hop", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) + + +def hopper_stand( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "hopper", + "stand", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) + + +def cheetah_run( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "cheetah", + "run", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) + + +def walker_run( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "walker", + "run", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) + + +def pendulum_swingup( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "pendulum", + "swingup", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) + + +def cartpole_swingup( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "cartpole", + "swingup", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) + + +def humanoid_walk( + from_pixels=True, height=64, width=64, frame_skip=2, channels_first=True +): + return DMCEnv( + "humanoid", + "walk", + from_pixels=from_pixels, + height=height, + width=width, + frame_skip=frame_skip, + channels_first=channels_first, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/env_using_remote_actor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/env_using_remote_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..b52242c9679abbad559db9e586310e93f9bb8928 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/env_using_remote_actor.py @@ -0,0 +1,63 @@ +""" +Example of an environment that uses a named remote actor as parameter +server. + +""" +from gymnasium.envs.classic_control.cartpole import CartPoleEnv +from gymnasium.utils import seeding + +import ray + + +@ray.remote +class ParameterStorage: + def get_params(self, rng): + return { + "MASSCART": rng.uniform(low=0.5, high=2.0), + } + + +class CartPoleWithRemoteParamServer(CartPoleEnv): + """CartPoleMassEnv varies the weights of the cart and the pole.""" + + def __init__(self, env_config): + self.env_config = env_config + super().__init__() + # Get our param server (remote actor) by name. + self._handler = ray.get_actor(env_config.get("param_server", "param-server")) + self.rng_seed = None + self.np_random, _ = seeding.np_random(self.rng_seed) + + def reset(self, *, seed=None, options=None): + if seed is not None: + self.rng_seed = int(seed) + self.np_random, _ = seeding.np_random(seed) + print( + f"Seeding env (worker={self.env_config.worker_index}) " f"with {seed}" + ) + + # Pass in our RNG to guarantee no race conditions. + # If `self._handler` had its own RNG, this may clash with other + # envs trying to use the same param-server. + params = ray.get(self._handler.get_params.remote(self.np_random)) + + # IMPORTANT: Advance the state of our RNG (self._rng was passed + # above via ray (serialized) and thus not altered locally here!). + # Or create a new RNG from another random number: + # Seed the RNG with a deterministic seed if set, otherwise, create + # a random one. + new_seed = int( + self.np_random.integers(0, 1000000) if not self.rng_seed else self.rng_seed + ) + self.np_random, _ = seeding.np_random(new_seed) + + print( + f"Env worker-idx={self.env_config.worker_index} " + f"mass={params['MASSCART']}" + ) + + self.masscart = params["MASSCART"] + self.total_mass = self.masspole + self.masscart + self.polemass_length = self.masspole * self.length + + return super().reset() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/env_with_subprocess.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/env_with_subprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..424f1eb095074a834f39d9159581dfddb190996f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/env_with_subprocess.py @@ -0,0 +1,42 @@ +import atexit +import gymnasium as gym +from gymnasium.spaces import Discrete +import os +import subprocess + + +class EnvWithSubprocess(gym.Env): + """An env that spawns a subprocess.""" + + # Dummy command to run as a subprocess with a unique name + UNIQUE_CMD = "sleep 20" + + def __init__(self, config): + self.UNIQUE_FILE_0 = config["tmp_file1"] + self.UNIQUE_FILE_1 = config["tmp_file2"] + self.UNIQUE_FILE_2 = config["tmp_file3"] + self.UNIQUE_FILE_3 = config["tmp_file4"] + + self.action_space = Discrete(2) + self.observation_space = Discrete(2) + # Subprocess that should be cleaned up. + self.subproc = subprocess.Popen(self.UNIQUE_CMD.split(" "), shell=False) + self.config = config + # Exit handler should be called. + atexit.register(lambda: self.subproc.kill()) + if config.worker_index == 0: + atexit.register(lambda: os.unlink(self.UNIQUE_FILE_0)) + else: + atexit.register(lambda: os.unlink(self.UNIQUE_FILE_1)) + + def close(self): + if self.config.worker_index == 0: + os.unlink(self.UNIQUE_FILE_2) + else: + os.unlink(self.UNIQUE_FILE_3) + + def reset(self, *, seed=None, options=None): + return 0, {} + + def step(self, action): + return 0, 0, True, False, {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/fast_image_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/fast_image_env.py new file mode 100644 index 0000000000000000000000000000000000000000..1eaad9a8fe81966ad42971b598bfcf6d125c11c7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/fast_image_env.py @@ -0,0 +1,20 @@ +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +import numpy as np + + +class FastImageEnv(gym.Env): + def __init__(self, config): + self.zeros = np.zeros((84, 84, 4)) + self.action_space = Discrete(2) + self.observation_space = Box(0.0, 1.0, shape=(84, 84, 4), dtype=np.float32) + self.i = 0 + + def reset(self, *, seed=None, options=None): + self.i = 0 + return self.zeros, {} + + def step(self, action): + self.i += 1 + done = truncated = self.i > 1000 + return self.zeros, 1, done, truncated, {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/gpu_requiring_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/gpu_requiring_env.py new file mode 100644 index 0000000000000000000000000000000000000000..1ac16edd7acf75ad100e76a01910ba1ac40abc49 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/gpu_requiring_env.py @@ -0,0 +1,37 @@ +import numpy as np + +import ray +from ray.rllib.examples.envs.classes.simple_corridor import SimpleCorridor +from ray.rllib.utils.framework import try_import_torch + +torch, _ = try_import_torch() + + +class GPURequiringEnv(SimpleCorridor): + """A dummy env that requires a GPU in order to work. + + The env here is a simple corridor env that additionally simulates a GPU + check in its constructor via `ray.get_gpu_ids()`. If this returns an + empty list, we raise an error. + + To make this env work, use `num_gpus_per_env_runner > 0` (RolloutWorkers + requesting this many GPUs each) and - maybe - `num_gpus > 0` in case + your local worker/driver must have an env as well. However, this is + only the case if `create_local_env_runner`=True (default is False). + """ + + def __init__(self, config=None): + super().__init__(config) + + # Fake-require some GPUs (at least one). + # If your local worker's env (`create_local_env_runner`=True) does not + # necessarily require a GPU, you can perform the below assertion only + # if `config.worker_index != 0`. + gpus_available = ray.get_gpu_ids() + print(f"{type(self).__name__} can see GPUs={gpus_available}") + + # Create a dummy tensor on the GPU. + if len(gpus_available) > 0 and torch: + self._tensor = torch.from_numpy(np.random.random_sample(size=(42, 42))).to( + f"cuda:{gpus_available[0]}" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/look_and_push.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/look_and_push.py new file mode 100644 index 0000000000000000000000000000000000000000..46c77b620e8a472499bf23a32c8da178c49a929e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/look_and_push.py @@ -0,0 +1,65 @@ +import gymnasium as gym +import numpy as np + + +class LookAndPush(gym.Env): + """Memory-requiring Env: Best sequence of actions depends on prev. states. + + Optimal behavior: + 0) a=0 -> observe next state (s'), which is the "hidden" state. + If a=1 here, the hidden state is not observed. + 1) a=1 to always jump to s=2 (not matter what the prev. state was). + 2) a=1 to move to s=3. + 3) a=1 to move to s=4. + 4) a=0 OR 1 depending on s' observed after 0): +10 reward and done. + otherwise: -10 reward and done. + """ + + def __init__(self): + self.action_space = gym.spaces.Discrete(2) + self.observation_space = gym.spaces.Discrete(5) + self._state = None + self._case = None + + def reset(self, *, seed=None, options=None): + self._state = 2 + self._case = np.random.choice(2) + return self._state, {} + + def step(self, action): + assert self.action_space.contains(action) + + if self._state == 4: + if action and self._case: + return self._state, 10.0, True, {} + else: + return self._state, -10, True, {} + else: + if action: + if self._state == 0: + self._state = 2 + else: + self._state += 1 + elif self._state == 2: + self._state = self._case + + return self._state, -1, False, False, {} + + +class OneHot(gym.Wrapper): + def __init__(self, env): + super(OneHot, self).__init__(env) + self.observation_space = gym.spaces.Box(0.0, 1.0, (env.observation_space.n,)) + + def reset(self, *, seed=None, options=None): + obs, info = self.env.reset(seed=seed, options=options) + return self._encode_obs(obs), info + + def step(self, action): + obs, reward, terminated, truncated, info = self.env.step(action) + return self._encode_obs(obs), reward, terminated, truncated, info + + def _encode_obs(self, obs): + new_obs = np.ones(self.env.observation_space.n) + new_obs[obs] = 1.0 + return new_obs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/memory_leaking_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/memory_leaking_env.py new file mode 100644 index 0000000000000000000000000000000000000000..c97edb296691f14a9566c7e6645d47049410cd9f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/memory_leaking_env.py @@ -0,0 +1,35 @@ +import logging +import uuid + +from ray.rllib.examples.envs.classes.random_env import RandomEnv +from ray.rllib.utils.annotations import override + +logger = logging.getLogger(__name__) + + +class MemoryLeakingEnv(RandomEnv): + """An env that leaks very little memory. + + Useful for proving that our memory-leak tests can catch the + slightest leaks. + """ + + def __init__(self, config=None): + super().__init__(config) + self._leak = {} + self._steps_after_reset = 0 + + @override(RandomEnv) + def reset(self, *, seed=None, options=None): + self._steps_after_reset = 0 + return super().reset(seed=seed, options=options) + + @override(RandomEnv) + def step(self, action): + self._steps_after_reset += 1 + + # Only leak once an episode. + if self._steps_after_reset == 2: + self._leak[uuid.uuid4().hex.upper()] = 1 + + return super().step(action) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/mock_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/mock_env.py new file mode 100644 index 0000000000000000000000000000000000000000..85d8b26935c3a1aa831ad912316f81c0246c7747 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/mock_env.py @@ -0,0 +1,220 @@ +import gymnasium as gym +import numpy as np +from typing import Optional + +from ray.rllib.env.vector_env import VectorEnv +from ray.rllib.utils.annotations import override + + +class MockEnv(gym.Env): + """Mock environment for testing purposes. + + Observation=0, reward=1.0, episode-len is configurable. + Actions are ignored. + """ + + def __init__(self, episode_length, config=None): + self.episode_length = episode_length + self.config = config + self.i = 0 + self.observation_space = gym.spaces.Discrete(1) + self.action_space = gym.spaces.Discrete(2) + + def reset(self, *, seed=None, options=None): + self.i = 0 + return 0, {} + + def step(self, action): + self.i += 1 + terminated = truncated = self.i >= self.episode_length + return 0, 1.0, terminated, truncated, {} + + +class MockEnv2(gym.Env): + """Mock environment for testing purposes. + + Observation=ts (discrete space!), reward=100.0, episode-len is + configurable. Actions are ignored. + """ + + metadata = { + "render.modes": ["rgb_array"], + } + render_mode: Optional[str] = "rgb_array" + + def __init__(self, episode_length): + self.episode_length = episode_length + self.i = 0 + self.observation_space = gym.spaces.Discrete(self.episode_length + 1) + self.action_space = gym.spaces.Discrete(2) + self.rng_seed = None + + def reset(self, *, seed=None, options=None): + self.i = 0 + if seed is not None: + self.rng_seed = seed + return self.i, {} + + def step(self, action): + self.i += 1 + terminated = truncated = self.i >= self.episode_length + return self.i, 100.0, terminated, truncated, {} + + def render(self): + # Just generate a random image here for demonstration purposes. + # Also see `gym/envs/classic_control/cartpole.py` for + # an example on how to use a Viewer object. + return np.random.randint(0, 256, size=(300, 400, 3), dtype=np.uint8) + + +class MockEnv3(gym.Env): + """Mock environment for testing purposes. + + Observation=ts (discrete space!), reward=100.0, episode-len is + configurable. Actions are ignored. + """ + + def __init__(self, episode_length): + self.episode_length = episode_length + self.i = 0 + self.observation_space = gym.spaces.Discrete(100) + self.action_space = gym.spaces.Discrete(2) + + def reset(self, *, seed=None, options=None): + self.i = 0 + return self.i, {"timestep": 0} + + def step(self, action): + self.i += 1 + terminated = truncated = self.i >= self.episode_length + return self.i, self.i, terminated, truncated, {"timestep": self.i} + + +class VectorizedMockEnv(VectorEnv): + """Vectorized version of the MockEnv. + + Contains `num_envs` MockEnv instances, each one having its own + `episode_length` horizon. + """ + + def __init__(self, episode_length, num_envs): + super().__init__( + observation_space=gym.spaces.Discrete(1), + action_space=gym.spaces.Discrete(2), + num_envs=num_envs, + ) + self.envs = [MockEnv(episode_length) for _ in range(num_envs)] + + @override(VectorEnv) + def vector_reset(self, *, seeds=None, options=None): + seeds = seeds or [None] * self.num_envs + options = options or [None] * self.num_envs + obs_and_infos = [ + e.reset(seed=seeds[i], options=options[i]) for i, e in enumerate(self.envs) + ] + return [oi[0] for oi in obs_and_infos], [oi[1] for oi in obs_and_infos] + + @override(VectorEnv) + def reset_at(self, index, *, seed=None, options=None): + return self.envs[index].reset(seed=seed, options=options) + + @override(VectorEnv) + def vector_step(self, actions): + obs_batch, rew_batch, terminated_batch, truncated_batch, info_batch = ( + [], + [], + [], + [], + [], + ) + for i in range(len(self.envs)): + obs, rew, terminated, truncated, info = self.envs[i].step(actions[i]) + obs_batch.append(obs) + rew_batch.append(rew) + terminated_batch.append(terminated) + truncated_batch.append(truncated) + info_batch.append(info) + return obs_batch, rew_batch, terminated_batch, truncated_batch, info_batch + + @override(VectorEnv) + def get_sub_environments(self): + return self.envs + + +class MockVectorEnv(VectorEnv): + """A custom vector env that uses a single(!) CartPole sub-env. + + However, this env pretends to be a vectorized one to illustrate how one + could create custom VectorEnvs w/o the need for actual vectorizations of + sub-envs under the hood. + """ + + def __init__(self, episode_length, mocked_num_envs): + self.env = gym.make("CartPole-v1") + super().__init__( + observation_space=self.env.observation_space, + action_space=self.env.action_space, + num_envs=mocked_num_envs, + ) + self.episode_len = episode_length + self.ts = 0 + + @override(VectorEnv) + def vector_reset(self, *, seeds=None, options=None): + # Since we only have one underlying sub-environment, just use the first seed + # and the first options dict (the user of this env thinks, there are + # `self.num_envs` sub-environments and sends that many seeds/options). + seeds = seeds or [None] + options = options or [None] + obs, infos = self.env.reset(seed=seeds[0], options=options[0]) + # Simply repeat the single obs/infos to pretend we really have + # `self.num_envs` sub-environments. + return ( + [obs for _ in range(self.num_envs)], + [infos for _ in range(self.num_envs)], + ) + + @override(VectorEnv) + def reset_at(self, index, *, seed=None, options=None): + self.ts = 0 + return self.env.reset(seed=seed, options=options) + + @override(VectorEnv) + def vector_step(self, actions): + self.ts += 1 + # Apply all actions sequentially to the same env. + # Whether this would make a lot of sense is debatable. + obs_batch, rew_batch, terminated_batch, truncated_batch, info_batch = ( + [], + [], + [], + [], + [], + ) + for i in range(self.num_envs): + obs, rew, terminated, truncated, info = self.env.step(actions[i]) + # Artificially truncate once time step limit has been reached. + # Note: Also terminate/truncate, when underlying CartPole is + # terminated/truncated. + if self.ts >= self.episode_len: + truncated = True + obs_batch.append(obs) + rew_batch.append(rew) + terminated_batch.append(terminated) + truncated_batch.append(truncated) + info_batch.append(info) + if terminated or truncated: + remaining = self.num_envs - (i + 1) + obs_batch.extend([obs for _ in range(remaining)]) + rew_batch.extend([rew for _ in range(remaining)]) + terminated_batch.extend([terminated for _ in range(remaining)]) + truncated_batch.extend([truncated for _ in range(remaining)]) + info_batch.extend([info for _ in range(remaining)]) + break + return obs_batch, rew_batch, terminated_batch, truncated_batch, info_batch + + @override(VectorEnv) + def get_sub_environments(self): + # You may also leave this method as-is, in which case, it would + # return an empty list. + return [self.env for _ in range(self.num_envs)] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7fb660ccd462981f7ace066fceacb8556f8a356 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__init__.py @@ -0,0 +1,35 @@ +from ray.rllib.env.multi_agent_env import make_multi_agent +from ray.rllib.examples.envs.classes.cartpole_with_dict_observation_space import ( + CartPoleWithDictObservationSpace, +) +from ray.rllib.examples.envs.classes.multi_agent.guess_the_number_game import ( + GuessTheNumberGame, +) +from ray.rllib.examples.envs.classes.multi_agent.two_step_game import ( + TwoStepGame, + TwoStepGameWithGroupedAgents, +) +from ray.rllib.examples.envs.classes.nested_space_repeat_after_me_env import ( + NestedSpaceRepeatAfterMeEnv, +) +from ray.rllib.examples.envs.classes.stateless_cartpole import StatelessCartPole + + +# Backward compatibility. +__all__ = [ + "GuessTheNumberGame", + "TwoStepGame", + "TwoStepGameWithGroupedAgents", +] + + +MultiAgentCartPole = make_multi_agent("CartPole-v1") +MultiAgentMountainCar = make_multi_agent("MountainCarContinuous-v0") +MultiAgentPendulum = make_multi_agent("Pendulum-v1") +MultiAgentStatelessCartPole = make_multi_agent(lambda config: StatelessCartPole(config)) +MultiAgentCartPoleWithDictObservationSpace = make_multi_agent( + lambda config: CartPoleWithDictObservationSpace(config) +) +MultiAgentNestedSpaceRepeatAfterMeEnv = make_multi_agent( + lambda config: NestedSpaceRepeatAfterMeEnv(config) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1328381f17541d81b9a5d6fb761a3ffd87da51b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/bandit_envs_discrete.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/bandit_envs_discrete.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4857f9e84d128153345b538d7ab8546291656cbc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/bandit_envs_discrete.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/bandit_envs_recommender_system.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/bandit_envs_recommender_system.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..169a43dfc3aa8e408ac4af2ad1c5b7d64a357c93 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/bandit_envs_recommender_system.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/double_row_corridor_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/double_row_corridor_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20166f648ff45f907e54d5340ba247a1eb369e98 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/double_row_corridor_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/guess_the_number_game.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/guess_the_number_game.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..311b8877fd6ad190d39206861ed604f40958425f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/guess_the_number_game.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/pettingzoo_chess.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/pettingzoo_chess.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8278473e9851d4186dbf72bee7303cb868a449dd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/pettingzoo_chess.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/pettingzoo_connect4.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/pettingzoo_connect4.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3aa6dc6762337d050d26f6c11bb23d40ac564cf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/pettingzoo_connect4.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/rock_paper_scissors.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/rock_paper_scissors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ac30ef1701bfe8ddf35b6a099c7e5657c9aa461 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/rock_paper_scissors.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/tic_tac_toe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/tic_tac_toe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0e1fca2996dd2d5624dee0c25b37ae11ad407d2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/tic_tac_toe.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/two_step_game.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/two_step_game.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80f26894584ebc539c8236d7e77a144ba202674e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/__pycache__/two_step_game.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/bandit_envs_discrete.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/bandit_envs_discrete.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ceb11ebfc39e1df470fa13d76d0f1c5058460a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/bandit_envs_discrete.py @@ -0,0 +1,206 @@ +import copy +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +import numpy as np +import random + + +class SimpleContextualBandit(gym.Env): + """Simple env w/ 2 states and 3 actions (arms): 0, 1, and 2. + + Episodes last only for one timestep, possible observations are: + [-1.0, 1.0] and [1.0, -1.0], where the first element is the "current context". + The highest reward (+10.0) is received for selecting arm 0 for context=1.0 + and arm 2 for context=-1.0. Action 1 always yields 0.0 reward. + """ + + def __init__(self, config=None): + self.action_space = Discrete(3) + self.observation_space = Box(low=-1.0, high=1.0, shape=(2,)) + self.cur_context = None + + def reset(self, *, seed=None, options=None): + self.cur_context = random.choice([-1.0, 1.0]) + return np.array([self.cur_context, -self.cur_context]), {} + + def step(self, action): + rewards_for_context = { + -1.0: [-10, 0, 10], + 1.0: [10, 0, -10], + } + reward = rewards_for_context[self.cur_context][action] + return ( + np.array([-self.cur_context, self.cur_context]), + reward, + True, + False, + {"regret": 10 - reward}, + ) + + +class LinearDiscreteEnv(gym.Env): + """Samples data from linearly parameterized arms. + + The reward for context X and arm i is given by X^T * theta_i, for some + latent set of parameters {theta_i : i = 1, ..., k}. + The thetas are sampled uniformly at random, the contexts are Gaussian, + and Gaussian noise is added to the rewards. + """ + + DEFAULT_CONFIG_LINEAR = { + "feature_dim": 8, + "num_actions": 4, + "reward_noise_std": 0.01, + } + + def __init__(self, config=None): + self.config = copy.copy(self.DEFAULT_CONFIG_LINEAR) + if config is not None and type(config) is dict: + self.config.update(config) + + self.feature_dim = self.config["feature_dim"] + self.num_actions = self.config["num_actions"] + self.sigma = self.config["reward_noise_std"] + + self.action_space = Discrete(self.num_actions) + self.observation_space = Box(low=-10, high=10, shape=(self.feature_dim,)) + + self.thetas = np.random.uniform(-1, 1, (self.num_actions, self.feature_dim)) + self.thetas /= np.linalg.norm(self.thetas, axis=1, keepdims=True) + + self._elapsed_steps = 0 + self._current_context = None + + def _sample_context(self): + return np.random.normal(scale=1 / 3, size=(self.feature_dim,)) + + def reset(self, *, seed=None, options=None): + self._current_context = self._sample_context() + return self._current_context, {} + + def step(self, action): + assert ( + self._elapsed_steps is not None + ), "Cannot call env.step() beforecalling reset()" + assert action < self.num_actions, "Invalid action." + + action = int(action) + context = self._current_context + rewards = self.thetas.dot(context) + + opt_action = rewards.argmax() + + regret = rewards.max() - rewards[action] + + # Add Gaussian noise + rewards += np.random.normal(scale=self.sigma, size=rewards.shape) + + reward = rewards[action] + self._current_context = self._sample_context() + return ( + self._current_context, + reward, + True, + False, + {"regret": regret, "opt_action": opt_action}, + ) + + def render(self, mode="human"): + raise NotImplementedError + + +class WheelBanditEnv(gym.Env): + """Wheel bandit environment for 2D contexts + (see https://arxiv.org/abs/1802.09127). + """ + + DEFAULT_CONFIG_WHEEL = { + "delta": 0.5, + "mu_1": 1.2, + "mu_2": 1, + "mu_3": 50, + "std": 0.01, + } + + feature_dim = 2 + num_actions = 5 + + def __init__(self, config=None): + self.config = copy.copy(self.DEFAULT_CONFIG_WHEEL) + if config is not None and type(config) is dict: + self.config.update(config) + + self.delta = self.config["delta"] + self.mu_1 = self.config["mu_1"] + self.mu_2 = self.config["mu_2"] + self.mu_3 = self.config["mu_3"] + self.std = self.config["std"] + + self.action_space = Discrete(self.num_actions) + self.observation_space = Box(low=-1, high=1, shape=(self.feature_dim,)) + + self.means = [self.mu_1] + 4 * [self.mu_2] + self._elapsed_steps = 0 + self._current_context = None + + def _sample_context(self): + while True: + state = np.random.uniform(-1, 1, self.feature_dim) + if np.linalg.norm(state) <= 1: + return state + + def reset(self, *, seed=None, options=None): + self._current_context = self._sample_context() + return self._current_context, {} + + def step(self, action): + assert ( + self._elapsed_steps is not None + ), "Cannot call env.step() before calling reset()" + + action = int(action) + self._elapsed_steps += 1 + rewards = [ + np.random.normal(self.means[j], self.std) for j in range(self.num_actions) + ] + context = self._current_context + r_big = np.random.normal(self.mu_3, self.std) + + if np.linalg.norm(context) >= self.delta: + if context[0] > 0: + if context[1] > 0: + # First quadrant + rewards[1] = r_big + opt_action = 1 + else: + # Fourth quadrant + rewards[4] = r_big + opt_action = 4 + else: + if context[1] > 0: + # Second quadrant + rewards[2] = r_big + opt_action = 2 + else: + # Third quadrant + rewards[3] = r_big + opt_action = 3 + else: + # Smaller region where action 0 is optimal + opt_action = 0 + + reward = rewards[action] + + regret = rewards[opt_action] - reward + + self._current_context = self._sample_context() + return ( + self._current_context, + reward, + True, + False, + {"regret": regret, "opt_action": opt_action}, + ) + + def render(self, mode="human"): + raise NotImplementedError diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/bandit_envs_recommender_system.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/bandit_envs_recommender_system.py new file mode 100644 index 0000000000000000000000000000000000000000..05a29082a0d3352d96dd7cbace9b46a88f24e225 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/bandit_envs_recommender_system.py @@ -0,0 +1,227 @@ +"""Examples for recommender system simulating envs ready to be used by RLlib Algorithms. + +This env follows RecSim obs and action APIs. +""" +import gymnasium as gym +import numpy as np +from typing import Optional + +from ray.rllib.utils.numpy import softmax + + +class ParametricRecSys(gym.Env): + """A recommendation environment which generates items with visible features + randomly (parametric actions). + The environment can be configured to be multi-user, i.e. different models + will be learned independently for each user, by setting num_users_in_db + parameter. + To enable slate recommendation, the `slate_size` config parameter can be + set as > 1. + """ + + def __init__( + self, + embedding_size: int = 20, + num_docs_to_select_from: int = 10, + slate_size: int = 1, + num_docs_in_db: Optional[int] = None, + num_users_in_db: Optional[int] = None, + user_time_budget: float = 60.0, + ): + """Initializes a ParametricRecSys instance. + + Args: + embedding_size: Embedding size for both users and docs. + Each value in the user/doc embeddings can have values between + -1.0 and 1.0. + num_docs_to_select_from: The number of documents to present to the + agent each timestep. The agent will then have to pick a slate + out of these. + slate_size: The size of the slate to recommend to the user at each + timestep. + num_docs_in_db: The total number of documents in the DB. Set this + to None, in case you would like to resample docs from an + infinite pool. + num_users_in_db: The total number of users in the DB. Set this to + None, in case you would like to resample users from an infinite + pool. + user_time_budget: The total time budget a user has throughout an + episode. Once this time budget is used up (through engagements + with clicked/selected documents), the episode ends. + """ + self.embedding_size = embedding_size + self.num_docs_to_select_from = num_docs_to_select_from + self.slate_size = slate_size + + self.num_docs_in_db = num_docs_in_db + self.docs_db = None + self.num_users_in_db = num_users_in_db + self.users_db = None + self.current_user = None + + self.user_time_budget = user_time_budget + self.current_user_budget = user_time_budget + + self.observation_space = gym.spaces.Dict( + { + # The D docs our agent sees at each timestep. + # It has to select a k-slate out of these. + "doc": gym.spaces.Dict( + { + str(i): gym.spaces.Box( + -1.0, 1.0, shape=(self.embedding_size,), dtype=np.float32 + ) + for i in range(self.num_docs_to_select_from) + } + ), + # The user engaging in this timestep/episode. + "user": gym.spaces.Box( + -1.0, 1.0, shape=(self.embedding_size,), dtype=np.float32 + ), + # For each item in the previous slate, was it clicked? + # If yes, how long was it being engaged with (e.g. watched)? + "response": gym.spaces.Tuple( + [ + gym.spaces.Dict( + { + # Clicked or not? + "click": gym.spaces.Discrete(2), + # Engagement time (how many minutes watched?). + "engagement": gym.spaces.Box( + 0.0, 100.0, shape=(), dtype=np.float32 + ), + } + ) + for _ in range(self.slate_size) + ] + ), + } + ) + # Our action space is + self.action_space = gym.spaces.MultiDiscrete( + [self.num_docs_to_select_from for _ in range(self.slate_size)] + ) + + def _get_embedding(self): + return np.random.uniform(-1, 1, size=(self.embedding_size,)).astype(np.float32) + + def reset(self, *, seed=None, options=None): + # Reset the current user's time budget. + self.current_user_budget = self.user_time_budget + + # Sample a user for the next episode/session. + # Pick from a only-once-sampled user DB. + if self.num_users_in_db is not None: + if self.users_db is None: + self.users_db = [ + self._get_embedding() for _ in range(self.num_users_in_db) + ] + self.current_user = self.users_db[np.random.choice(self.num_users_in_db)] + # Pick from an infinite pool of users. + else: + self.current_user = self._get_embedding() + + return self._get_obs(), {} + + def step(self, action): + # Action is the suggested slate (indices of the docs in the + # suggested ones). + + # We calculate scores as the dot product between document features and user + # features. The softmax ensures regret<1 further down. + scores = softmax( + [np.dot(self.current_user, doc) for doc in self.currently_suggested_docs] + ) + best_reward = np.max(scores) + + # User choice model: User picks a doc stochastically, + # where probs are dot products between user- and doc feature + # (categories) vectors (rewards). + # There is also a no-click doc whose weight is 0.0. + user_doc_overlaps = np.array([scores[a] for a in action] + [0.0]) + # We have to softmax again so that probabilities add up to 1 + probabilities = softmax(user_doc_overlaps) + which_clicked = np.random.choice( + np.arange(self.slate_size + 1), p=probabilities + ) + + reward = 0.0 + if which_clicked < self.slate_size: + # Reward is 1.0 - regret if clicked. 0.0 if not clicked. + regret = best_reward - user_doc_overlaps[which_clicked] + # The reward also represents the user engagement that we define to be + # withing the range [0...100]. + reward = (1 - regret) * 100 + # If anything clicked, deduct from the current user's time budget. + self.current_user_budget -= 1.0 + done = truncated = self.current_user_budget <= 0.0 + + # Compile response. + response = tuple( + { + "click": int(idx == which_clicked), + "engagement": reward if idx == which_clicked else 0.0, + } + for idx in range(len(user_doc_overlaps) - 1) + ) + + return self._get_obs(response=response), reward, done, truncated, {} + + def _get_obs(self, response=None): + # Sample D docs from infinity or our pre-existing docs. + # Pick from a only-once-sampled docs DB. + if self.num_docs_in_db is not None: + if self.docs_db is None: + self.docs_db = [ + self._get_embedding() for _ in range(self.num_docs_in_db) + ] + self.currently_suggested_docs = [ + self.docs_db[doc_idx].astype(np.float32) + for doc_idx in np.random.choice( + self.num_docs_in_db, + size=(self.num_docs_to_select_from,), + replace=False, + ) + ] + # Pick from an infinite pool of docs. + else: + self.currently_suggested_docs = [ + self._get_embedding() for _ in range(self.num_docs_to_select_from) + ] + + doc = {str(i): d for i, d in enumerate(self.currently_suggested_docs)} + + if not response: + response = self.observation_space["response"].sample() + + return { + "user": self.current_user.astype(np.float32), + "doc": doc, + "response": response, + } + + +if __name__ == "__main__": + """Test RecommSys env with random actions for baseline performance.""" + env = ParametricRecSys( + num_docs_in_db=100, + num_users_in_db=1, + ) + obs, info = env.reset() + num_episodes = 0 + episode_rewards = [] + episode_reward = 0.0 + + while num_episodes < 100: + action = env.action_space.sample() + obs, reward, done, truncated, _ = env.step(action) + + episode_reward += reward + if done: + print(f"episode reward = {episode_reward}") + env.reset() + num_episodes += 1 + episode_rewards.append(episode_reward) + episode_reward = 0.0 + + print(f"Avg reward={np.mean(episode_rewards)}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/double_row_corridor_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/double_row_corridor_env.py new file mode 100644 index 0000000000000000000000000000000000000000..b489eab2f0c029cfc3b49663fae7bd0cfc015973 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/double_row_corridor_env.py @@ -0,0 +1,146 @@ +import gymnasium as gym +import numpy as np + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import AgentID + + +class DoubleRowCorridorEnv(MultiAgentEnv): + """A MultiAgentEnv with a single, global observation space for all agents. + + There are two agents in this grid-world-style environment, `agent_0` and `agent_1`. + The grid has two-rows and multiple columns and agents must, each + separately, reach their individual goal position to receive a final reward of +10: + + +---------------+ + |0 | + | 1| + +---------------+ + Legend: + 0 = agent_0 + goal state for agent_1 + 1 = agent_1 + goal state for agent_0 + + You can change the length of the grid through providing the "length" key in the + `config` dict passed to the env's constructor. + + The action space for both agents is Discrete(4), which encodes to moving up, down, + left, or right in the grid. + + If the two agents collide, meaning they end up in the exact same field after both + taking their actions at any timestep, an additional reward of +5 is given to both + agents. Thus, optimal policies aim at seeking the respective other agent first, and + only then proceeding to their agent's goal position. + + Each agent in the env has an observation space of a 2-tuple containing its own + x/y-position, where x is the row index, being either 0 (1st row) or 1 (2nd row), + and y is the column index (starting from 0). + """ + + def __init__(self, config=None): + super().__init__() + + config = config or {} + + self.length = config.get("length", 15) + self.terminateds = {} + self.collided = False + + # Provide information about agents and possible agents. + self.agents = self.possible_agents = ["agent_0", "agent_1"] + self.terminateds = {} + + # Observations: x/y, where the first number is the row index, the second number + # is the column index, for both agents. + # For example: [0.0, 2.0] means the agent is in row 0 and column 2. + self._obs_spaces = gym.spaces.Box( + 0.0, self.length - 1, shape=(2,), dtype=np.int32 + ) + self._act_spaces = gym.spaces.Discrete(4) + + @override(MultiAgentEnv) + def reset(self, *, seed=None, options=None): + self.agent_pos = { + "agent_0": [0, 0], + "agent_1": [1, self.length - 1], + } + self.goals = { + "agent_0": [0, self.length - 1], + "agent_1": [1, 0], + } + self.terminateds = {agent_id: False for agent_id in self.agent_pos} + self.collided = False + + return self._get_obs(), {} + + @override(MultiAgentEnv) + def step(self, action_dict): + rewards = { + agent_id: -0.1 + for agent_id in self.agent_pos + if not self.terminateds[agent_id] + } + + for agent_id, action in action_dict.items(): + row, col = self.agent_pos[agent_id] + + # up + if action == 0 and row > 0: + row -= 1 + # down + elif action == 1 and row < 1: + row += 1 + # left + elif action == 2 and col > 0: + col -= 1 + # right + elif action == 3 and col < self.length - 1: + col += 1 + + # Update positions. + self.agent_pos[agent_id] = [row, col] + + obs = self._get_obs() + + # Check for collision (only if both agents are still active). + if ( + not any(self.terminateds.values()) + and self.agent_pos["agent_0"] == self.agent_pos["agent_1"] + ): + if not self.collided: + rewards["agent_0"] += 5 + rewards["agent_1"] += 5 + self.collided = True + + # Check goals. + for agent_id in self.agent_pos: + if ( + self.agent_pos[agent_id] == self.goals[agent_id] + and not self.terminateds[agent_id] + ): + rewards[agent_id] += 10 + self.terminateds[agent_id] = True + + terminateds = { + agent_id: self.terminateds[agent_id] for agent_id in self.agent_pos + } + terminateds["__all__"] = all(self.terminateds.values()) + + return obs, rewards, terminateds, {}, {} + + @override(MultiAgentEnv) + def get_observation_space(self, agent_id: AgentID) -> gym.Space: + return self._obs_spaces + + @override(MultiAgentEnv) + def get_action_space(self, agent_id: AgentID) -> gym.Space: + return self._act_spaces + + def _get_obs(self): + obs = {} + pos = self.agent_pos + for agent_id in self.agent_pos: + if self.terminateds[agent_id]: + continue + obs[agent_id] = np.array(pos[agent_id], dtype=np.int32) + return obs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/guess_the_number_game.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/guess_the_number_game.py new file mode 100644 index 0000000000000000000000000000000000000000..eaac3e4becc55e06efa0d618fa8b5df032be07cd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/guess_the_number_game.py @@ -0,0 +1,89 @@ +import gymnasium as gym + +from ray.rllib.env.multi_agent_env import MultiAgentEnv + + +class GuessTheNumberGame(MultiAgentEnv): + """ + We have two players, 0 and 1. Agent 0 has to pick a number between 0, MAX-1 + at reset. Agent 1 has to guess the number by asking N questions of whether + of the form of "a is higher|lower|equal to the picked number. The + action space is MultiDiscrete [3, MAX]. For the first index 0 means lower, + 1 means higher and 2 means equal. The environment answers with yes (1) or + no (0) on the reward function. Every time step that agent 1 wastes agent 0 + gets a reward of 1. After N steps the game is terminated. If agent 1 + guesses the number correctly, it gets a reward of 100 points, otherwise it + gets a reward of 0. On the other hand if agent 0 wins they win 100 points. + The optimal policy controlling agent 1 should converge to a binary search + strategy. + """ + + MAX_NUMBER = 3 + MAX_STEPS = 20 + + def __init__(self, config=None): + super().__init__() + self._agent_ids = {0, 1} + + self.max_number = config.get("max_number", self.MAX_NUMBER) + self.max_steps = config.get("max_steps", self.MAX_STEPS) + + self._number = None + self.observation_space = gym.spaces.Discrete(2) + self.action_space = gym.spaces.MultiDiscrete([3, self.max_number]) + + def reset(self, *, seed=None, options=None): + self._step = 0 + self._number = None + # agent 0 has to pick a number. So the returned obs does not matter. + return {0: 0}, {} + + def step(self, action_dict): + # get agent 0's action + agent_0_action = action_dict.get(0) + + if agent_0_action is not None: + # ignore the first part of the action and look at the number + self._number = agent_0_action[1] + # next obs should tell agent 1 to start guessing. + # the returned reward and dones should be on agent 0 who picked a + # number. + return ( + {1: 0}, + {0: 0}, + {0: False, "__all__": False}, + {0: False, "__all__": False}, + {}, + ) + + if self._number is None: + raise ValueError( + "No number is selected by agent 0. Have you restarted " + "the environment?" + ) + + # get agent 1's action + direction, number = action_dict.get(1) + info = {} + # always the same, we don't need agent 0 to act ever again, agent 1 should keep + # guessing. + obs = {1: 0} + guessed_correctly = False + terminated = {1: False, "__all__": False} + truncated = {1: False, "__all__": False} + # everytime agent 1 does not guess correctly agent 0 gets a reward of 1. + if direction == 0: # lower + reward = {1: int(number > self._number), 0: 1} + elif direction == 1: # higher + reward = {1: int(number < self._number), 0: 1} + else: # equal + guessed_correctly = number == self._number + reward = {1: guessed_correctly * 100, 0: guessed_correctly * -100} + terminated = {1: guessed_correctly, "__all__": guessed_correctly} + + self._step += 1 + if self._step >= self.max_steps: # max number of steps episode is over + truncated["__all__"] = True + if not guessed_correctly: + reward[0] = 100 # agent 0 wins + return obs, reward, terminated, truncated, info diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/pettingzoo_chess.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/pettingzoo_chess.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba87488d29fc59eba16473ea218209659ddf7b3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/pettingzoo_chess.py @@ -0,0 +1,234 @@ +from pettingzoo import AECEnv +from pettingzoo.classic.chess.chess import raw_env as chess_v5 +import copy +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from typing import Dict, Any +import chess as ch +import numpy as np + + +class MultiAgentChess(MultiAgentEnv): + """An interface to the PettingZoo MARL environment library. + See: https://github.com/Farama-Foundation/PettingZoo + Inherits from MultiAgentEnv and exposes a given AEC + (actor-environment-cycle) game from the PettingZoo project via the + MultiAgentEnv public API. + Note that the wrapper has some important limitations: + 1. All agents have the same action_spaces and observation_spaces. + Note: If, within your aec game, agents do not have homogeneous action / + observation spaces, apply SuperSuit wrappers + to apply padding functionality: https://github.com/Farama-Foundation/ + SuperSuit#built-in-multi-agent-only-functions + 2. Environments are positive sum games (-> Agents are expected to cooperate + to maximize reward). This isn't a hard restriction, it just that + standard algorithms aren't expected to work well in highly competitive + games. + + .. testcode:: + :skipif: True + + from pettingzoo.butterfly import prison_v3 + from ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnv + env = PettingZooEnv(prison_v3.env()) + obs = env.reset() + print(obs) + # only returns the observation for the agent which should be stepping + + .. testoutput:: + + { + 'prisoner_0': array([[[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + ..., + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]], dtype=uint8) + } + + .. testcode:: + :skipif: True + + obs, rewards, dones, infos = env.step({ + "prisoner_0": 1 + }) + # only returns the observation, reward, info, etc, for + # the agent who's turn is next. + print(obs) + + .. testoutput:: + + { + 'prisoner_1': array([[[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + ..., + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]], dtype=uint8) + } + + .. testcode:: + :skipif: True + + print(rewards) + + .. testoutput:: + + { + 'prisoner_1': 0 + } + + .. testcode:: + :skipif: True + + print(dones) + + .. testoutput:: + + { + 'prisoner_1': False, '__all__': False + } + + .. testcode:: + :skipif: True + + print(infos) + + .. testoutput:: + + { + 'prisoner_1': {'map_tuple': (1, 0)} + } + """ + + def __init__( + self, + config: Dict[Any, Any] = None, + env: AECEnv = None, + ): + super().__init__() + if env is None: + self.env = chess_v5() + else: + self.env = env + self.env.reset() + + self.config = config + if self.config is None: + self.config = {} + try: + self.config["random_start"] = self.config["random_start"] + except KeyError: + self.config["random_start"] = 4 + + # If these important attributes are not set, try to infer them. + if not self.agents: + self.agents = list(self._agent_ids) + if not self.possible_agents: + self.possible_agents = self.agents.copy() + + # Get first observation space, assuming all agents have equal space + self.observation_space = self.env.observation_space(self.env.agents[0]) + + # Get first action space, assuming all agents have equal space + self.action_space = self.env.action_space(self.env.agents[0]) + + assert all( + self.env.observation_space(agent) == self.observation_space + for agent in self.env.agents + ), ( + "Observation spaces for all agents must be identical. Perhaps " + "SuperSuit's pad_observations wrapper can help (useage: " + "`supersuit.aec_wrappers.pad_observations(env)`" + ) + + assert all( + self.env.action_space(agent) == self.action_space + for agent in self.env.agents + ), ( + "Action spaces for all agents must be identical. Perhaps " + "SuperSuit's pad_action_space wrapper can help (usage: " + "`supersuit.aec_wrappers.pad_action_space(env)`" + ) + self._agent_ids = set(self.env.agents) + + def random_start(self, random_moves): + self.env.board = ch.Board() + for i in range(random_moves): + self.env.board.push(np.random.choice(list(self.env.board.legal_moves))) + return self.env.board + + def observe(self): + return { + self.env.agent_selection: self.env.observe(self.env.agent_selection), + "state": self.get_state(), + } + + def reset(self, *args, **kwargs): + self.env.reset() + if self.config["random_start"] > 0: + self.random_start(self.config["random_start"]) + return ( + {self.env.agent_selection: self.env.observe(self.env.agent_selection)}, + {self.env.agent_selection: {}}, + ) + + def step(self, action): + try: + self.env.step(action[self.env.agent_selection]) + except (KeyError, IndexError): + self.env.step(action) + except AssertionError: + # Illegal action + print(action) + raise AssertionError("Illegal action") + + obs_d = {} + rew_d = {} + done_d = {} + truncated_d = {} + info_d = {} + while self.env.agents: + obs, rew, done, trunc, info = self.env.last() + a = self.env.agent_selection + obs_d[a] = obs + rew_d[a] = rew + done_d[a] = done + truncated_d[a] = trunc + info_d[a] = info + if self.env.terminations[self.env.agent_selection]: + self.env.step(None) + done_d["__all__"] = True + truncated_d["__all__"] = True + else: + done_d["__all__"] = False + truncated_d["__all__"] = False + break + + return obs_d, rew_d, done_d, truncated_d, info_d + + def close(self): + self.env.close() + + def seed(self, seed=None): + self.env.seed(seed) + + def render(self, mode="human"): + return self.env.render(mode) + + @property + def agent_selection(self): + return self.env.agent_selection + + @property + def get_sub_environments(self): + return self.env.unwrapped + + def get_state(self): + state = copy.deepcopy(self.env) + return state + + def set_state(self, state): + self.env = copy.deepcopy(state) + return self.env.observe(self.env.agent_selection) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/pettingzoo_connect4.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/pettingzoo_connect4.py new file mode 100644 index 0000000000000000000000000000000000000000..7be070d101cdae297ee97618e5c1eb469d3058a2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/pettingzoo_connect4.py @@ -0,0 +1,220 @@ +import copy +from typing import Dict, Any + +from pettingzoo import AECEnv +from pettingzoo.classic.connect_four_v3 import raw_env as connect_four_v3 + +from ray.rllib.env.multi_agent_env import MultiAgentEnv + + +class MultiAgentConnect4(MultiAgentEnv): + """An interface to the PettingZoo MARL environment library. + See: https://github.com/Farama-Foundation/PettingZoo + Inherits from MultiAgentEnv and exposes a given AEC + (actor-environment-cycle) game from the PettingZoo project via the + MultiAgentEnv public API. + Note that the wrapper has some important limitations: + 1. All agents have the same action_spaces and observation_spaces. + Note: If, within your aec game, agents do not have homogeneous action / + observation spaces, apply SuperSuit wrappers + to apply padding functionality: https://github.com/Farama-Foundation/ + SuperSuit#built-in-multi-agent-only-functions + 2. Environments are positive sum games (-> Agents are expected to cooperate + to maximize reward). This isn't a hard restriction, it just that + standard algorithms aren't expected to work well in highly competitive + games. + + .. testcode:: + :skipif: True + + from pettingzoo.butterfly import prison_v3 + from ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnv + env = PettingZooEnv(prison_v3.env()) + obs = env.reset() + print(obs) + + .. testoutput:: + + # only returns the observation for the agent which should be stepping + { + 'prisoner_0': array([[[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + ..., + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]], dtype=uint8) + } + + .. testcode:: + :skipif: True + + obs, rewards, dones, infos = env.step({ + "prisoner_0": 1 + }) + # only returns the observation, reward, info, etc, for + # the agent who's turn is next. + print(obs) + + .. testoutput:: + + { + 'prisoner_1': array([[[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + ..., + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]], dtype=uint8) + } + + .. testcode:: + :skipif: True + + print(rewards) + + .. testoutput:: + + { + 'prisoner_1': 0 + } + + .. testcode:: + :skipif: True + + print(dones) + + .. testoutput:: + + { + 'prisoner_1': False, '__all__': False + } + + .. testcode:: + :skipif: True + + print(infos) + + .. testoutput:: + + { + 'prisoner_1': {'map_tuple': (1, 0)} + } + """ + + def __init__( + self, + config: Dict[Any, Any] = None, + env: AECEnv = None, + ): + super().__init__() + if env is None: + self.env = connect_four_v3() + else: + self.env = env + self.env.reset() + + # If these important attributes are not set, try to infer them. + if not self.agents: + self.agents = list(self._agent_ids) + if not self.possible_agents: + self.possible_agents = self.agents.copy() + + self.config = config + # Get first observation space, assuming all agents have equal space + self.observation_space = self.env.observation_space(self.env.agents[0]) + + # Get first action space, assuming all agents have equal space + self.action_space = self.env.action_space(self.env.agents[0]) + + assert all( + self.env.observation_space(agent) == self.observation_space + for agent in self.env.agents + ), ( + "Observation spaces for all agents must be identical. Perhaps " + "SuperSuit's pad_observations wrapper can help (useage: " + "`supersuit.aec_wrappers.pad_observations(env)`" + ) + + assert all( + self.env.action_space(agent) == self.action_space + for agent in self.env.agents + ), ( + "Action spaces for all agents must be identical. Perhaps " + "SuperSuit's pad_action_space wrapper can help (usage: " + "`supersuit.aec_wrappers.pad_action_space(env)`" + ) + + self._agent_ids = set(self.env.agents) + + def observe(self): + return { + self.env.agent_selection: self.env.observe(self.env.agent_selection), + "state": self.get_state(), + } + + def reset(self, *args, **kwargs): + self.env.reset() + return ( + {self.env.agent_selection: self.env.observe(self.env.agent_selection)}, + {self.env.agent_selection: {}}, + ) + + def step(self, action): + try: + self.env.step(action[self.env.agent_selection]) + except (KeyError, IndexError): + self.env.step(action) + except AssertionError: + # Illegal action + print(action) + raise AssertionError("Illegal action") + + obs_d = {} + rew_d = {} + done_d = {} + trunc_d = {} + info_d = {} + while self.env.agents: + obs, rew, done, trunc, info = self.env.last() + a = self.env.agent_selection + obs_d[a] = obs + rew_d[a] = rew + done_d[a] = done + trunc_d[a] = trunc + info_d[a] = info + if self.env.terminations[self.env.agent_selection]: + self.env.step(None) + done_d["__all__"] = True + trunc_d["__all__"] = True + else: + done_d["__all__"] = False + trunc_d["__all__"] = False + break + + return obs_d, rew_d, done_d, trunc_d, info_d + + def close(self): + self.env.close() + + def seed(self, seed=None): + self.env.seed(seed) + + def render(self, mode="human"): + return self.env.render(mode) + + @property + def agent_selection(self): + return self.env.agent_selection + + @property + def get_sub_environments(self): + return self.env.unwrapped + + def get_state(self): + state = copy.deepcopy(self.env) + return state + + def set_state(self, state): + self.env = copy.deepcopy(state) + return self.env.observe(self.env.agent_selection) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/rock_paper_scissors.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/rock_paper_scissors.py new file mode 100644 index 0000000000000000000000000000000000000000..aa363ae75f2bd79dcd3f97a888f9bb7f33c43771 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/rock_paper_scissors.py @@ -0,0 +1,125 @@ +# __sphinx_doc_1_begin__ +import gymnasium as gym + +from ray.rllib.env.multi_agent_env import MultiAgentEnv + + +class RockPaperScissors(MultiAgentEnv): + """Two-player environment for the famous rock paper scissors game. + + # __sphinx_doc_1_end__ + Optionally, the "Sheldon Cooper extension" can be activated by passing + `sheldon_cooper_mode=True` into the constructor, in which case two more moves + are allowed: Spock and Lizard. Spock is poisoned by Lizard, disproven by Paper, but + crushes Rock and smashes Scissors. Lizard poisons Spock and eats Paper, but is + decapitated by Scissors and crushed by Rock. + + # __sphinx_doc_2_begin__ + Both players always move simultaneously over a course of 10 timesteps in total. + The winner of each timestep receives reward of +1, the losing player -1.0. + + The observation of each player is the last opponent action. + """ + + ROCK = 0 + PAPER = 1 + SCISSORS = 2 + LIZARD = 3 + SPOCK = 4 + + WIN_MATRIX = { + (ROCK, ROCK): (0, 0), + (ROCK, PAPER): (-1, 1), + (ROCK, SCISSORS): (1, -1), + (PAPER, ROCK): (1, -1), + (PAPER, PAPER): (0, 0), + (PAPER, SCISSORS): (-1, 1), + (SCISSORS, ROCK): (-1, 1), + (SCISSORS, PAPER): (1, -1), + (SCISSORS, SCISSORS): (0, 0), + } + # __sphinx_doc_2_end__ + + WIN_MATRIX.update( + { + # Sheldon Cooper mode: + (LIZARD, LIZARD): (0, 0), + (LIZARD, SPOCK): (1, -1), # Lizard poisons Spock + (LIZARD, ROCK): (-1, 1), # Rock crushes lizard + (LIZARD, PAPER): (1, -1), # Lizard eats paper + (LIZARD, SCISSORS): (-1, 1), # Scissors decapitate lizard + (ROCK, LIZARD): (1, -1), # Rock crushes lizard + (PAPER, LIZARD): (-1, 1), # Lizard eats paper + (SCISSORS, LIZARD): (1, -1), # Scissors decapitate lizard + (SPOCK, SPOCK): (0, 0), + (SPOCK, LIZARD): (-1, 1), # Lizard poisons Spock + (SPOCK, ROCK): (1, -1), # Spock vaporizes rock + (SPOCK, PAPER): (-1, 1), # Paper disproves Spock + (SPOCK, SCISSORS): (1, -1), # Spock smashes scissors + (ROCK, SPOCK): (-1, 1), # Spock vaporizes rock + (PAPER, SPOCK): (1, -1), # Paper disproves Spock + (SCISSORS, SPOCK): (-1, 1), # Spock smashes scissors + } + ) + + # __sphinx_doc_3_begin__ + def __init__(self, config=None): + super().__init__() + + self.agents = self.possible_agents = ["player1", "player2"] + + # The observations are always the last taken actions. Hence observation- and + # action spaces are identical. + self.observation_spaces = self.action_spaces = { + "player1": gym.spaces.Discrete(3), + "player2": gym.spaces.Discrete(3), + } + self.last_move = None + self.num_moves = 0 + # __sphinx_doc_3_end__ + + self.sheldon_cooper_mode = False + if config.get("sheldon_cooper_mode"): + self.sheldon_cooper_mode = True + self.action_spaces = self.observation_spaces = { + "player1": gym.spaces.Discrete(5), + "player2": gym.spaces.Discrete(5), + } + + # __sphinx_doc_4_begin__ + def reset(self, *, seed=None, options=None): + self.num_moves = 0 + + # The first observation should not matter (none of the agents has moved yet). + # Set them to 0. + return { + "player1": 0, + "player2": 0, + }, {} # <- empty infos dict + + # __sphinx_doc_4_end__ + + # __sphinx_doc_5_begin__ + def step(self, action_dict): + self.num_moves += 1 + + move1 = action_dict["player1"] + move2 = action_dict["player2"] + + # Set the next observations (simply use the other player's action). + # Note that because we are publishing both players in the observations dict, + # we expect both players to act in the next `step()` (simultaneous stepping). + observations = {"player1": move2, "player2": move1} + + # Compute rewards for each player based on the win-matrix. + r1, r2 = self.WIN_MATRIX[move1, move2] + rewards = {"player1": r1, "player2": r2} + + # Terminate the entire episode (for all agents) once 10 moves have been made. + terminateds = {"__all__": self.num_moves >= 10} + + # Leave truncateds and infos empty. + return observations, rewards, terminateds, {}, {} + + +# __sphinx_doc_5_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/tic_tac_toe.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/tic_tac_toe.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb08422092fdd7f19ab7e63d74f03f1615967a8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/tic_tac_toe.py @@ -0,0 +1,144 @@ +# __sphinx_doc_1_begin__ +import gymnasium as gym +import numpy as np + +from ray.rllib.env.multi_agent_env import MultiAgentEnv + + +class TicTacToe(MultiAgentEnv): + """A two-player game in which any player tries to complete one row in a 3x3 field. + + The observation space is Box(0.0, 1.0, (9,)), where each index represents a distinct + field on a 3x3 board and values of 0.0 mean the field is empty, -1.0 means + the opponend owns the field, and 1.0 means we occupy the field: + ---------- + | 0| 1| 2| + ---------- + | 3| 4| 5| + ---------- + | 6| 7| 8| + ---------- + + The action space is Discrete(9) and actions landing on an already occupied field + are simply ignored (and thus useless to the player taking these actions). + + Once a player completes a row, they receive +1.0 reward, the losing player receives + -1.0 reward. In all other cases, both players receive 0.0 reward. + """ + + # __sphinx_doc_1_end__ + + # __sphinx_doc_2_begin__ + def __init__(self, config=None): + super().__init__() + + # Define the agents in the game. + self.agents = self.possible_agents = ["player1", "player2"] + + # Each agent observes a 9D tensor, representing the 3x3 fields of the board. + # A 0 means an empty field, a 1 represents a piece of player 1, a -1 a piece of + # player 2. + self.observation_spaces = { + "player1": gym.spaces.Box(-1.0, 1.0, (9,), np.float32), + "player2": gym.spaces.Box(-1.0, 1.0, (9,), np.float32), + } + # Each player has 9 actions, encoding the 9 fields each player can place a piece + # on during their turn. + self.action_spaces = { + "player1": gym.spaces.Discrete(9), + "player2": gym.spaces.Discrete(9), + } + + self.board = None + self.current_player = None + + # __sphinx_doc_2_end__ + + # __sphinx_doc_3_begin__ + def reset(self, *, seed=None, options=None): + self.board = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + # Pick a random player to start the game. + self.current_player = np.random.choice(["player1", "player2"]) + # Return observations dict (only with the starting player, which is the one + # we expect to act next). + return { + self.current_player: np.array(self.board, np.float32), + }, {} + + # __sphinx_doc_3_end__ + + # __sphinx_doc_4_begin__ + def step(self, action_dict): + action = action_dict[self.current_player] + + # Create a rewards-dict (containing the rewards of the agent that just acted). + rewards = {self.current_player: 0.0} + # Create a terminateds-dict with the special `__all__` agent ID, indicating that + # if True, the episode ends for all agents. + terminateds = {"__all__": False} + + opponent = "player1" if self.current_player == "player2" else "player2" + + # Penalize trying to place a piece on an already occupied field. + if self.board[action] != 0: + rewards[self.current_player] -= 5.0 + # Change the board according to the (valid) action taken. + else: + self.board[action] = 1 if self.current_player == "player1" else -1 + + # After having placed a new piece, figure out whether the current player + # won or not. + if self.current_player == "player1": + win_val = [1, 1, 1] + else: + win_val = [-1, -1, -1] + if ( + # Horizontal win. + self.board[:3] == win_val + or self.board[3:6] == win_val + or self.board[6:] == win_val + # Vertical win. + or self.board[0:7:3] == win_val + or self.board[1:8:3] == win_val + or self.board[2:9:3] == win_val + # Diagonal win. + or self.board[::3] == win_val + or self.board[2:7:2] == win_val + ): + # Final reward is +5 for victory and -5 for a loss. + rewards[self.current_player] += 5.0 + rewards[opponent] = -5.0 + + # Episode is done and needs to be reset for a new game. + terminateds["__all__"] = True + + # The board might also be full w/o any player having won/lost. + # In this case, we simply end the episode and none of the players receives + # +1 or -1 reward. + elif 0 not in self.board: + terminateds["__all__"] = True + + # Flip players and return an observations dict with only the next player to + # make a move in it. + self.current_player = opponent + + return ( + {self.current_player: np.array(self.board, np.float32)}, + rewards, + terminateds, + {}, + {}, + ) + + +# __sphinx_doc_4_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/two_step_game.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/two_step_game.py new file mode 100644 index 0000000000000000000000000000000000000000..fb198056f7b71d1c86e5ce94a81b279b6abcc60b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/multi_agent/two_step_game.py @@ -0,0 +1,125 @@ +from gymnasium.spaces import Dict, Discrete, MultiDiscrete, Tuple +import numpy as np + +from ray.rllib.env.multi_agent_env import MultiAgentEnv, ENV_STATE + + +class TwoStepGame(MultiAgentEnv): + action_space = Discrete(2) + + def __init__(self, env_config): + super().__init__() + self.action_space = Discrete(2) + self.state = None + self.agent_1 = 0 + self.agent_2 = 1 + # MADDPG emits action logits instead of actual discrete actions + self.actions_are_logits = env_config.get("actions_are_logits", False) + self.one_hot_state_encoding = env_config.get("one_hot_state_encoding", False) + self.with_state = env_config.get("separate_state_space", False) + self._agent_ids = {0, 1} + if not self.one_hot_state_encoding: + self.observation_space = Discrete(6) + self.with_state = False + else: + # Each agent gets the full state (one-hot encoding of which of the + # three states are active) as input with the receiving agent's + # ID (1 or 2) concatenated onto the end. + if self.with_state: + self.observation_space = Dict( + { + "obs": MultiDiscrete([2, 2, 2, 3]), + ENV_STATE: MultiDiscrete([2, 2, 2]), + } + ) + else: + self.observation_space = MultiDiscrete([2, 2, 2, 3]) + + def reset(self, *, seed=None, options=None): + if seed is not None: + np.random.seed(seed) + self.state = np.array([1, 0, 0]) + return self._obs(), {} + + def step(self, action_dict): + if self.actions_are_logits: + action_dict = { + k: np.random.choice([0, 1], p=v) for k, v in action_dict.items() + } + + state_index = np.flatnonzero(self.state) + if state_index == 0: + action = action_dict[self.agent_1] + assert action in [0, 1], action + if action == 0: + self.state = np.array([0, 1, 0]) + else: + self.state = np.array([0, 0, 1]) + global_rew = 0 + terminated = False + elif state_index == 1: + global_rew = 7 + terminated = True + else: + if action_dict[self.agent_1] == 0 and action_dict[self.agent_2] == 0: + global_rew = 0 + elif action_dict[self.agent_1] == 1 and action_dict[self.agent_2] == 1: + global_rew = 8 + else: + global_rew = 1 + terminated = True + + rewards = {self.agent_1: global_rew / 2.0, self.agent_2: global_rew / 2.0} + obs = self._obs() + terminateds = {"__all__": terminated} + truncateds = {"__all__": False} + infos = { + self.agent_1: {"done": terminateds["__all__"]}, + self.agent_2: {"done": terminateds["__all__"]}, + } + return obs, rewards, terminateds, truncateds, infos + + def _obs(self): + if self.with_state: + return { + self.agent_1: {"obs": self.agent_1_obs(), ENV_STATE: self.state}, + self.agent_2: {"obs": self.agent_2_obs(), ENV_STATE: self.state}, + } + else: + return {self.agent_1: self.agent_1_obs(), self.agent_2: self.agent_2_obs()} + + def agent_1_obs(self): + if self.one_hot_state_encoding: + return np.concatenate([self.state, [1]]) + else: + return np.flatnonzero(self.state)[0] + + def agent_2_obs(self): + if self.one_hot_state_encoding: + return np.concatenate([self.state, [2]]) + else: + return np.flatnonzero(self.state)[0] + 3 + + +class TwoStepGameWithGroupedAgents(MultiAgentEnv): + def __init__(self, env_config): + self._agent_ids = {"agents"} + + super().__init__() + env = TwoStepGame(env_config) + tuple_obs_space = Tuple([env.observation_space, env.observation_space]) + tuple_act_space = Tuple([env.action_space, env.action_space]) + + self.env = env.with_agent_groups( + groups={"agents": [0, 1]}, + obs_space=tuple_obs_space, + act_space=tuple_act_space, + ) + self.observation_space = Dict({"agents": self.env.observation_space}) + self.action_space = Dict({"agents": self.env.action_space}) + + def reset(self, *, seed=None, options=None): + return self.env.reset(seed=seed, options=options) + + def step(self, actions): + return self.env.step(actions) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/nested_space_repeat_after_me_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/nested_space_repeat_after_me_env.py new file mode 100644 index 0000000000000000000000000000000000000000..233f72f3610d629f905da1b8819b82065dc43296 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/nested_space_repeat_after_me_env.py @@ -0,0 +1,50 @@ +import gymnasium as gym +from gymnasium.spaces import Box, Dict, Discrete, Tuple +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.utils.spaces.space_utils import flatten_space + + +class NestedSpaceRepeatAfterMeEnv(gym.Env): + """Env for which policy has to repeat the (possibly complex) observation. + + The action space and observation spaces are always the same and may be + arbitrarily nested Dict/Tuple Spaces. + Rewards are given for exactly matching Discrete sub-actions and for being + as close as possible for Box sub-actions. + """ + + def __init__(self, config=None): + config = config or {} + self.observation_space = config.get( + "space", Tuple([Discrete(2), Dict({"a": Box(-1.0, 1.0, (2,))})]) + ) + self.action_space = self.observation_space + self.flattened_action_space = flatten_space(self.action_space) + self.episode_len = config.get("episode_len", 100) + + def reset(self, *, seed=None, options=None): + self.steps = 0 + return self._next_obs(), {} + + def step(self, action): + self.steps += 1 + action = tree.flatten(action) + reward = 0.0 + for a, o, space in zip( + action, self.current_obs_flattened, self.flattened_action_space + ): + # Box: -abs(diff). + if isinstance(space, gym.spaces.Box): + reward -= np.sum(np.abs(a - o)) + # Discrete: +1.0 if exact match. + if isinstance(space, gym.spaces.Discrete): + reward += 1.0 if a == o else 0.0 + truncated = self.steps >= self.episode_len + return self._next_obs(), reward, False, truncated, {} + + def _next_obs(self): + self.current_obs = self.observation_space.sample() + self.current_obs_flattened = tree.flatten(self.current_obs) + return self.current_obs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/parametric_actions_cartpole.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/parametric_actions_cartpole.py new file mode 100644 index 0000000000000000000000000000000000000000..94fb78f417b8f4caab84f569b2926f261250459b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/parametric_actions_cartpole.py @@ -0,0 +1,145 @@ +import random + +import gymnasium as gym +import numpy as np +from gymnasium.spaces import Box, Dict, Discrete + + +class ParametricActionsCartPole(gym.Env): + """Parametric action version of CartPole. + + In this env there are only ever two valid actions, but we pretend there are + actually up to `max_avail_actions` actions that can be taken, and the two + valid actions are randomly hidden among this set. + + At each step, we emit a dict of: + - the actual cart observation + - a mask of valid actions (e.g., [0, 0, 1, 0, 0, 1] for 6 max avail) + - the list of action embeddings (w/ zeroes for invalid actions) (e.g., + [[0, 0], + [0, 0], + [-0.2322, -0.2569], + [0, 0], + [0, 0], + [0.7878, 1.2297]] for max_avail_actions=6) + + In a real environment, the actions embeddings would be larger than two + units of course, and also there would be a variable number of valid actions + per step instead of always [LEFT, RIGHT]. + """ + + def __init__(self, max_avail_actions): + # Use simple random 2-unit action embeddings for [LEFT, RIGHT] + self.left_action_embed = np.random.randn(2) + self.right_action_embed = np.random.randn(2) + self.action_space = Discrete(max_avail_actions) + self.wrapped = gym.make("CartPole-v1") + self.observation_space = Dict( + { + "action_mask": Box(0, 1, shape=(max_avail_actions,), dtype=np.int8), + "avail_actions": Box(-10, 10, shape=(max_avail_actions, 2)), + "cart": self.wrapped.observation_space, + } + ) + + def update_avail_actions(self): + self.action_assignments = np.array( + [[0.0, 0.0]] * self.action_space.n, dtype=np.float32 + ) + self.action_mask = np.array([0.0] * self.action_space.n, dtype=np.int8) + self.left_idx, self.right_idx = random.sample(range(self.action_space.n), 2) + self.action_assignments[self.left_idx] = self.left_action_embed + self.action_assignments[self.right_idx] = self.right_action_embed + self.action_mask[self.left_idx] = 1 + self.action_mask[self.right_idx] = 1 + + def reset(self, *, seed=None, options=None): + self.update_avail_actions() + obs, infos = self.wrapped.reset() + return { + "action_mask": self.action_mask, + "avail_actions": self.action_assignments, + "cart": obs, + }, infos + + def step(self, action): + if action == self.left_idx: + actual_action = 0 + elif action == self.right_idx: + actual_action = 1 + else: + raise ValueError( + "Chosen action was not one of the non-zero action embeddings", + action, + self.action_assignments, + self.action_mask, + self.left_idx, + self.right_idx, + ) + orig_obs, rew, done, truncated, info = self.wrapped.step(actual_action) + self.update_avail_actions() + self.action_mask = self.action_mask.astype(np.int8) + obs = { + "action_mask": self.action_mask, + "avail_actions": self.action_assignments, + "cart": orig_obs, + } + return obs, rew, done, truncated, info + + +class ParametricActionsCartPoleNoEmbeddings(gym.Env): + """Same as the above ParametricActionsCartPole. + + However, action embeddings are not published inside observations, + but will be learnt by the model. + + At each step, we emit a dict of: + - the actual cart observation + - a mask of valid actions (e.g., [0, 0, 1, 0, 0, 1] for 6 max avail) + - action embeddings (w/ "dummy embedding" for invalid actions) are + outsourced in the model and will be learned. + """ + + def __init__(self, max_avail_actions): + # Randomly set which two actions are valid and available. + self.left_idx, self.right_idx = random.sample(range(max_avail_actions), 2) + self.valid_avail_actions_mask = np.array( + [0.0] * max_avail_actions, dtype=np.int8 + ) + self.valid_avail_actions_mask[self.left_idx] = 1 + self.valid_avail_actions_mask[self.right_idx] = 1 + self.action_space = Discrete(max_avail_actions) + self.wrapped = gym.make("CartPole-v1") + self.observation_space = Dict( + { + "valid_avail_actions_mask": Box(0, 1, shape=(max_avail_actions,)), + "cart": self.wrapped.observation_space, + } + ) + + def reset(self, *, seed=None, options=None): + obs, infos = self.wrapped.reset() + return { + "valid_avail_actions_mask": self.valid_avail_actions_mask, + "cart": obs, + }, infos + + def step(self, action): + if action == self.left_idx: + actual_action = 0 + elif action == self.right_idx: + actual_action = 1 + else: + raise ValueError( + "Chosen action was not one of the non-zero action embeddings", + action, + self.valid_avail_actions_mask, + self.left_idx, + self.right_idx, + ) + orig_obs, rew, done, truncated, info = self.wrapped.step(actual_action) + obs = { + "valid_avail_actions_mask": self.valid_avail_actions_mask, + "cart": orig_obs, + } + return obs, rew, done, truncated, info diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/random_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/random_env.py new file mode 100644 index 0000000000000000000000000000000000000000..5f413a597c9abc17180aa5900bd49f5077f45d93 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/random_env.py @@ -0,0 +1,125 @@ +import copy +import gymnasium as gym +from gymnasium.spaces import Discrete, Tuple +import numpy as np + +from ray.rllib.examples.envs.classes.multi_agent import make_multi_agent + + +class RandomEnv(gym.Env): + """A randomly acting environment. + + Can be instantiated with arbitrary action-, observation-, and reward + spaces. Observations and rewards are generated by simply sampling from the + observation/reward spaces. The probability of a `terminated=True` after each + action can be configured, as well as the max episode length. + """ + + def __init__(self, config=None): + config = config or {} + + # Action space. + self.action_space = config.get("action_space", Discrete(2)) + # Observation space from which to sample. + self.observation_space = config.get("observation_space", Discrete(2)) + # Reward space from which to sample. + self.reward_space = config.get( + "reward_space", + gym.spaces.Box(low=-1.0, high=1.0, shape=(), dtype=np.float32), + ) + self.static_samples = config.get("static_samples", False) + if self.static_samples: + self.observation_sample = self.observation_space.sample() + self.reward_sample = self.reward_space.sample() + + # Chance that an episode ends at any step. + # Note that a max episode length can be specified via + # `max_episode_len`. + self.p_terminated = config.get("p_terminated") + if self.p_terminated is None: + self.p_terminated = config.get("p_done", 0.1) + # A max episode length. Even if the `p_terminated` sampling does not lead + # to a terminus, the episode will end after at most this many + # timesteps. + # Set to 0 or None for using no limit on the episode length. + self.max_episode_len = config.get("max_episode_len", None) + # Whether to check action bounds. + self.check_action_bounds = config.get("check_action_bounds", False) + # Steps taken so far (after last reset). + self.steps = 0 + + def reset(self, *, seed=None, options=None): + self.steps = 0 + if not self.static_samples: + return self.observation_space.sample(), {} + else: + return copy.deepcopy(self.observation_sample), {} + + def step(self, action): + if self.check_action_bounds and not self.action_space.contains(action): + raise ValueError( + "Illegal action for {}: {}".format(self.action_space, action) + ) + if isinstance(self.action_space, Tuple) and len(action) != len( + self.action_space.spaces + ): + raise ValueError( + "Illegal action for {}: {}".format(self.action_space, action) + ) + + self.steps += 1 + terminated = False + truncated = False + # We are `truncated` as per our max-episode-len. + if self.max_episode_len and self.steps >= self.max_episode_len: + truncated = True + # Max episode length not reached yet -> Sample `terminated` via `p_terminated`. + elif self.p_terminated > 0.0: + terminated = bool( + np.random.choice( + [True, False], p=[self.p_terminated, 1.0 - self.p_terminated] + ) + ) + + if not self.static_samples: + return ( + self.observation_space.sample(), + self.reward_space.sample(), + terminated, + truncated, + {}, + ) + else: + return ( + copy.deepcopy(self.observation_sample), + copy.deepcopy(self.reward_sample), + terminated, + truncated, + {}, + ) + + +# Multi-agent version of the RandomEnv. +RandomMultiAgentEnv = make_multi_agent(lambda c: RandomEnv(c)) + + +# Large observation space "pre-compiled" random env (for testing). +class RandomLargeObsSpaceEnv(RandomEnv): + def __init__(self, config=None): + config = config or {} + config.update({"observation_space": gym.spaces.Box(-1.0, 1.0, (5000,))}) + super().__init__(config=config) + + +# Large observation space + cont. actions "pre-compiled" random env +# (for testing). +class RandomLargeObsSpaceEnvContActions(RandomEnv): + def __init__(self, config=None): + config = config or {} + config.update( + { + "observation_space": gym.spaces.Box(-1.0, 1.0, (5000,)), + "action_space": gym.spaces.Box(-1.0, 1.0, (5,)), + } + ) + super().__init__(config=config) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/recommender_system_envs_with_recsim.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/recommender_system_envs_with_recsim.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f7a28e4b39ca6587dffdd89a065ce9226187ea --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/recommender_system_envs_with_recsim.py @@ -0,0 +1,108 @@ +"""Examples for RecSim envs ready to be used by RLlib Algorithms. + +RecSim is a configurable recommender systems simulation platform. +Source: https://github.com/google-research/recsim +""" + +from recsim import choice_model +from recsim.environments import ( + long_term_satisfaction as lts, + interest_evolution as iev, + interest_exploration as iex, +) + +from ray.rllib.env.wrappers.recsim import make_recsim_env +from ray.tune import register_env + +# Some built-in RecSim envs to test with. +# --------------------------------------- + +# Long-term satisfaction env: User has to pick from items that are either +# a) unhealthy, but taste good, or b) healthy, but have bad taste. +# Best strategy is to pick a mix of both to ensure long-term +# engagement. + + +def lts_user_model_creator(env_ctx): + return lts.LTSUserModel( + env_ctx["slate_size"], + user_state_ctor=lts.LTSUserState, + response_model_ctor=lts.LTSResponse, + ) + + +def lts_document_sampler_creator(env_ctx): + return lts.LTSDocumentSampler() + + +LongTermSatisfactionRecSimEnv = make_recsim_env( + recsim_user_model_creator=lts_user_model_creator, + recsim_document_sampler_creator=lts_document_sampler_creator, + reward_aggregator=lts.clicked_engagement_reward, +) + + +# Interest exploration env: Models the problem of active exploration +# of user interests. It is meant to illustrate popularity bias in +# recommender systems, where myopic maximization of engagement leads +# to bias towards documents that have wider appeal, +# whereas niche user interests remain unexplored. +def iex_user_model_creator(env_ctx): + return iex.IEUserModel( + env_ctx["slate_size"], + user_state_ctor=iex.IEUserState, + response_model_ctor=iex.IEResponse, + seed=env_ctx["seed"], + ) + + +def iex_document_sampler_creator(env_ctx): + return iex.IETopicDocumentSampler(seed=env_ctx["seed"]) + + +InterestExplorationRecSimEnv = make_recsim_env( + recsim_user_model_creator=iex_user_model_creator, + recsim_document_sampler_creator=iex_document_sampler_creator, + reward_aggregator=iex.total_clicks_reward, +) + + +# Interest evolution env: See https://github.com/google-research/recsim +# for more information. +def iev_user_model_creator(env_ctx): + return iev.IEvUserModel( + env_ctx["slate_size"], + choice_model_ctor=choice_model.MultinomialProportionalChoiceModel, + response_model_ctor=iev.IEvResponse, + user_state_ctor=iev.IEvUserState, + seed=env_ctx["seed"], + ) + + +# Extend IEvVideo to fix a bug caused by None cluster_ids. +class SingleClusterIEvVideo(iev.IEvVideo): + def __init__(self, doc_id, features, video_length=None, quality=None): + super(SingleClusterIEvVideo, self).__init__( + doc_id=doc_id, + features=features, + cluster_id=0, # single cluster. + video_length=video_length, + quality=quality, + ) + + +def iev_document_sampler_creator(env_ctx): + return iev.UtilityModelVideoSampler(doc_ctor=iev.IEvVideo, seed=env_ctx["seed"]) + + +InterestEvolutionRecSimEnv = make_recsim_env( + recsim_user_model_creator=iev_user_model_creator, + recsim_document_sampler_creator=iev_document_sampler_creator, + reward_aggregator=iev.clicked_watchtime_reward, +) + + +# Backward compatibility. +register_env( + name="RecSim-v1", env_creator=lambda env_ctx: InterestEvolutionRecSimEnv(env_ctx) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/repeat_after_me_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/repeat_after_me_env.py new file mode 100644 index 0000000000000000000000000000000000000000..0a87f60ac6c55c6783205e3b9e9ce7392b5f9396 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/repeat_after_me_env.py @@ -0,0 +1,47 @@ +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +import numpy as np + + +class RepeatAfterMeEnv(gym.Env): + """Env in which the observation at timestep minus n must be repeated.""" + + def __init__(self, config=None): + config = config or {} + if config.get("continuous"): + self.observation_space = Box(-1.0, 1.0, (2,)) + else: + self.observation_space = Discrete(2) + + self.action_space = self.observation_space + # Note: Set `repeat_delay` to 0 for simply repeating the seen + # observation (no delay). + self.delay = config.get("repeat_delay", 1) + self.episode_len = config.get("episode_len", 100) + self.history = [] + + def reset(self, *, seed=None, options=None): + self.history = [0] * self.delay + return self._next_obs(), {} + + def step(self, action): + obs = self.history[-(1 + self.delay)] + + reward = 0.0 + # Box: -abs(diff). + if isinstance(self.action_space, Box): + reward = -np.sum(np.abs(action - obs)) + # Discrete: +1.0 if exact match, -1.0 otherwise. + if isinstance(self.action_space, Discrete): + reward = 1.0 if action == obs else -1.0 + + done = truncated = len(self.history) > self.episode_len + return self._next_obs(), reward, done, truncated, {} + + def _next_obs(self): + if isinstance(self.observation_space, Box): + token = np.random.random(size=(2,)) + else: + token = np.random.choice([0, 1]) + self.history.append(token) + return token diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/repeat_initial_obs_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/repeat_initial_obs_env.py new file mode 100644 index 0000000000000000000000000000000000000000..d1d43c560424caaa8fac5b433f536a72d5f4adc5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/repeat_initial_obs_env.py @@ -0,0 +1,32 @@ +import gymnasium as gym +from gymnasium.spaces import Discrete +import random + + +class RepeatInitialObsEnv(gym.Env): + """Env in which the initial observation has to be repeated all the time. + + Runs for n steps. + r=1 if action correct, -1 otherwise (max. R=100). + """ + + def __init__(self, episode_len=100): + self.observation_space = Discrete(2) + self.action_space = Discrete(2) + self.token = None + self.episode_len = episode_len + self.num_steps = 0 + + def reset(self, *, seed=None, options=None): + self.token = random.choice([0, 1]) + self.num_steps = 0 + return self.token, {} + + def step(self, action): + if action == self.token: + reward = 1 + else: + reward = -1 + self.num_steps += 1 + done = truncated = self.num_steps >= self.episode_len + return 0, reward, done, truncated, {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/simple_corridor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/simple_corridor.py new file mode 100644 index 0000000000000000000000000000000000000000..9088f73dbd374da7f7d1312e6ed68c1d5c25444e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/simple_corridor.py @@ -0,0 +1,42 @@ +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +import numpy as np + + +class SimpleCorridor(gym.Env): + """Example of a custom env in which you have to walk down a corridor. + + You can configure the length of the corridor via the env config.""" + + def __init__(self, config=None): + config = config or {} + + self.action_space = Discrete(2) + self.observation_space = Box(0.0, 999.0, shape=(1,), dtype=np.float32) + + self.set_corridor_length(config.get("corridor_length", 10)) + + self._cur_pos = 0 + + def set_corridor_length(self, length): + self.end_pos = length + print(f"Set corridor length to {self.end_pos}") + assert self.end_pos <= 999, "The maximum `corridor_length` allowed is 999!" + + def reset(self, *, seed=None, options=None): + self._cur_pos = 0.0 + return self._get_obs(), {} + + def step(self, action): + assert action in [0, 1], action + if action == 0 and self._cur_pos > 0: + self._cur_pos -= 1.0 + elif action == 1: + self._cur_pos += 1.0 + terminated = self._cur_pos >= self.end_pos + truncated = False + reward = 1.0 if terminated else -0.01 + return self._get_obs(), reward, terminated, truncated, {} + + def _get_obs(self): + return np.array([self._cur_pos], np.float32) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/simple_rpg.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/simple_rpg.py new file mode 100644 index 0000000000000000000000000000000000000000..7de7390bd96dd72e00c3871885ecc600a359e0b5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/simple_rpg.py @@ -0,0 +1,49 @@ +import gymnasium as gym +from gymnasium.spaces import Discrete, Box, Dict + +from ray.rllib.utils.spaces.repeated import Repeated + +# Constraints on the Repeated space. +MAX_PLAYERS = 4 +MAX_ITEMS = 7 +MAX_EFFECTS = 2 + + +class SimpleRPG(gym.Env): + """Example of a custom env with a complex, structured observation. + + The observation is a list of players, each of which is a Dict of + attributes, and may further hold a list of items (categorical space). + + Note that the env doesn't train, it's just a dummy example to show how to + use spaces.Repeated in a custom model (see CustomRPGModel below). + """ + + def __init__(self, config): + self.cur_pos = 0 + self.action_space = Discrete(4) + + # Represents an item. + self.item_space = Discrete(5) + + # Represents an effect on the player. + self.effect_space = Box(9000, 9999, shape=(4,)) + + # Represents a player. + self.player_space = Dict( + { + "location": Box(-100, 100, shape=(2,)), + "status": Box(-1, 1, shape=(10,)), + "items": Repeated(self.item_space, max_len=MAX_ITEMS), + "effects": Repeated(self.effect_space, max_len=MAX_EFFECTS), + } + ) + + # Observation is a list of players. + self.observation_space = Repeated(self.player_space, max_len=MAX_PLAYERS) + + def reset(self, *, seed=None, options=None): + return self.observation_space.sample(), {} + + def step(self, action): + return self.observation_space.sample(), 1, True, False, {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/six_room_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/six_room_env.py new file mode 100644 index 0000000000000000000000000000000000000000..2a4b1a2a41d51084e44e6b6e267ddb309bc1c22d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/six_room_env.py @@ -0,0 +1,315 @@ +import gymnasium as gym + +from ray.rllib.env.multi_agent_env import MultiAgentEnv + + +# Map representation: Always six rooms (as the name suggests) with doors in between. +MAPS = { + "small": [ + "WWWWWWWWWWWWW", + "W W W W", + "W W W", + "W W W", + "W WWWW WWWW W", + "W W W W", + "W W W", + "W W GW", + "WWWWWWWWWWWWW", + ], + "medium": [ + "WWWWWWWWWWWWWWWWWWW", + "W W W W", + "W W W", + "W W W", + "W WWWWWWW WWWWWWW W", + "W W W W", + "W W W", + "W W GW", + "WWWWWWWWWWWWWWWWWWW", + ], + "large": [ + "WWWWWWWWWWWWWWWWWWWWWWWWW", + "W W W W", + "W W W W", + "W W W", + "W W W", + "W W W W", + "WW WWWWWWWWW WWWWWWWWWW W", + "W W W W", + "W W W", + "W W W W", + "W W W", + "W W W GW", + "WWWWWWWWWWWWWWWWWWWWWWWWW", + ], +} + + +class SixRoomEnv(gym.Env): + """A grid-world with six rooms (arranged as 2x3), which are connected by doors. + + The agent starts in the upper left room and has to reach a designated goal state + in one of the rooms using primitive actions up, left, down, and right. + + The agent receives a small penalty of -0.01 on each step and a reward of +10.0 when + reaching the goal state. + """ + + def __init__(self, config=None): + super().__init__() + + # User can provide a custom map or a recognized map name (small, medium, large). + self.map = config.get("custom_map", MAPS.get(config.get("map"), MAPS["small"])) + self.time_limit = config.get("time_limit", 50) + + # Define observation space: Discrete, index fields. + self.observation_space = gym.spaces.Discrete(len(self.map) * len(self.map[0])) + # Primitive actions: up, down, left, right. + self.action_space = gym.spaces.Discrete(4) + + # Initialize environment state. + self.reset() + + def reset(self, *, seed=None, options=None): + self._agent_pos = (1, 1) + self._ts = 0 + # Return high-level observation. + return self._agent_discrete_pos, {} + + def step(self, action): + next_pos = _get_next_pos(action, self._agent_pos) + + self._ts += 1 + + # Check if the move ends up in a wall. If so -> Ignore the move and stay + # where we are right now. + if self.map[next_pos[0]][next_pos[1]] != "W": + self._agent_pos = next_pos + + # Check if the agent has reached the global goal state. + if self.map[self._agent_pos[0]][self._agent_pos[1]] == "G": + return self._agent_discrete_pos, 10.0, True, False, {} + + # Small step penalty. + return self._agent_discrete_pos, -0.01, False, self._ts >= self.time_limit, {} + + @property + def _agent_discrete_pos(self): + x = self._agent_pos[0] + y = self._agent_pos[1] + # discrete position = row idx * columns + col idx + return x * len(self.map[0]) + y + + +class HierarchicalSixRoomEnv(MultiAgentEnv): + def __init__(self, config=None): + super().__init__() + + # User can provide a custom map or a recognized map name (small, medium, large). + self.map = config.get("custom_map", MAPS.get(config.get("map"), MAPS["small"])) + self.max_steps_low_level = config.get("max_steps_low_level", 15) + self.time_limit = config.get("time_limit", 50) + self.num_low_level_agents = config.get("num_low_level_agents", 3) + + self.agents = self.possible_agents = ["high_level_agent"] + [ + f"low_level_agent_{i}" for i in range(self.num_low_level_agents) + ] + + # Define basic observation space: Discrete, index fields. + observation_space = gym.spaces.Discrete(len(self.map) * len(self.map[0])) + # Low level agents always see where they are right now and what the target + # state should be. + low_level_observation_space = gym.spaces.Tuple( + (observation_space, observation_space) + ) + # Primitive actions: up, down, left, right. + low_level_action_space = gym.spaces.Discrete(4) + + self.observation_spaces = {"high_level_agent": observation_space} + self.observation_spaces.update( + { + f"low_level_agent_{i}": low_level_observation_space + for i in range(self.num_low_level_agents) + } + ) + self.action_spaces = { + "high_level_agent": gym.spaces.Tuple( + ( + # The new target observation. + observation_space, + # Low-level policy that should get us to the new target observation. + gym.spaces.Discrete(self.num_low_level_agents), + ) + ) + } + self.action_spaces.update( + { + f"low_level_agent_{i}": low_level_action_space + for i in range(self.num_low_level_agents) + } + ) + + # Initialize environment state. + self.reset() + + def reset(self, *, seed=None, options=None): + self._agent_pos = (1, 1) + self._low_level_steps = 0 + self._high_level_action = None + # Number of times the low-level agent reached the given target (by the high + # level agent). + self._num_targets_reached = 0 + + self._ts = 0 + + # Return high-level observation. + return { + "high_level_agent": self._agent_discrete_pos, + }, {} + + def step(self, action_dict): + self._ts += 1 + + terminateds = {"__all__": self._ts >= self.time_limit} + truncateds = {"__all__": False} + + # High-level agent acted: Set next goal and next low-level policy to use. + # Note that the agent does not move in this case and stays at its current + # location. + if "high_level_agent" in action_dict: + self._high_level_action = action_dict["high_level_agent"] + low_level_agent = f"low_level_agent_{self._high_level_action[1]}" + self._low_level_steps = 0 + # Return next low-level observation for the now-active agent. + # We want this agent to act next. + return ( + { + low_level_agent: ( + self._agent_discrete_pos, # current + self._high_level_action[0], # target + ) + }, + # Penalty for a target state that's close to the current state. + { + "high_level_agent": ( + self.eucl_dist( + self._agent_discrete_pos, + self._high_level_action[0], + self.map, + ) + / (len(self.map) ** 2 + len(self.map[0]) ** 2) ** 0.5 + ) + - 1.0, + }, + terminateds, + truncateds, + {}, + ) + # Low-level agent made a move (primitive action). + else: + assert len(action_dict) == 1 + + # Increment low-level step counter. + self._low_level_steps += 1 + + target_discrete_pos, low_level_agent = self._high_level_action + low_level_agent = f"low_level_agent_{low_level_agent}" + next_pos = _get_next_pos(action_dict[low_level_agent], self._agent_pos) + + # Check if the move ends up in a wall. If so -> Ignore the move and stay + # where we are right now. + if self.map[next_pos[0]][next_pos[1]] != "W": + self._agent_pos = next_pos + + # Check if the agent has reached the global goal state. + if self.map[self._agent_pos[0]][self._agent_pos[1]] == "G": + rewards = { + "high_level_agent": 10.0, + # +1.0 if the goal position was also the target position for the + # low level agent. + low_level_agent: float( + self._agent_discrete_pos == target_discrete_pos + ), + } + terminateds["__all__"] = True + return ( + {"high_level_agent": self._agent_discrete_pos}, + rewards, + terminateds, + truncateds, + {}, + ) + + # Low-level agent has reached its target location (given by the high-level): + # - Hand back control to high-level agent. + # - Reward low level agent and high-level agent with small rewards. + elif self._agent_discrete_pos == target_discrete_pos: + self._num_targets_reached += 1 + rewards = { + "high_level_agent": 1.0, + low_level_agent: 1.0, + } + return ( + {"high_level_agent": self._agent_discrete_pos}, + rewards, + terminateds, + truncateds, + {}, + ) + + # Low-level agent has not reached anything. + else: + # Small step penalty for low-level agent. + rewards = {low_level_agent: -0.01} + # Reached time budget -> Hand back control to high level agent. + if self._low_level_steps >= self.max_steps_low_level: + rewards["high_level_agent"] = -0.01 + return ( + {"high_level_agent": self._agent_discrete_pos}, + rewards, + terminateds, + truncateds, + {}, + ) + else: + return ( + { + low_level_agent: ( + self._agent_discrete_pos, # current + target_discrete_pos, # target + ), + }, + rewards, + terminateds, + truncateds, + {}, + ) + + @property + def _agent_discrete_pos(self): + x = self._agent_pos[0] + y = self._agent_pos[1] + # discrete position = row idx * columns + col idx + return x * len(self.map[0]) + y + + @staticmethod + def eucl_dist(pos1, pos2, map): + x1, y1 = pos1 % len(map[0]), pos1 // len(map) + x2, y2 = pos2 % len(map[0]), pos2 // len(map) + return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 + + +def _get_next_pos(action, pos): + x, y = pos + # Up. + if action == 0: + return x - 1, y + # Down. + elif action == 1: + return x + 1, y + # Left. + elif action == 2: + return x, y - 1 + # Right. + else: + return x, y + 1 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/stateless_cartpole.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/stateless_cartpole.py new file mode 100644 index 0000000000000000000000000000000000000000..cacc95bd7057120324e3c5460884db7028b6306c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/stateless_cartpole.py @@ -0,0 +1,39 @@ +from gymnasium.spaces import Box +import numpy as np + +from gymnasium.envs.classic_control import CartPoleEnv + + +class StatelessCartPole(CartPoleEnv): + """Partially observable variant of the CartPole gym environment. + + https://github.com/openai/gym/blob/master/gym/envs/classic_control/ + cartpole.py + + We delete the x- and angular velocity components of the state, so that it + can only be solved by a memory enhanced model (policy). + """ + + def __init__(self, config=None): + super().__init__() + + # Fix our observation-space (remove 2 velocity components). + high = np.array( + [ + self.x_threshold * 2, + self.theta_threshold_radians * 2, + ], + dtype=np.float32, + ) + + self.observation_space = Box(low=-high, high=high, dtype=np.float32) + + def step(self, action): + next_obs, reward, done, truncated, info = super().step(action) + # next_obs is [x-pos, x-veloc, angle, angle-veloc] + return np.array([next_obs[0], next_obs[2]]), reward, done, truncated, info + + def reset(self, *, seed=None, options=None): + init_obs, init_info = super().reset(seed=seed, options=options) + # init_obs is [x-pos, x-veloc, angle, angle-veloc] + return np.array([init_obs[0], init_obs[2]]), init_info diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/stateless_pendulum.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/stateless_pendulum.py new file mode 100644 index 0000000000000000000000000000000000000000..36c6018229a5b510baeb9ea11bf0f68b1a7946ac --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/stateless_pendulum.py @@ -0,0 +1,35 @@ +from gymnasium.spaces import Box +import numpy as np + +from gymnasium.envs.classic_control import PendulumEnv + + +class StatelessPendulum(PendulumEnv): + """Partially observable variant of the Pendulum gym environment. + + https://github.com/Farama-Foundation/Gymnasium/blob/main/gymnasium/envs/ + classic_control/pendulum.py + + We delete the angular velocity component of the state, so that it + can only be solved by a memory enhanced model (policy). + """ + + def __init__(self, config=None): + config = config or {} + g = config.get("g", 10.0) + + super().__init__(g=g) + + # Fix our observation-space (remove angular velocity component). + high = np.array([1.0, 1.0], dtype=np.float32) + self.observation_space = Box(low=-high, high=high, dtype=np.float32) + + def step(self, action): + next_obs, reward, done, truncated, info = super().step(action) + # next_obs is [cos(theta), sin(theta), theta-dot (angular velocity)] + return next_obs[:-1], reward, done, truncated, info + + def reset(self, *, seed=None, options=None): + init_obs, init_info = super().reset(seed=seed, options=options) + # init_obs is [cos(theta), sin(theta), theta-dot (angular velocity)] + return init_obs[:-1], init_info diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/transformed_action_space_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/transformed_action_space_env.py new file mode 100644 index 0000000000000000000000000000000000000000..1dce1051cbf30861fb196e6c8fbc0cf1522c871a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/transformed_action_space_env.py @@ -0,0 +1,61 @@ +import gymnasium as gym +from typing import Type + + +class ActionTransform(gym.ActionWrapper): + def __init__(self, env, low, high): + super().__init__(env) + self._low = low + self._high = high + self.action_space = type(env.action_space)( + self._low, self._high, env.action_space.shape, env.action_space.dtype + ) + + def action(self, action): + return (action - self._low) / (self._high - self._low) * ( + self.env.action_space.high - self.env.action_space.low + ) + self.env.action_space.low + + +def transform_action_space(env_name_or_creator) -> Type[gym.Env]: + """Wrapper for gym.Envs to have their action space transformed. + + Args: + env_name_or_creator (Union[str, Callable[]]: String specifier or + env_maker function. + + Returns: + New transformed_action_space_env function that returns an environment + wrapped by the ActionTransform wrapper. The constructor takes a + config dict with `_low` and `_high` keys specifying the new action + range (default -1.0 to 1.0). The reset of the config dict will be + passed on to the underlying/wrapped env's constructor. + + .. testcode:: + :skipif: True + + # By gym string: + pendulum_300_to_500_cls = transform_action_space("Pendulum-v1") + # Create a transformed pendulum env. + pendulum_300_to_500 = pendulum_300_to_500_cls({"_low": -15.0}) + pendulum_300_to_500.action_space + + .. testoutput:: + + gym.spaces.Box(-15.0, 1.0, (1, ), "float32") + """ + + def transformed_action_space_env(config): + if isinstance(env_name_or_creator, str): + inner_env = gym.make(env_name_or_creator) + else: + inner_env = env_name_or_creator(config) + _low = config.pop("low", -1.0) + _high = config.pop("high", 1.0) + env = ActionTransform(inner_env, _low, _high) + return env + + return transformed_action_space_env + + +TransformedActionPendulum = transform_action_space("Pendulum-v1") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39b15f7fe42c5ab856b7f628088db8dd1074f253 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/cartpole_observations_proto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/cartpole_observations_proto.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7b641aa92bf07a09fa4807cc12a65a7f32c5b27 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/cartpole_observations_proto.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/dummy_external_client.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/dummy_external_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c85592c1cc459b45add1bae4706baf686e3731a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/__pycache__/dummy_external_client.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/cartpole_observations_proto.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/cartpole_observations_proto.py new file mode 100644 index 0000000000000000000000000000000000000000..15b30f5b0b13680f3c4c4e8eba039cd038accd23 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/cartpole_observations_proto.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: cartpole_observations.proto +# Protobuf Python Version: 5.26.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1b\x63\x61rtpole_observations.proto"]\n\x13\x43\x61rtPoleObservation\x12\r\n\x05x_pos\x18\x01 \x01(\x01\x12\x0f\n\x07x_veloc\x18\x02 \x01(\x01\x12\x11\n\tangle_pos\x18\x03 \x01(\x01\x12\x13\n\x0b\x61ngle_veloc\x18\x04 \x01(\x01\x62\x06proto3' # noqa +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "cartpole_observations_proto", _globals +) +if not _descriptor._USE_C_DESCRIPTORS: + DESCRIPTOR._loaded_options = None + _globals["_CARTPOLEOBSERVATION"]._serialized_start = 31 + _globals["_CARTPOLEOBSERVATION"]._serialized_end = 124 +# @@protoc_insertion_point(module_scope) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/dummy_external_client.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/dummy_external_client.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc1bf0af6f70b9c7789d5950462e5ff5bd72d62 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/utils/dummy_external_client.py @@ -0,0 +1,126 @@ +import pickle +import socket +import time + +import gymnasium as gym +import numpy as np + +from ray.rllib.core import ( + Columns, + COMPONENT_RL_MODULE, +) +from ray.rllib.env.external.rllink import ( + get_rllink_message, + send_rllink_message, + RLlink, +) +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import softmax + +torch, _ = try_import_torch() + + +def _dummy_external_client(port: int = 5556): + """A dummy client that runs CartPole and acts as a testing external env.""" + + def _set_state(msg_body, rl_module): + rl_module.set_state(msg_body[COMPONENT_RL_MODULE]) + # return msg_body[WEIGHTS_SEQ_NO] + + # Connect to server. + while True: + try: + print(f"Trying to connect to localhost:{port} ...") + sock_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock_.connect(("localhost", port)) + break + except ConnectionRefusedError: + time.sleep(5) + + # Send ping-pong. + send_rllink_message(sock_, {"type": RLlink.PING.name}) + msg_type, msg_body = get_rllink_message(sock_) + assert msg_type == RLlink.PONG + + # Request config. + send_rllink_message(sock_, {"type": RLlink.GET_CONFIG.name}) + msg_type, msg_body = get_rllink_message(sock_) + assert msg_type == RLlink.SET_CONFIG + + config = pickle.loads(msg_body["config"]) + # Create the RLModule. + rl_module = config.get_rl_module_spec().build() + + # Request state/weights. + send_rllink_message(sock_, {"type": RLlink.GET_STATE.name}) + msg_type, msg_body = get_rllink_message(sock_) + assert msg_type == RLlink.SET_STATE + _set_state(msg_body["state"], rl_module) + + env_steps_per_sample = config.get_rollout_fragment_length() + + # Start actual env loop. + env = gym.make("CartPole-v1") + obs, _ = env.reset() + episode = SingleAgentEpisode(observations=[obs]) + episodes = [episode] + + while True: + # Perform action inference using the RLModule. + logits = rl_module.forward_exploration( + batch={ + Columns.OBS: torch.tensor(np.array([obs], np.float32)), + } + )[Columns.ACTION_DIST_INPUTS][ + 0 + ].numpy() # [0]=batch size 1 + + # Stochastic sample. + action_probs = softmax(logits) + action = int(np.random.choice(list(range(env.action_space.n)), p=action_probs)) + logp = float(np.log(action_probs[action])) + + # Perform the env step. + obs, reward, terminated, truncated, _ = env.step(action) + + # Collect step data. + episode.add_env_step( + action=action, + reward=reward, + observation=obs, + terminated=terminated, + truncated=truncated, + extra_model_outputs={ + Columns.ACTION_DIST_INPUTS: logits, + Columns.ACTION_LOGP: logp, + }, + ) + + # We collected enough samples -> Send them to server. + if sum(map(len, episodes)) == env_steps_per_sample: + # Send the data to the server. + send_rllink_message( + sock_, + { + "type": RLlink.EPISODES_AND_GET_STATE.name, + "episodes": [e.get_state() for e in episodes], + "timesteps": env_steps_per_sample, + }, + ) + # We are forced to sample on-policy. Have to wait for a response + # with the state (weights) in it. + msg_type, msg_body = get_rllink_message(sock_) + assert msg_type == RLlink.SET_STATE + _set_state(msg_body["state"], rl_module) + + episodes = [] + if not episode.is_done: + episode = episode.cut() + episodes.append(episode) + + # If episode is done, reset env and create a new episode. + if episode.is_done: + obs, _ = env.reset() + episode = SingleAgentEpisode(observations=[obs]) + episodes.append(episode) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/windy_maze_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/windy_maze_env.py new file mode 100644 index 0000000000000000000000000000000000000000..0a86fe4f9069a50ffb338b7ad3e7779a3260fb1f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/classes/windy_maze_env.py @@ -0,0 +1,159 @@ +import gymnasium as gym +from gymnasium.spaces import Box, Discrete, Tuple +import logging +import random + +from ray.rllib.env import MultiAgentEnv + +logger = logging.getLogger(__name__) + +# Agent has to traverse the maze from the starting position S -> F +# Observation space [x_pos, y_pos, wind_direction] +# Action space: stay still OR move in current wind direction +MAP_DATA = """ +######### +#S # +####### # + # # + # # +####### # +#F # +#########""" + + +class WindyMazeEnv(gym.Env): + def __init__(self, env_config): + self.map = [m for m in MAP_DATA.split("\n") if m] + self.x_dim = len(self.map) + self.y_dim = len(self.map[0]) + logger.info("Loaded map {} {}".format(self.x_dim, self.y_dim)) + for x in range(self.x_dim): + for y in range(self.y_dim): + if self.map[x][y] == "S": + self.start_pos = (x, y) + elif self.map[x][y] == "F": + self.end_pos = (x, y) + logger.info("Start pos {} end pos {}".format(self.start_pos, self.end_pos)) + self.observation_space = Tuple( + [ + Box(0, 100, shape=(2,)), # (x, y) + Discrete(4), # wind direction (N, E, S, W) + ] + ) + self.action_space = Discrete(2) # whether to move or not + + def reset(self, *, seed=None, options=None): + self.wind_direction = random.choice([0, 1, 2, 3]) + self.pos = self.start_pos + self.num_steps = 0 + return [[self.pos[0], self.pos[1]], self.wind_direction], {} + + def step(self, action): + if action == 1: + self.pos = self._get_new_pos(self.pos, self.wind_direction) + self.num_steps += 1 + self.wind_direction = random.choice([0, 1, 2, 3]) + at_goal = self.pos == self.end_pos + truncated = self.num_steps >= 200 + done = at_goal or truncated + return ( + [[self.pos[0], self.pos[1]], self.wind_direction], + 100 * int(at_goal), + done, + truncated, + {}, + ) + + def _get_new_pos(self, pos, direction): + if direction == 0: + new_pos = (pos[0] - 1, pos[1]) + elif direction == 1: + new_pos = (pos[0], pos[1] + 1) + elif direction == 2: + new_pos = (pos[0] + 1, pos[1]) + elif direction == 3: + new_pos = (pos[0], pos[1] - 1) + if ( + new_pos[0] >= 0 + and new_pos[0] < self.x_dim + and new_pos[1] >= 0 + and new_pos[1] < self.y_dim + and self.map[new_pos[0]][new_pos[1]] != "#" + ): + return new_pos + else: + return pos # did not move + + +class HierarchicalWindyMazeEnv(MultiAgentEnv): + def __init__(self, env_config): + super().__init__() + self.flat_env = WindyMazeEnv(env_config) + + def reset(self, *, seed=None, options=None): + self.cur_obs, infos = self.flat_env.reset() + self.current_goal = None + self.steps_remaining_at_level = None + self.num_high_level_steps = 0 + # current low level agent id. This must be unique for each high level + # step since agent ids cannot be reused. + self.low_level_agent_id = "low_level_{}".format(self.num_high_level_steps) + return { + "high_level_agent": self.cur_obs, + }, {"high_level_agent": infos} + + def step(self, action_dict): + assert len(action_dict) == 1, action_dict + if "high_level_agent" in action_dict: + return self._high_level_step(action_dict["high_level_agent"]) + else: + return self._low_level_step(list(action_dict.values())[0]) + + def _high_level_step(self, action): + logger.debug("High level agent sets goal") + self.current_goal = action + self.steps_remaining_at_level = 25 + self.num_high_level_steps += 1 + self.low_level_agent_id = "low_level_{}".format(self.num_high_level_steps) + obs = {self.low_level_agent_id: [self.cur_obs, self.current_goal]} + rew = {self.low_level_agent_id: 0} + done = truncated = {"__all__": False} + return obs, rew, done, truncated, {} + + def _low_level_step(self, action): + logger.debug("Low level agent step {}".format(action)) + self.steps_remaining_at_level -= 1 + cur_pos = tuple(self.cur_obs[0]) + goal_pos = self.flat_env._get_new_pos(cur_pos, self.current_goal) + + # Step in the actual env + f_obs, f_rew, f_terminated, f_truncated, info = self.flat_env.step(action) + new_pos = tuple(f_obs[0]) + self.cur_obs = f_obs + + # Calculate low-level agent observation and reward + obs = {self.low_level_agent_id: [f_obs, self.current_goal]} + if new_pos != cur_pos: + if new_pos == goal_pos: + rew = {self.low_level_agent_id: 1} + else: + rew = {self.low_level_agent_id: -1} + else: + rew = {self.low_level_agent_id: 0} + + # Handle env termination & transitions back to higher level. + terminated = {"__all__": False} + truncated = {"__all__": False} + if f_terminated or f_truncated: + terminated["__all__"] = f_terminated + truncated["__all__"] = f_truncated + logger.debug("high level final reward {}".format(f_rew)) + rew["high_level_agent"] = f_rew + obs["high_level_agent"] = f_obs + elif self.steps_remaining_at_level == 0: + terminated[self.low_level_agent_id] = True + truncated[self.low_level_agent_id] = False + rew["high_level_agent"] = 0 + obs["high_level_agent"] = f_obs + + return obs, rew, terminated, truncated, {self.low_level_agent_id: info} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/custom_env_render_method.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/custom_env_render_method.py new file mode 100644 index 0000000000000000000000000000000000000000..3aa44f63095b5848ac67b13ad8e5e9df747f26d7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/custom_env_render_method.py @@ -0,0 +1,199 @@ +"""Example of implementing a custom `render()` method for your gymnasium RL environment. + +This example: + - shows how to write a simple gym.Env class yourself, in this case a corridor env, + in which the agent starts at the left side of the corridor and has to reach the + goal state all the way at the right. + - in particular, the new class overrides the Env's `render()` method to show, how + you can write your own rendering logic. + - furthermore, we use the RLlib callbacks class introduced in this example here: + https://github.com/ray-project/ray/blob/master/rllib/examples/envs/env_rendering_and_recording.py # noqa + in order to compile videos of the worst and best performing episodes in each + iteration and log these videos to your WandB account, so you can view them. + + +How to run this script +---------------------- +`python [script file name].py +--wandb-key=[your WandB API key] --wandb-project=[some WandB project name] +--wandb-run-name=[optional: WandB run name within --wandb-project]` + +In order to see the actual videos, you need to have a WandB account and provide your +API key and a project name on the command line (see above). + +Use the `--num-agents` argument to set up the env as a multi-agent env. If +`--num-agents` > 0, RLlib will simply run as many of the defined single-agent +environments in parallel and with different policies to be trained for each agent. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + + +Results to expect +----------------- +After the first training iteration, you should see the videos in your WandB account +under the provided `--wandb-project` name. Filter for "videos_best" or "videos_worst". + +Note that the default Tune TensorboardX (TBX) logger might complain about the videos +being logged. This is ok, the TBX logger will simply ignore these. The WandB logger, +however, will recognize the video tensors shaped +(1 [batch], T [video len], 3 [rgb], [height], [width]) and properly create a WandB video +object to be sent to their server. + +Your terminal output should look similar to this (the following is for a +`--num-agents=2` run; expect similar results for the other `--num-agents` +settings): ++---------------------+------------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +|---------------------+------------+----------------+--------+------------------+ +| PPO_env_fb1c0_00000 | TERMINATED | 127.0.0.1:8592 | 3 | 21.1876 | ++---------------------+------------+----------------+--------+------------------+ ++-------+-------------------+-------------+-------------+ +| ts | combined return | return p1 | return p0 | +|-------+-------------------+-------------+-------------| +| 12000 | 12.7655 | 7.3605 | 5.4095 | ++-------+-------------------+-------------+-------------+ +""" + +import gymnasium as gym +import numpy as np +from gymnasium.spaces import Box, Discrete +from PIL import Image, ImageDraw + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.env.multi_agent_env import make_multi_agent +from ray.rllib.examples.envs.env_rendering_and_recording import EnvRenderCallback +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray import tune + +parser = add_rllib_example_script_args( + default_iters=10, + default_reward=9.0, + default_timesteps=10000, +) + + +class CustomRenderedCorridorEnv(gym.Env): + """Example of a custom env, for which we specify rendering behavior.""" + + def __init__(self, config): + self.end_pos = config.get("corridor_length", 10) + self.max_steps = config.get("max_steps", 100) + self.cur_pos = 0 + self.steps = 0 + self.action_space = Discrete(2) + self.observation_space = Box(0.0, 999.0, shape=(1,), dtype=np.float32) + + def reset(self, *, seed=None, options=None): + self.cur_pos = 0.0 + self.steps = 0 + return np.array([self.cur_pos], np.float32), {} + + def step(self, action): + self.steps += 1 + assert action in [0, 1], action + if action == 0 and self.cur_pos > 0: + self.cur_pos -= 1.0 + elif action == 1: + self.cur_pos += 1.0 + truncated = self.steps >= self.max_steps + terminated = self.cur_pos >= self.end_pos + return ( + np.array([self.cur_pos], np.float32), + 10.0 if terminated else -0.1, + terminated, + truncated, + {}, + ) + + def render(self) -> np._typing.NDArray[np.uint8]: + """Implements rendering logic for this env (given the current observation). + + You should return a numpy RGB image like so: + np.array([height, width, 3], dtype=np.uint8). + + Returns: + np.ndarray: A numpy uint8 3D array (image) to render. + """ + # Image dimensions. + # Each position in the corridor is 50 pixels wide. + width = (self.end_pos + 2) * 50 + # Fixed height of the image. + height = 100 + + # Create a new image with white background + image = Image.new("RGB", (width, height), "white") + draw = ImageDraw.Draw(image) + + # Draw the corridor walls + # Grey rectangle for the corridor. + draw.rectangle([50, 30, width - 50, 70], fill="grey") + + # Draw the agent. + # Calculate the x coordinate of the agent. + agent_x = (self.cur_pos + 1) * 50 + # Blue rectangle for the agent. + draw.rectangle([agent_x + 10, 40, agent_x + 40, 60], fill="blue") + + # Draw the goal state. + # Calculate the x coordinate of the goal. + goal_x = self.end_pos * 50 + # Green rectangle for the goal state. + draw.rectangle([goal_x + 10, 40, goal_x + 40, 60], fill="green") + + # Convert the image to a uint8 numpy array. + return np.array(image, dtype=np.uint8) + + +# Create a simple multi-agent version of the above Env by duplicating the single-agent +# env n (n=num agents) times and having the agents act independently, each one in a +# different corridor. +MultiAgentCustomRenderedCorridorEnv = make_multi_agent( + lambda config: CustomRenderedCorridorEnv(config) +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # The `config` arg passed into our Env's constructor (see the class' __init__ method + # above). Feel free to change these. + env_options = { + "corridor_length": 10, + "max_steps": 100, + "num_agents": args.num_agents, # <- only used by the multu-agent version. + } + + env_cls_to_use = ( + CustomRenderedCorridorEnv + if args.num_agents == 0 + else MultiAgentCustomRenderedCorridorEnv + ) + + tune.register_env("env", lambda _: env_cls_to_use(env_options)) + + # Example config switching on rendering. + base_config = ( + PPOConfig() + # Configure our env to be the above-registered one. + .environment("env") + # Plugin our env-rendering (and logging) callback. This callback class allows + # you to fully customize your rendering behavior (which workers should render, + # which episodes, which (vector) env indices, etc..). We refer to this example + # script here for further details: + # https://github.com/ray-project/ray/blob/master/rllib/examples/envs/env_rendering_and_recording.py # noqa + .callbacks(EnvRenderCallback) + ) + + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, eps, **kw: f"p{aid}", + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/custom_gym_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/custom_gym_env.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5db2b5465fe4e548093f93f397e104b13b29e5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/custom_gym_env.py @@ -0,0 +1,164 @@ +"""Example of defining a custom gymnasium Env to be learned by an RLlib Algorithm. + +This example: + - demonstrates how to write your own (single-agent) gymnasium Env class, define its + physics and mechanics, the reward function used, the allowed actions (action space), + and the type of observations (observation space), etc.. + - shows how to configure and setup this environment class within an RLlib + Algorithm config. + - runs the experiment with the configured algo, trying to solve the environment. + +To see more details on which env we are building for this example, take a look at the +`SimpleCorridor` class defined below. + + +How to run this script +---------------------- +`python [script file name].py` + +Use the `--corridor-length` option to set a custom length for the corridor. Note that +for extremely long corridors, the algorithm should take longer to learn. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see results similar to the following in your console output: + ++--------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|--------------------------------+------------+-----------------+--------+ +| PPO_SimpleCorridor_78714_00000 | TERMINATED | 127.0.0.1:85794 | 7 | ++--------------------------------+------------+-----------------+--------+ + ++------------------+-------+----------+--------------------+ +| total time (s) | ts | reward | episode_len_mean | +|------------------+-------+----------+--------------------| +| 18.3034 | 28000 | 0.908918 | 12.9676 | ++------------------+-------+----------+--------------------+ +""" +# These tags allow extracting portions of this script on Anyscale. +# ws-template-imports-start +import gymnasium as gym +from gymnasium.spaces import Discrete, Box +import numpy as np +import random + +from typing import Optional + +# ws-template-imports-end + +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env # noqa + + +parser = add_rllib_example_script_args( + default_reward=0.9, + default_iters=50, + default_timesteps=100000, +) +parser.add_argument( + "--corridor-length", + type=int, + default=10, + help="The length of the corridor in fields. Note that this number includes the " + "starting- and goal states.", +) + + +# These tags allow extracting portions of this script on Anyscale. +# ws-template-code-start +class SimpleCorridor(gym.Env): + """Example of a custom env in which the agent has to walk down a corridor. + + ------------ + |S........G| + ------------ + , where S is the starting position, G is the goal position, and fields with '.' + mark free spaces, over which the agent may step. The length of the above example + corridor is 10. + Allowed actions are left (0) and right (1). + The reward function is -0.01 per step taken and a uniform random value between + 0.5 and 1.5 when reaching the goal state. + + You can configure the length of the corridor via the env's config. Thus, in your + AlgorithmConfig, you can do: + `config.environment(env_config={"corridor_length": ..})`. + """ + + def __init__(self, config: Optional[dict] = None): + config = config or {} + self.end_pos = config.get("corridor_length", 7) + self.cur_pos = 0 + self.action_space = Discrete(2) + self.observation_space = Box(0.0, self.end_pos, shape=(1,), dtype=np.float32) + + def reset(self, *, seed=None, options=None): + random.seed(seed) + self.cur_pos = 0 + # Return obs and (empty) info dict. + return np.array([self.cur_pos], np.float32), {"env_state": "reset"} + + def step(self, action): + assert action in [0, 1], action + # Move left. + if action == 0 and self.cur_pos > 0: + self.cur_pos -= 1 + # Move right. + elif action == 1: + self.cur_pos += 1 + + # The environment only ever terminates when we reach the goal state. + terminated = self.cur_pos >= self.end_pos + truncated = False + # Produce a random reward from [0.5, 1.5] when we reach the goal. + reward = random.uniform(0.5, 1.5) if terminated else -0.01 + infos = {} + return ( + np.array([self.cur_pos], np.float32), + reward, + terminated, + truncated, + infos, + ) + + +# ws-template-code-end + +if __name__ == "__main__": + args = parser.parse_args() + + # Can also register the env creator function explicitly with: + # register_env("corridor-env", lambda config: SimpleCorridor()) + + # Or you can hard code certain settings into the Env's constructor (`config`). + # register_env( + # "corridor-env-w-len-100", + # lambda config: SimpleCorridor({**config, **{"corridor_length": 100}}), + # ) + + # Or allow the RLlib user to set more c'tor options via their algo config: + # config.environment(env_config={[c'tor arg name]: [value]}) + # register_env("corridor-env", lambda config: SimpleCorridor(config)) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + SimpleCorridor, # or provide the registered string: "corridor-env" + env_config={"corridor_length": args.corridor_length}, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_connecting_to_rllib_w_tcp_client.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_connecting_to_rllib_w_tcp_client.py new file mode 100644 index 0000000000000000000000000000000000000000..aedd97237ce0da652dce65ad3978c791a53f8738 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_connecting_to_rllib_w_tcp_client.py @@ -0,0 +1,140 @@ +"""Example of running against a TCP-connected external env performing its own inference. + +The example uses a custom EnvRunner (EnvRunnerServerForExternalInference) to allow +connections from one or more TCP clients to RLlib's EnvRunner actors, which act as +RL servers. +In this example, action inference for stepping the env is performed on the client's +side, meaning the client computes all actions itself, applies them to the env logic, +collects episodes of experiences, and sends these (in bulk) back to RLlib for training. +Also, from time to time, the updated model weights have to be sent from RLlib (server) +back to the connected clients. +Note that RLlib's new API stack does not yet support individual action requests, where +action computations happen on the RLlib (server) side. + +This example: + - demonstrates how RLlib can be hooked up to an externally running complex simulator + through TCP connections. + - shows how a custom EnvRunner subclass can be configured allowing users to + implement their own logic of connecting to external processes and customize the + messaging protocols. + + +How to run this script +---------------------- +`python [script file name].py --port 5555 + +Use the `--port` option to change the default port (5555) to some other value. +Make sure that you do the same on the client side. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see something like this on your terminal. Note that the dummy CartPole +client (which runs in a thread for the purpose of this example here) might throw +a disconnection error at the end, b/c RLlib closes the server socket when done training. + ++----------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|----------------------+------------+--------+------------------+ +| PPO_None_3358e_00000 | TERMINATED | 40 | 32.2649 | ++----------------------+------------+--------+------------------+ ++------------------------+------------------------+ +| episode_return_mean | num_env_steps_sample | +| | d_lifetime | +|-----------------------+------------------------| +| 458.68 | 160000 | ++-----------------------+------------------------+ + +From the dummy client (thread), you should see at the end: +``` +ConnectionError: Error receiving message from peer on socket ... +``` +""" +import threading + +import gymnasium as gym +import numpy as np + +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.env.external.env_runner_server_for_external_inference import ( + EnvRunnerServerForExternalInference, +) +from ray.rllib.examples.envs.classes.utils.dummy_external_client import ( + _dummy_external_client, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_reward=450.0, default_iters=200, default_timesteps=2000000 +) +parser.set_defaults( + num_env_runners=1, +) +parser.add_argument( + "--port", + type=int, + default=5555, + help="The port for RLlib's EnvRunner to listen to for incoming UE5 connections. " + "You need to specify the same port inside your UE5 `RLlibClient` plugin.", +) +parser.add_argument( + "--use-dummy-client", + action="store_true", + help="If set, the script runs with its own external client acting as a " + "simulator. Otherwise connect on your own from your C++ application.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Start the dummy CartPole "simulation". + if args.use_dummy_client: + threading.Thread( + target=_dummy_external_client, + args=( + # Connect to the first remote EnvRunner, of - if there is no remote one - + # to the local EnvRunner. + args.port + + (args.num_env_runners if args.num_env_runners is not None else 1), + ), + ).start() + + # Define the RLlib (server) config. + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + observation_space=gym.spaces.Box( + float("-inf"), float("-inf"), (4,), np.float32 + ), + action_space=gym.spaces.Discrete(2), + # EnvRunners listen on `port` + their worker index. + env_config={"port": args.port}, + ) + .env_runners( + # Point RLlib to the custom EnvRunner to be used here. + env_runner_cls=EnvRunnerServerForExternalInference, + ) + .training( + num_epochs=10, + vf_loss_coeff=0.01, + ) + .rl_module(model_config=DefaultModelConfig(vf_share_layers=True)) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_rendering_and_recording.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_rendering_and_recording.py new file mode 100644 index 0000000000000000000000000000000000000000..17019cdea3c6c182515f50ae2a45230132356592 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_rendering_and_recording.py @@ -0,0 +1,302 @@ +"""Example of using a custom Callback to render and log episode videos from a gym.Env. + +This example: + - shows how to set up your (Atari) gym.Env for human-friendly rendering inside the + `AlgorithmConfig.environment()` method. + - demonstrates how to write an RLlib custom callback class that renders all envs on + all timesteps, stores the individual images temporarily in the Episode + objects, and compiles a video from these images once the Episode terminates. + - furthermore, in each sampling cycle (iteration), the callback uses the unified + `MetricsLogger` facility - available in all RLlib components - to log the video of + the best performing and worst performing episode and sends these videos to WandB. + - configures the above callbacks class within the AlgorithmConfig. + + +How to run this script +---------------------- +`python [script file name].py --env [env name e.g. 'ALE/Pong-v5'] +--wandb-key=[your WandB API key] --wandb-project=[some WandB project name] +--wandb-run-name=[optional: WandB run name within --wandb-project]` + +In order to see the actual videos, you need to have a WandB account and provide your +API key and a project name on the command line (see above). To log the videos in WandB +you need to have the `wandb` and `moviepy` packages installed (`pip install wandb +moviepy`). + +Use the `--env` flag to control, which Atari env is used. Note that this example +only works with Atari envs. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + + +Results to expect +----------------- +After the first training iteration, you should see the videos in your WandB account +under the provided `--wandb-project` name. Filter for "videos_best" or "videos_worst". + +Note that the default Tune TensorboardX (TBX) logger might complain about the videos +being logged. This is ok, the TBX logger will simply ignore these. The WandB logger, +however, will recognize the video tensors shaped +(1 [batch], T [video len], 3 [rgb], [height], [width]) and properly create a WandB video +object to be sent to their server. + +Your terminal output should look similar to this: ++---------------------+----------+-----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+----------+-----------------+--------+------------------+ +| PPO_env_8d3f3_00000 | RUNNING | 127.0.0.1:89991 | 1 | 239.633 | ++---------------------+----------+-----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| num_env_steps_sample | num_env_steps_traine | num_episodes_lifetim | +| d_lifetime | d_lifetime | e | ++------------------------+------------------------+------------------------| +| 4000 | 4000 | 24 | ++------------------------+------------------------+------------------------+ +""" +import gymnasium as gym +import numpy as np +from typing import Optional, Sequence + +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.env.vector.vector_multi_agent_env import VectorMultiAgentEnv +from ray.rllib.env.wrappers.atari_wrappers import wrap_atari_for_new_api_stack +from ray.rllib.utils.images import resize +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env +from ray import tune + +parser = add_rllib_example_script_args(default_reward=20.0) +parser.set_defaults( + env="ale_py:ALE/Pong-v5", +) + + +class EnvRenderCallback(RLlibCallback): + """A custom callback to render the environment. + + This can be used to create videos of the episodes for some or all EnvRunners + and some or all env indices (in a vectorized env). These videos can then + be sent to e.g. WandB as shown in this example script here. + + We override the `on_episode_step` method to create a single ts render image + and temporarily store it in the Episode object. + """ + + def __init__(self, env_runner_indices: Optional[Sequence[int]] = None): + """Initializes an EnvRenderCallback instance. + + Args: + env_runner_indices: The (optional) EnvRunner indices, for this callback + should be active. If None, activates the rendering for all EnvRunners. + If a Sequence type, only renders, if the EnvRunner index is found in + `env_runner_indices`. + """ + super().__init__() + # Only render and record on certain EnvRunner indices? + self._env_runner_indices = env_runner_indices + # Per sample round (on this EnvRunner), we want to only log the best- and + # worst performing episode's videos in the custom metrics. Otherwise, too much + # data would be sent to WandB. + self.best_episode_and_return = (None, float("-inf")) + self.worst_episode_and_return = (None, float("inf")) + + def on_episode_step( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + """Adds current render image to episode's temporary data. + + Note that this would work with MultiAgentEpisodes as well. + """ + # Skip, if this EnvRunner's index is not in `self._env_runner_indices`. + if ( + self._env_runner_indices is not None + and env_runner.worker_index not in self._env_runner_indices + ): + return + + # If we have a vector env, only render the sub-env at index 0. + if isinstance(env.unwrapped, (gym.vector.VectorEnv, VectorMultiAgentEnv)): + image = env.unwrapped.envs[0].render() + # Render the gym.Env. + else: + image = env.unwrapped.render() + + # Original render images for CartPole are 400x600 (hxw). We'll downsize here to + # a very small dimension (to save space and bandwidth). + image = resize(image, 64, 96) + # For WandB videos, we need to put channels first. + image = np.transpose(image, axes=[2, 0, 1]) + # Add the compiled single-step image as temp. data to our Episode object. + # Once the episode is done, we'll compile the video from all logged images + # and log the video with the EnvRunner's `MetricsLogger.log_...()` APIs. + # See below: + # `on_episode_end()`: We compile the video and maybe store it). + # `on_sample_end()` We log the best and worst video to the `MetricsLogger`. + if "render_images" not in episode.custom_data: + episode.custom_data["render_images"] = [] + episode.custom_data["render_images"].append(image) + + def on_episode_end( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + """Computes episode's return and compiles a video, iff best/worst in this iter. + + Note that the actual logging to the EnvRunner's MetricsLogger only happens + at the very env of sampling (when we know, which episode was the best and + worst). See `on_sample_end` for the implemented logging logic. + """ + if ( + self._env_runner_indices is not None + and env_runner.worker_index not in self._env_runner_indices + ): + return + + # Get the episode's return. + episode_return = episode.get_return() + + # Better than the best or worse than worst Episode thus far? + if ( + episode_return > self.best_episode_and_return[1] + or episode_return < self.worst_episode_and_return[1] + ): + # Pull all images from the temp. data of the episode. + images = episode.custom_data["render_images"] + # `images` is now a list of 3D ndarrays + + # Create a video from the images by simply stacking them AND + # adding an extra B=1 dimension. Note that Tune's WandB logger currently + # knows how to log the different data types by the following rules: + # array is shape=3D -> An image (c, h, w). + # array is shape=4D -> A batch of images (B, c, h, w). + # array is shape=5D -> A video (1, L, c, h, w), where L is the length of the + # video. + # -> Make our video ndarray a 5D one. + video = np.expand_dims(np.stack(images, axis=0), axis=0) + + # `video` is from the best episode in this cycle (iteration). + if episode_return > self.best_episode_and_return[1]: + self.best_episode_and_return = (video, episode_return) + # `video` is worst in this cycle (iteration). + else: + self.worst_episode_and_return = (video, episode_return) + + def on_sample_end( + self, + *, + env_runner, + metrics_logger, + samples, + **kwargs, + ) -> None: + """Logs the best and worst video to this EnvRunner's MetricsLogger.""" + # Best video. + if self.best_episode_and_return[0] is not None: + metrics_logger.log_value( + "episode_videos_best", + self.best_episode_and_return[0], + # Do not reduce the videos (across the various parallel EnvRunners). + # This would not make sense (mean over the pixels?). Instead, we want to + # log all best videos of all EnvRunners per iteration. + reduce=None, + # B/c we do NOT reduce over the video data (mean/min/max), we need to + # make sure the list of videos in our MetricsLogger does not grow + # infinitely and gets cleared after each `reduce()` operation, meaning + # every time, the EnvRunner is asked to send its logged metrics. + clear_on_reduce=True, + ) + self.best_episode_and_return = (None, float("-inf")) + # Worst video. + if self.worst_episode_and_return[0] is not None: + metrics_logger.log_value( + "episode_videos_worst", + self.worst_episode_and_return[0], + # Same logging options as above. + reduce=None, + clear_on_reduce=True, + ) + self.worst_episode_and_return = (None, float("inf")) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + def _env_creator(cfg): + cfg.update({"render_mode": "rgb_array"}) + if args.env.startswith("ale_py:ALE/"): + cfg.update( + { + # Make analogous to old v4 + NoFrameskip. + "frameskip": 1, + "full_action_space": False, + "repeat_action_probability": 0.0, + } + ) + return wrap_atari_for_new_api_stack(gym.make(args.env, **cfg), framestack=4) + else: + return gym.make(args.env, **cfg) + + register_env("env", _env_creator) + + base_config = ( + get_trainable_cls(args.algo).get_default_config() + # Use the above-registered environment. + .environment("env") + # Plug in our custom callback that controls, which videos are created (best, + # and worst per sampling cycle per EnvRunner) and then logged via the + # `MetricsLogger` API. + .callbacks(EnvRenderCallback) + # Switch off RLlib's logging to avoid having the large videos show up in any log + # files. + .debugging(logger_config={"type": tune.logger.NoopLogger}) + # The following settings are beneficial for Atari-type environments. Feel free + # to adjust these when providing a non-Atari `--env` option. + .training( + lambda_=0.95, + kl_coeff=0.5, + clip_param=0.1, + vf_clip_param=10.0, + entropy_coeff=0.01, + num_epochs=10, + # Linearly adjust learning rate based on number of GPUs. + lr=0.00015 * (args.num_learners or 1), + grad_clip=100.0, + grad_clip_by="global_norm", + ) + ) + + if base_config.is_atari: + base_config.rl_module( + model_config=DefaultModelConfig( + conv_filters=[[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]], + conv_activation="relu", + head_fcnet_hiddens=[256], + vf_share_layers=True, + ), + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_w_protobuf_observations.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_w_protobuf_observations.py new file mode 100644 index 0000000000000000000000000000000000000000..77b4ee024d9232ef60fbdb87965319462e77ec79 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/env_w_protobuf_observations.py @@ -0,0 +1,79 @@ +"""Example of handling an Env that outputs protobuf observations. + +This example: + - demonstrates how a custom Env can use protobufs to compress its observation into + a binary format to save space and gain performance. + - shows how to use a very simple ConnectorV2 piece that translates these protobuf + binary observation strings into proper more NN-readable observations (like a 1D + float32 tensor). + +To see more details on which env we are building for this example, take a look at the +`CartPoleWithProtobufObservationSpace` class imported below. +To see more details on which ConnectorV2 piece we are plugging into the config +below, take a look at the `ProtobufCartPoleObservationDecoder` class imported below. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see results similar to the following in your console output: + ++------------------------------------------------------+------------+-----------------+ +| Trial name | status | loc | +| | | | +|------------------------------------------------------+------------+-----------------+ +| PPO_CartPoleWithProtobufObservationSpace_47dd2_00000 | TERMINATED | 127.0.0.1:67325 | ++------------------------------------------------------+------------+-----------------+ ++--------+------------------+------------------------+------------------------+ +| iter | total time (s) | episode_return_mean | num_episodes_lifetim | +| | | | e | ++--------+------------------+------------------------+------------------------+ +| 17 | 39.9011 | 513.29 | 465 | ++--------+------------------+------------------------+------------------------+ +""" +from ray.rllib.examples.connectors.classes.protobuf_cartpole_observation_decoder import ( # noqa + ProtobufCartPoleObservationDecoder, +) +from ray.rllib.examples.envs.classes.cartpole_with_protobuf_observation_space import ( + CartPoleWithProtobufObservationSpace, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + + +parser = add_rllib_example_script_args(default_timesteps=200000, default_reward=400.0) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo).get_default_config() + # Set up the env to be CartPole-v1, but with protobuf observations. + .environment(CartPoleWithProtobufObservationSpace) + # Plugin our custom ConnectorV2 piece to translate protobuf observations + # (box of dtype uint8) into NN-readible ones (1D tensor of dtype flaot32). + .env_runners( + env_to_module_connector=( + lambda env, spaces, device: ProtobufCartPoleObservationDecoder() + ), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/greyscale_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/greyscale_env.py new file mode 100644 index 0000000000000000000000000000000000000000..7df56f5477842971d11ddaaead7a0a1305b2450a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/greyscale_env.py @@ -0,0 +1,126 @@ +# @OldAPIStack +""" +Example of interfacing with an environment that produces 2D observations. + +This example shows how turning 2D observations with shape (A, B) into a 3D +observations with shape (C, D, 1) can enable usage of RLlib's default models. +RLlib's default Catalog class does not provide default models for 2D observation +spaces, but it does so for 3D observations. +Therefore, one can either write a custom model or transform the 2D observations into 3D +observations. This enables RLlib to use one of the default CNN filters, even though the +original observation space of the environment does not fit them. + +This simple example should reach rewards of 50 within 150k timesteps. +""" + +from numpy import float32 +import argparse +from pettingzoo.butterfly import pistonball_v6 +from supersuit import ( + normalize_obs_v0, + dtype_v0, + color_reduction_v0, + reshape_v0, + resize_v1, +) + +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.env import PettingZooEnv +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.tune.registry import register_env +from ray import tune + + +parser = argparse.ArgumentParser() +parser.add_argument( + "--framework", + choices=["tf2", "torch"], + default="torch", + help="The DL framework specifier.", +) +parser.add_argument( + "--as-test", + action="store_true", + help="Whether this script should be run as a compilation test.", +) +parser.add_argument( + "--stop-iters", type=int, default=150, help="Number of iterations to train." +) +parser.add_argument( + "--stop-timesteps", type=int, default=1000000, help="Number of timesteps to train." +) +parser.add_argument( + "--stop-reward", type=float, default=50, help="Reward at which we stop training." +) + +args = parser.parse_args() + + +# The space we down-sample and transform the greyscale pistonball images to. +# Other spaces supported by RLlib can be chosen here. +TRANSFORMED_OBS_SPACE = (42, 42, 1) + + +def env_creator(config): + env = pistonball_v6.env(n_pistons=5) + env = dtype_v0(env, dtype=float32) + # This gives us greyscale images for the color red + env = color_reduction_v0(env, mode="R") + env = normalize_obs_v0(env) + # This gives us images that are upsampled to the number of pixels in the + # default CNN filter + env = resize_v1( + env, x_size=TRANSFORMED_OBS_SPACE[0], y_size=TRANSFORMED_OBS_SPACE[1] + ) + # This gives us 3D images for which we have default filters + env = reshape_v0(env, shape=TRANSFORMED_OBS_SPACE) + return env + + +# Register env +register_env("pistonball", lambda config: PettingZooEnv(env_creator(config))) + +config = ( + PPOConfig() + .environment("pistonball", env_config={"local_ratio": 0.5}, clip_rewards=True) + .env_runners( + num_env_runners=15 if not args.as_test else 2, + num_envs_per_env_runner=1, + observation_filter="NoFilter", + rollout_fragment_length="auto", + ) + .framework("torch") + .training( + entropy_coeff=0.01, + vf_loss_coeff=0.1, + clip_param=0.1, + vf_clip_param=10.0, + num_epochs=10, + kl_coeff=0.5, + lr=0.0001, + grad_clip=100, + minibatch_size=500, + train_batch_size=5000 if not args.as_test else 1000, + model={"vf_share_layers": True}, + ) + .resources(num_gpus=1 if not args.as_test else 0) + .reporting(min_time_s_per_iteration=30) +) + +tune.Tuner( + "PPO", + param_space=config.to_dict(), + run_config=tune.RunConfig( + stop={ + TRAINING_ITERATION: args.stop_iters, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + }, + verbose=2, + ), +).fit() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/unity3d_env_local.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/unity3d_env_local.py new file mode 100644 index 0000000000000000000000000000000000000000..f923c8beeed0a8024dd5d9ad9230b30022e45779 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/envs/unity3d_env_local.py @@ -0,0 +1,213 @@ +# @OldAPIStack + +""" +Example of running an RLlib Algorithm against a locally running Unity3D editor +instance (available as Unity3DEnv inside RLlib). +For a distributed cloud setup example with Unity, +see `examples/envs/external_envs/unity3d_[server|client].py` + +To run this script against a local Unity3D engine: +1) Install Unity3D and `pip install mlagents`. + +2) Open the Unity3D Editor and load an example scene from the following + ml-agents pip package location: + `.../ml-agents/Project/Assets/ML-Agents/Examples/` + This script supports the `3DBall`, `3DBallHard`, `SoccerStrikersVsGoalie`, + `Tennis`, and `Walker` examples. + Specify the game you chose on your command line via e.g. `--env 3DBall`. + Feel free to add more supported examples here. + +3) Then run this script (you will have to press Play in your Unity editor + at some point to start the game and the learning process): +$ python unity3d_env_local.py --env 3DBall --stop-reward [..] + [--framework=torch]? +""" + +import argparse +import os + +import ray +from ray import tune +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.env.wrappers.unity3d_env import Unity3DEnv +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import check_learning_achieved + +parser = argparse.ArgumentParser() +parser.add_argument( + "--env", + type=str, + default="3DBall", + choices=[ + "3DBall", + "3DBallHard", + "GridFoodCollector", + "Pyramids", + "SoccerStrikersVsGoalie", + "SoccerTwos", + "Sorter", + "Tennis", + "VisualHallway", + "Walker", + ], + help="The name of the Env to run in the Unity3D editor: `3DBall(Hard)?|" + "Pyramids|GridFoodCollector|SoccerStrikersVsGoalie|Sorter|Tennis|" + "VisualHallway|Walker` (feel free to add more and PR!)", +) +parser.add_argument( + "--file-name", + type=str, + default=None, + help="The Unity3d binary (compiled) game, e.g. " + "'/home/ubuntu/soccer_strikers_vs_goalie_linux.x86_64'. Use `None` for " + "a currently running Unity3D editor.", +) +parser.add_argument( + "--from-checkpoint", + type=str, + default=None, + help="Full path to a checkpoint file for restoring a previously saved " + "Algorithm state.", +) +parser.add_argument("--num-workers", type=int, default=0) +parser.add_argument( + "--as-test", + action="store_true", + help="Whether this script should be run as a test: --stop-reward must " + "be achieved within --stop-timesteps AND --stop-iters.", +) +parser.add_argument( + "--stop-iters", type=int, default=9999, help="Number of iterations to train." +) +parser.add_argument( + "--stop-timesteps", type=int, default=10000000, help="Number of timesteps to train." +) +parser.add_argument( + "--stop-reward", + type=float, + default=9999.0, + help="Reward at which we stop training.", +) +parser.add_argument( + "--horizon", + type=int, + default=3000, + help="The max. number of `step()`s for any episode (per agent) before " + "it'll be reset again automatically.", +) +parser.add_argument( + "--framework", + choices=["tf", "tf2", "torch"], + default="torch", + help="The DL framework specifier.", +) + +if __name__ == "__main__": + ray.init() + + args = parser.parse_args() + + tune.register_env( + "unity3d", + lambda c: Unity3DEnv( + file_name=c["file_name"], + no_graphics=(args.env != "VisualHallway" and c["file_name"] is not None), + episode_horizon=c["episode_horizon"], + ), + ) + + # Get policies (different agent types; "behaviors" in MLAgents) and + # the mappings from individual agents to Policies. + policies, policy_mapping_fn = Unity3DEnv.get_policy_configs_for_game(args.env) + + config = ( + PPOConfig() + .environment( + "unity3d", + env_config={ + "file_name": args.file_name, + "episode_horizon": args.horizon, + }, + ) + .framework("tf" if args.env != "Pyramids" else "torch") + # For running in editor, force to use just one Worker (we only have + # one Unity running)! + .env_runners( + num_env_runners=args.num_workers if args.file_name else 0, + rollout_fragment_length=200, + ) + .training( + lr=0.0003, + lambda_=0.95, + gamma=0.99, + minibatch_size=256, + train_batch_size=4000, + num_epochs=20, + clip_param=0.2, + model={"fcnet_hiddens": [512, 512]}, + ) + .multi_agent(policies=policies, policy_mapping_fn=policy_mapping_fn) + # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0. + .resources(num_gpus=int(os.environ.get("RLLIB_NUM_GPUS", "0"))) + ) + + # Switch on Curiosity based exploration for Pyramids env + # (not solvable otherwise). + if args.env == "Pyramids": + config.env_runners( + exploration_config={ + "type": "Curiosity", + "eta": 0.1, + "lr": 0.001, + # No actual feature net: map directly from observations to feature + # vector (linearly). + "feature_net_config": { + "fcnet_hiddens": [], + "fcnet_activation": "relu", + }, + "sub_exploration": { + "type": "StochasticSampling", + }, + "forward_net_activation": "relu", + "inverse_net_activation": "relu", + } + ) + elif args.env == "GridFoodCollector": + config.training( + model={ + "conv_filters": [[16, [4, 4], 2], [32, [4, 4], 2], [256, [10, 10], 1]], + } + ) + elif args.env == "Sorter": + config.training(model={"use_attention": True}) + + stop = { + TRAINING_ITERATION: args.stop_iters, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + + # Run the experiment. + results = tune.Tuner( + "PPO", + param_space=config.to_dict(), + run_config=tune.RunConfig( + stop=stop, + verbose=1, + checkpoint_config=tune.CheckpointConfig( + checkpoint_frequency=5, + checkpoint_at_end=True, + ), + ), + ).fit() + + # And check the results. + if args.as_test: + check_learning_achieved(results, args.stop_reward) + + ray.shutdown() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0065fa636f14c4a878028824ff87d441d51ad8bc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/custom_evaluation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/custom_evaluation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f9fe98cbff9327749b087a0b075dd454ea47f65 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/custom_evaluation.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/evaluation_parallel_to_training.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/evaluation_parallel_to_training.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4977c476cd7c6651694554cab51c3cdb7ff8d0e1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/__pycache__/evaluation_parallel_to_training.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/custom_evaluation.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/custom_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..e503b02a50e7c457c618c5023037e90bc89a1c6e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/custom_evaluation.py @@ -0,0 +1,231 @@ +"""Example of customizing the evaluation procedure for an RLlib Algorithm. + +Note, that you should only choose to provide a custom eval function, in case the already +built-in eval options are not sufficient. Normally, though, RLlib's eval utilities +that come with each Algorithm are enough to properly evaluate the learning progress +of your Algorithm. + +This script uses the SimpleCorridor environment, a simple 1D gridworld, in which +the agent can only walk left (action=0) or right (action=1). The goal state is located +at the end of the (1D) corridor. The env exposes an API to change the length of the +corridor on-the-fly. We use this API here to extend the size of the corridor for the +evaluation runs. + +For demonstration purposes only, we define a simple custom evaluation method that does +the following: +- It changes the corridor length of all environments used on the evaluation EnvRunners. +- It runs a defined number of episodes for evaluation purposes. +- It collects the metrics from those runs, summarizes these metrics and returns them. + + +How to run this script +---------------------- +`python [script file name].py + +You can switch off custom evaluation (and use RLlib's default evaluation procedure) +with the `--no-custom-eval` flag. + +You can switch on parallel evaluation to training using the +`--evaluation-parallel-to-training` flag. See this example script here: +https://github.com/ray-project/ray/blob/master/rllib/examples/evaluation/evaluation_parallel_to_training.py # noqa +for more details on running evaluation parallel to training. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see the following (or very similar) console output when running this script. +Note that for each iteration, due to the definition of our custom evaluation function, +we run 3 evaluation rounds per single training round. + +... +Training iteration 1 -> evaluation round 0 +Training iteration 1 -> evaluation round 1 +Training iteration 1 -> evaluation round 2 +... +... ++--------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|--------------------------------+------------+-----------------+--------+ +| PPO_SimpleCorridor_06582_00000 | TERMINATED | 127.0.0.1:69905 | 4 | ++--------------------------------+------------+-----------------+--------+ ++------------------+-------+----------+--------------------+ +| total time (s) | ts | reward | episode_len_mean | +|------------------+-------+----------+--------------------| +| 26.1973 | 16000 | 0.872034 | 13.7966 | ++------------------+-------+----------+--------------------+ +""" +from typing import Tuple + +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.env.env_runner_group import EnvRunnerGroup +from ray.rllib.examples.envs.classes.simple_corridor import SimpleCorridor +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EVALUATION_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.rllib.utils.typing import ResultDict +from ray.tune.registry import get_trainable_cls + + +parser = add_rllib_example_script_args( + default_iters=50, + default_reward=0.7, + default_timesteps=50000, +) +parser.add_argument("--no-custom-eval", action="store_true") +parser.add_argument("--corridor-length-training", type=int, default=10) +parser.add_argument("--corridor-length-eval-worker-1", type=int, default=20) +parser.add_argument("--corridor-length-eval-worker-2", type=int, default=30) + + +def custom_eval_function( + algorithm: Algorithm, + eval_workers: EnvRunnerGroup, +) -> Tuple[ResultDict, int, int]: + """Example of a custom evaluation function. + + Args: + algorithm: Algorithm class to evaluate. + eval_workers: Evaluation EnvRunnerGroup. + + Returns: + metrics: Evaluation metrics dict. + """ + # Set different env settings for each (eval) EnvRunner. Here we use the EnvRunner's + # `worker_index` property to figure out the actual length. + # Loop through all workers and all sub-envs (gym.Env) on each worker and call the + # `set_corridor_length` method on these. + eval_workers.foreach_env_runner( + func=lambda worker: ( + env.unwrapped.set_corridor_length( + args.corridor_length_eval_worker_1 + if worker.worker_index == 1 + else args.corridor_length_eval_worker_2 + ) + for env in worker.env.unwrapped.envs + ) + ) + + # Collect metrics results collected by eval workers in this list for later + # processing. + env_runner_metrics = [] + sampled_episodes = [] + # For demonstration purposes, run through some number of evaluation + # rounds within this one call. Note that this function is called once per + # training iteration (`Algorithm.train()` call) OR once per `Algorithm.evaluate()` + # (which can be called manually by the user). + for i in range(3): + print(f"Training iteration {algorithm.iteration} -> evaluation round {i}") + # Sample episodes from the EnvRunners AND have them return only the thus + # collected metrics. + episodes_and_metrics_all_env_runners = eval_workers.foreach_env_runner( + # Return only the metrics, NOT the sampled episodes (we don't need them + # anymore). + func=lambda worker: (worker.sample(), worker.get_metrics()), + local_env_runner=False, + ) + sampled_episodes.extend( + eps + for eps_and_mtrcs in episodes_and_metrics_all_env_runners + for eps in eps_and_mtrcs[0] + ) + env_runner_metrics.extend( + eps_and_mtrcs[1] for eps_and_mtrcs in episodes_and_metrics_all_env_runners + ) + + # You can compute metrics from the episodes manually, or use the Algorithm's + # convenient MetricsLogger to store all evaluation metrics inside the main + # algo. + algorithm.metrics.aggregate( + env_runner_metrics, key=(EVALUATION_RESULTS, ENV_RUNNER_RESULTS) + ) + eval_results = algorithm.metrics.peek((EVALUATION_RESULTS, ENV_RUNNER_RESULTS)) + # Alternatively, you could manually reduce over the n returned `env_runner_metrics` + # dicts, but this would be much harder as you might not know, which metrics + # to sum up, which ones to average over, etc.. + + # Compute env and agent steps from sampled episodes. + env_steps = sum(eps.env_steps() for eps in sampled_episodes) + agent_steps = sum(eps.agent_steps() for eps in sampled_episodes) + + return eval_results, env_steps, agent_steps + + +if __name__ == "__main__": + args = parser.parse_args() + args.local_mode = True + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + # For training, we use a corridor length of n. For evaluation, we use different + # values, depending on the eval worker index (1 or 2). + .environment( + SimpleCorridor, + env_config={"corridor_length": args.corridor_length_training}, + ) + .env_runners(create_env_on_local_worker=True) + .evaluation( + # Do we use the custom eval function defined above? + custom_evaluation_function=( + None if args.no_custom_eval else custom_eval_function + ), + # Number of eval EnvRunners to use. + evaluation_num_env_runners=2, + # Enable evaluation, once per training iteration. + evaluation_interval=1, + # Run 10 episodes each time evaluation runs (OR "auto" if parallel to + # training). + evaluation_duration="auto" if args.evaluation_parallel_to_training else 10, + # Evaluate parallelly to training? + evaluation_parallel_to_training=args.evaluation_parallel_to_training, + # Override the env settings for the eval workers. + # Note, though, that this setting here is only used in case --no-custom-eval + # is set, b/c in case the custom eval function IS used, we override the + # length of the eval environments in that custom function, so this setting + # here is simply ignored. + evaluation_config=AlgorithmConfig.overrides( + env_config={"corridor_length": args.corridor_length_training * 2}, + # TODO (sven): Add support for window=float(inf) and reduce=mean for + # evaluation episode_return_mean reductions (identical to old stack + # behavior, which does NOT use a window (100 by default) to reduce + # eval episode returns. + metrics_num_episodes_for_smoothing=5, + ), + ) + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": ( + args.stop_reward + ), + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + } + + run_rllib_example_script_experiment( + base_config, + args, + stop=stop, + success_metric={ + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": ( + args.stop_reward + ), + }, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/evaluation_parallel_to_training.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/evaluation_parallel_to_training.py new file mode 100644 index 0000000000000000000000000000000000000000..12c371aa3849054a0fd66f15bff9ea28970835d1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/evaluation/evaluation_parallel_to_training.py @@ -0,0 +1,256 @@ +"""Example showing how one can set up evaluation running in parallel to training. + +Such a setup saves a considerable amount of time during RL Algorithm training, b/c +the next training step does NOT have to wait for the previous evaluation procedure to +finish, but can already start running (in parallel). + +See RLlib's documentation for more details on the effect of the different supported +evaluation configuration options: +https://docs.ray.io/en/latest/rllib/rllib-advanced-api.html#customized-evaluation-during-training # noqa + +For an example of how to write a fully customized evaluation function (which normally +is not necessary as the config options are sufficient and offer maximum flexibility), +see this example script here: + +https://github.com/ray-project/ray/blob/master/rllib/examples/evaluation/custom_evaluation.py # noqa + + +How to run this script +---------------------- +`python [script file name].py` + +Use the `--evaluation-num-workers` option to scale up the evaluation workers. Note +that the requested evaluation duration (`--evaluation-duration` measured in +`--evaluation-duration-unit`, which is either "timesteps" (default) or "episodes") is +shared between all configured evaluation workers. For example, if the evaluation +duration is 10 and the unit is "episodes" and you configured 5 workers, then each of the +evaluation workers will run exactly 2 episodes. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see the following output (at the end of the experiment) in your console when +running with a fixed number of 100k training timesteps +(`--evaluation-duration=auto --stop-timesteps=100000 +--stop-reward=100000`): ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_1377a_00000 | TERMINATED | 127.0.0.1:73330 | 25 | ++-----------------------------+------------+-----------------+--------+ ++------------------+--------+----------+--------------------+ +| total time (s) | ts | reward | episode_len_mean | +|------------------+--------+----------+--------------------| +| 71.7485 | 100000 | 476.51 | 476.51 | ++------------------+--------+----------+--------------------+ + +When running without parallel evaluation (no `--evaluation-parallel-to-training` flag), +the experiment takes considerably longer (~70sec vs ~80sec): ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_f1788_00000 | TERMINATED | 127.0.0.1:75135 | 25 | ++-----------------------------+------------+-----------------+--------+ ++------------------+--------+----------+--------------------+ +| total time (s) | ts | reward | episode_len_mean | +|------------------+--------+----------+--------------------| +| 81.7371 | 100000 | 494.68 | 494.68 | ++------------------+--------+----------+--------------------+ +""" +from typing import Optional + +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, + NUM_EPISODES, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.rllib.utils.typing import ResultDict +from ray.tune.registry import get_trainable_cls, register_env + +parser = add_rllib_example_script_args( + default_timesteps=200000, + default_reward=500.0, +) +parser.set_defaults( + evaluation_num_env_runners=2, + evaluation_interval=1, +) + + +class AssertEvalCallback(RLlibCallback): + def on_train_result( + self, + *, + algorithm: Algorithm, + metrics_logger: Optional[MetricsLogger] = None, + result: ResultDict, + **kwargs, + ): + # The eval results can be found inside the main `result` dict + # (old API stack: "evaluation"). + eval_results = result.get(EVALUATION_RESULTS, {}) + # In there, there is a sub-key: ENV_RUNNER_RESULTS. + eval_env_runner_results = eval_results.get(ENV_RUNNER_RESULTS) + # Make sure we always run exactly the given evaluation duration, + # no matter what the other settings are (such as + # `evaluation_num_env_runners` or `evaluation_parallel_to_training`). + if eval_env_runner_results and NUM_EPISODES in eval_env_runner_results: + num_episodes_done = eval_env_runner_results[NUM_EPISODES] + if algorithm.config.enable_env_runner_and_connector_v2: + num_timesteps_reported = eval_env_runner_results[NUM_ENV_STEPS_SAMPLED] + else: + num_timesteps_reported = eval_results["timesteps_this_iter"] + + # We run for automatic duration (as long as training takes). + if algorithm.config.evaluation_duration == "auto": + # If duration=auto: Expect at least as many timesteps as workers + # (each worker's `sample()` is at least called once). + # UNLESS: All eval workers were completely busy during the auto-time + # with older (async) requests and did NOT return anything from the async + # fetch. + assert ( + num_timesteps_reported == 0 + or num_timesteps_reported + >= algorithm.config.evaluation_num_env_runners + ) + # We count in episodes. + elif algorithm.config.evaluation_duration_unit == "episodes": + # Compare number of entries in episode_lengths (this is the + # number of episodes actually run) with desired number of + # episodes from the config. + assert ( + algorithm.iteration + 1 % algorithm.config.evaluation_interval != 0 + or num_episodes_done == algorithm.config.evaluation_duration + ), (num_episodes_done, algorithm.config.evaluation_duration) + print( + "Number of run evaluation episodes: " f"{num_episodes_done} (ok)!" + ) + # We count in timesteps. + else: + # TODO (sven): This assertion works perfectly fine locally, but breaks + # the CI for no reason. The observed collected timesteps is +500 more + # than desired (~2500 instead of 2011 and ~1250 vs 1011). + # num_timesteps_wanted = algorithm.config.evaluation_duration + # delta = num_timesteps_wanted - num_timesteps_reported + # Expect roughly the same (desired // num-eval-workers). + # assert abs(delta) < 20, ( + # delta, + # num_timesteps_wanted, + # num_timesteps_reported, + # ) + print( + "Number of run evaluation timesteps: " + f"{num_timesteps_reported} (ok?)!" + ) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda _: MultiAgentCartPole(config={"num_agents": args.num_agents}), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env" if args.num_agents > 0 else "CartPole-v1") + .env_runners(create_env_on_local_worker=True) + # Use a custom callback that asserts that we are running the + # configured exact number of episodes per evaluation OR - in auto + # mode - run at least as many episodes as we have eval workers. + .callbacks(AssertEvalCallback) + .evaluation( + # Parallel evaluation+training config. + # Switch on evaluation in parallel with training. + evaluation_parallel_to_training=args.evaluation_parallel_to_training, + # Use two evaluation workers. Must be >0, otherwise, + # evaluation will run on a local worker and block (no parallelism). + evaluation_num_env_runners=args.evaluation_num_env_runners, + # Evaluate every other training iteration (together + # with every other call to Algorithm.train()). + evaluation_interval=args.evaluation_interval, + # Run for n episodes/timesteps (properly distribute load amongst + # all eval workers). The longer it takes to evaluate, the more sense + # it makes to use `evaluation_parallel_to_training=True`. + # Use "auto" to run evaluation for roughly as long as the training + # step takes. + evaluation_duration=args.evaluation_duration, + # "episodes" or "timesteps". + evaluation_duration_unit=args.evaluation_duration_unit, + # Switch off exploratory behavior for better (greedy) results. + evaluation_config={ + "explore": False, + # TODO (sven): Add support for window=float(inf) and reduce=mean for + # evaluation episode_return_mean reductions (identical to old stack + # behavior, which does NOT use a window (100 by default) to reduce + # eval episode returns. + "metrics_num_episodes_for_smoothing": 5, + }, + ) + ) + + # Set the minimum time for an iteration to 10sec, even for algorithms like PPO + # that naturally limit their iteration times to exactly one `training_step` + # call. This provides enough time for the eval EnvRunners in the + # "evaluation_duration=auto" setting to sample at least one complete episode. + if args.evaluation_duration == "auto": + base_config.reporting(min_time_s_per_iteration=10) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + # Set some PPO-specific tuning settings to learn better in the env (assumed to be + # CartPole-v1). + if args.algo == "PPO": + base_config.training( + lr=0.0003, + num_epochs=6, + vf_loss_coeff=0.01, + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": ( + args.stop_reward + ), + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + } + + run_rllib_example_script_experiment( + base_config, + args, + stop=stop, + success_metric={ + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": ( + args.stop_reward + ), + }, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8a902686857b20205fe260215b8d526f9d3735c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/__pycache__/crashing_and_stalling_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/__pycache__/crashing_and_stalling_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8db8ac6fb0f547e49961ac215f61301e8e0b653 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/__pycache__/crashing_and_stalling_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/crashing_and_stalling_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/crashing_and_stalling_env.py new file mode 100644 index 0000000000000000000000000000000000000000..39b700edde700dd91ed52f4c1470348ff49c4cc5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/fault_tolerance/crashing_and_stalling_env.py @@ -0,0 +1,175 @@ +"""Example demonstrating that RLlib can learn (at scale) in unstable environments. + +This script uses the `CartPoleCrashing` environment, an adapted cartpole env whose +instability is configurable through setting the probability of a crash and/or stall +(sleep for a configurable amount of time) during `reset()` and/or `step()`. + +RLlib has two major flags for EnvRunner fault tolerance, which can be independently +set to True: +1) `config.fault_tolerance(restart_failed_sub_environments=True)` causes only the +(gymnasium) environment object on an EnvRunner to be closed (try calling `close()` on +the faulty object), garbage collected, and finally recreated from scratch. Note that +during this process, the containing EnvRunner remaing up and running and sampling +simply continues after the env recycling. This is the lightest and fastest form of +fault tolerance and should be attempted first. +2) `config.fault_tolerance(restart_failed_env_runners=True)` causes the entire +EnvRunner (a Ray remote actor) to be restarted. This restart logically includes the +gymnasium environment, the RLModule, and all connector pipelines on the EnvRunner. +Use this option only if you face problems with the first option +(restart_failed_sub_environments=True), such as incomplete cleanups and memory leaks. + + +How to run this script +---------------------- +`python [script file name].py + +You can switch on the fault tolerant behavior (1) (restart_failed_sub_environments) +through the `--restart-failed-envs` flag. If this flag is not set, the script will +recreate the entire (faulty) EnvRunner. + +You can switch on stalling (besides crashing) through the `--stall` command line flag. +If set, besides crashing on `reset()` and/or `step()`, there is also a chance of +stalling for a few seconds on each of these events. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see the following (or very similar) console output when running this script +with: +`--algo=PPO --stall --restart-failed-envs --stop-reward=450.0` ++---------------------+------------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+------------+----------------+--------+------------------+ +| PPO_env_ba39b_00000 | TERMINATED | 127.0.0.1:1401 | 22 | 133.497 | ++---------------------+------------+----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetim | num_env_steps_traine | +| | e | d_lifetime | +|------------------------+------------------------+------------------------| +| 450.24 | 542 | 88628 | ++------------------------+------------------------+------------------------+ + +For APPO and testing restarting the entire EnvRunners, you could run the script with: +`--algo=APPO --stall --stop-reward=450.0` ++----------------------+------------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|----------------------+------------+----------------+--------+------------------+ +| APPO_env_ba39b_00000 | TERMINATED | 127.0.0.1:4653 | 10 | 101.531 | ++----------------------+------------+----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetim | num_env_steps_traine | +| | e | d_lifetime | +|------------------------+------------------------+------------------------| +| 478.85 | 2546 | 321500 | ++------------------------+------------------------+------------------------+ +""" +from gymnasium.wrappers import TimeLimit + +from ray import tune +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.cartpole_crashing import ( + CartPoleCrashing, + MultiAgentCartPoleCrashing, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +parser = add_rllib_example_script_args( + default_reward=450.0, + default_timesteps=2000000, +) +parser.set_defaults( + num_env_runners=4, +) +# Use `parser` to add your own custom command line options to this script +# and (if needed) use their values to set up `config` below. +parser.add_argument( + "--stall", + action="store_true", + help="Whether to also stall the env from time to time", +) +parser.add_argument( + "--restart-failed-envs", + action="store_true", + help="Whether to restart a failed environment (vs restarting the entire " + "EnvRunner).", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + if args.num_agents > 0: + tune.register_env("env", lambda cfg: MultiAgentCartPoleCrashing(cfg)) + else: + tune.register_env( + "env", + lambda cfg: TimeLimit(CartPoleCrashing(cfg), max_episode_steps=500), + ) + + base_config = ( + tune.registry.get_trainable_cls(args.algo) + .get_default_config() + .environment( + "env", + env_config={ + "num_agents": args.num_agents, + # Probability to crash during step(). + "p_crash": 0.0001, + # Probability to crash during reset(). + "p_crash_reset": 0.001, + "crash_on_worker_indices": [1, 2], + "init_time_s": 2.0, + # Probability to stall during step(). + "p_stall": 0.0005, + # Probability to stall during reset(). + "p_stall_reset": 0.001, + # Stall from 2 to 5sec (or 0.0 if --stall not set). + "stall_time_sec": (2, 5) if args.stall else 0.0, + # EnvRunner indices to stall on. + "stall_on_worker_indices": [2, 3], + }, + ) + # Switch on resiliency. + .fault_tolerance( + # Recreate any failed EnvRunners. + restart_failed_env_runners=True, + # Restart any failed environment (w/o recreating the EnvRunner). Note that + # this is the much faster option. + restart_failed_sub_environments=args.restart_failed_envs, + ) + ) + + # Use more stabilizing hyperparams for APPO. + if args.algo == "APPO": + base_config.training( + grad_clip=40.0, + entropy_coeff=0.0, + vf_loss_coeff=0.05, + ) + base_config.rl_module( + model_config=DefaultModelConfig(vf_share_layers=True), + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + run_rllib_example_script_experiment(base_config, args=args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01013495959b623c76c3dc5e4273fd7c9464a81e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/float16_training_and_inference.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/float16_training_and_inference.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22592860b4e6177a9814ae2c35e2078aca8b55ba Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/float16_training_and_inference.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/fractional_gpus_per_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/fractional_gpus_per_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7697fd6d01abae74bda5d0e8c538c0433042873 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/fractional_gpus_per_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/gpus_on_env_runners.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/gpus_on_env_runners.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14490eb1bf1f907feeebc2eda0aa07d3050691e7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/gpus_on_env_runners.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/mixed_precision_training_float16_inference.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/mixed_precision_training_float16_inference.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55a4ba411f3d6384500a4abd01eee70700a9cbd9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/__pycache__/mixed_precision_training_float16_inference.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/float16_training_and_inference.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/float16_training_and_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..be065b6f8f73fe325e71258c1965be1a5c833fb3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/float16_training_and_inference.py @@ -0,0 +1,251 @@ +"""Example of using float16 precision for training and inference. + +This example: + - shows how to write a custom callback for RLlib to convert all RLModules + (on the EnvRunners and Learners) to float16 precision. + - shows how to write a custom env-to-module ConnectorV2 piece to convert all + observations and rewards in the collected trajectories to float16 (numpy) arrays. + - shows how to write a custom grad scaler for torch that is necessary to stabilize + learning with float16 weight matrices and gradients. This custom scaler behaves + exactly like the torch built-in `torch.amp.GradScaler` but also works for float16 + gradients (which the torch built-in one doesn't). + - shows how to write a custom TorchLearner to change the epsilon setting (to the + much larger 1e-4 to stabilize learning) on the default optimizer (Adam) registered + for each RLModule. + - demonstrates how to plug in all the above custom components into an + `AlgorithmConfig` instance and start training (and inference) with float16 + precision. + + +How to run this script +---------------------- +`python [script file name].py + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- +You should see something similar to the following on your terminal, when running this +script with the above recommended options: + ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_437ee_00000 | TERMINATED | 127.0.0.1:81045 | 6 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_episodes_lifetime | +| | | | +|------------------+------------------------+------------------------+ +| 71.3123 | 153.79 | 358 | ++------------------+------------------------+------------------------+ +""" +import gymnasium as gym +import numpy as np +import torch + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import PPOTorchLearner +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_iters=50, default_reward=150.0, default_timesteps=100000 +) + + +def on_algorithm_init( + algorithm: Algorithm, + **kwargs, +) -> None: + """Callback making sure that all RLModules in the algo are `half()`'ed.""" + + # Switch all Learner RLModules to float16. + algorithm.learner_group.foreach_learner( + lambda learner: learner.module.foreach_module(lambda mid, mod: mod.half()) + ) + # Switch all EnvRunner RLModules (assuming single RLModules) to float16. + algorithm.env_runner_group.foreach_env_runner( + lambda env_runner: env_runner.module.half() + ) + if algorithm.eval_env_runner_group: + algorithm.eval_env_runner_group.foreach_env_runner( + lambda env_runner: env_runner.module.half() + ) + + +class WriteObsAndRewardsAsFloat16(ConnectorV2): + """ConnectorV2 piece preprocessing observations and rewards to be float16. + + Note that users can also write a gymnasium.Wrapper for observations and rewards + to achieve the same thing. + """ + + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ): + return gym.spaces.Box( + input_observation_space.low.astype(np.float16), + input_observation_space.high.astype(np.float16), + input_observation_space.shape, + np.float16, + ) + + def __call__(self, *, rl_module, batch, episodes, **kwargs): + for sa_episode in self.single_agent_episode_iterator(episodes): + obs = sa_episode.get_observations(-1) + float16_obs = obs.astype(np.float16) + sa_episode.set_observations(new_data=float16_obs, at_indices=-1) + if len(sa_episode) > 0: + rew = sa_episode.get_rewards(-1).astype(np.float16) + sa_episode.set_rewards(new_data=rew, at_indices=-1) + return batch + + +class Float16GradScaler: + """Custom grad scaler for `TorchLearner`. + + This class is utilizing the experimental support for the `TorchLearner`'s support + for loss/gradient scaling (analogous to how a `torch.amp.GradScaler` would work). + + TorchLearner performs the following steps using this class (`scaler`): + - loss_per_module = TorchLearner.compute_losses() + - for L in loss_per_module: L = scaler.scale(L) + - grads = TorchLearner.compute_gradients() # L.backward() on scaled loss + - TorchLearner.apply_gradients(grads): + for optim in optimizers: + scaler.step(optim) # <- grads should get unscaled + scaler.update() # <- update scaling factor + """ + + def __init__( + self, + init_scale=1000.0, + growth_factor=2.0, + backoff_factor=0.5, + growth_interval=2000, + ): + self._scale = init_scale + self.growth_factor = growth_factor + self.backoff_factor = backoff_factor + self.growth_interval = growth_interval + self._found_inf_or_nan = False + self.steps_since_growth = 0 + + def scale(self, loss): + # Scale the loss by `self._scale`. + return loss * self._scale + + def get_scale(self): + return self._scale + + def step(self, optimizer): + # Unscale the gradients for all model parameters and apply. + for group in optimizer.param_groups: + for param in group["params"]: + if param.grad is not None: + param.grad.data.div_(self._scale) + if torch.isinf(param.grad).any() or torch.isnan(param.grad).any(): + self._found_inf_or_nan = True + break + if self._found_inf_or_nan: + break + # Only step if no inf/NaN grad found. + if not self._found_inf_or_nan: + optimizer.step() + + def update(self): + # If gradients are found to be inf/NaN, reduce the scale. + if self._found_inf_or_nan: + self._scale *= self.backoff_factor + self.steps_since_growth = 0 + # Increase the scale after a set number of steps without inf/NaN. + else: + self.steps_since_growth += 1 + if self.steps_since_growth >= self.growth_interval: + self._scale *= self.growth_factor + self.steps_since_growth = 0 + # Reset inf/NaN flag. + self._found_inf_or_nan = False + + +class LargeEpsAdamTorchLearner(PPOTorchLearner): + """A TorchLearner overriding the default optimizer (Adam) to use non-default eps.""" + + @override(TorchLearner) + def configure_optimizers_for_module(self, module_id, config): + """Registers an Adam optimizer with a larg epsilon under the given module_id.""" + params = list(self._module[module_id].parameters()) + + # Register one Adam optimizer (under the default optimizer name: + # DEFAULT_OPTIMIZER) for the `module_id`. + self.register_optimizer( + module_id=module_id, + # Create an Adam optimizer with a different eps for better float16 + # stability. + optimizer=torch.optim.Adam(params, eps=1e-4), + params=params, + # Let RLlib handle the learning rate/learning rate schedule. + # You can leave `lr_or_lr_schedule` at None, but then you should + # pass a fixed learning rate into the Adam constructor above. + lr_or_lr_schedule=config.lr, + ) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("CartPole-v1") + # Plug in our custom callback (on_algorithm_init) to make all RLModules + # float16 models. + .callbacks(on_algorithm_init=on_algorithm_init) + # Plug in our custom loss scaler class to stabilize gradient computations + # (by scaling the loss, then unscaling the gradients before applying them). + # This is using the built-in, experimental feature of TorchLearner. + .experimental(_torch_grad_scaler_class=Float16GradScaler) + # Plug in our custom env-to-module ConnectorV2 piece to convert all observations + # and reward in the episodes (permanently) to float16. + .env_runners( + env_to_module_connector=( + lambda env, spaces, device: WriteObsAndRewardsAsFloat16() + ), + ) + .training( + # Plug in our custom TorchLearner (using a much larger, stabilizing epsilon + # on the Adam optimizer). + learner_class=LargeEpsAdamTorchLearner, + # Switch off grad clipping entirely b/c we use our custom grad scaler with + # built-in inf/nan detection (see `step` method of `Float16GradScaler`). + grad_clip=None, + # Typical CartPole-v1 hyperparams known to work well: + gamma=0.99, + lr=0.0003, + num_epochs=6, + vf_loss_coeff=0.01, + use_kl_loss=True, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/fractional_gpus_per_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/fractional_gpus_per_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..648e28e7816900b4eecc5b990ec479dc3904a009 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/fractional_gpus_per_learner.py @@ -0,0 +1,118 @@ +"""Example of using fractional GPUs (< 1.0) per Learner worker. + +The number of GPUs required, just for learning (excluding those maybe needed on your +EnvRunners, if applicable) can be computed by: +`num_gpus = config.num_learners * config.num_gpus_per_learner` + +This example: + - shows how to set up an Algorithm that uses one or more Learner workers ... + - ... and how to assign a fractional (< 1.0) number of GPUs to each of these Learners. + + +How to run this script +---------------------- +`python [script file name].py --num-learners= +[number of Learners, e.g. 1] --num-gpus-per-learner [some fraction <1.0]` + +The following command line combinations been tested on a 4 NVIDIA T4 GPUs (16 vCPU) +machine. +Note that for each run, 4 tune trials will be setup; see tune.grid_search over 4 +learning rates in the `base_config` below: +1) --num-learners=1 --num-gpus-per-learner=0.5 (2.0 GPUs used). +2) --num-learners=1 --num-gpus-per-learner=0.3 (1.2 GPUs used). +3) --num-learners=1 --num-gpus-per-learner=0.25 (1.0 GPU used). +4) --num-learners=2 --num-gpus-per-learner=1 (8 GPUs used). +5) non-sensical setting: --num-learners=2 --num-gpus-per-learner=0.5 (expect an +NCCL-related error due to the fact that torch will try to perform DDP sharding, +but notices that the shards sit on the same GPU). + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +Note that the shown GPU settings in this script also work in case you are not +running via tune, but instead are using the `--no-tune` command line option. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- +In the console output, you can see that only fractional GPUs are being used by RLlib: + +== Status == +... +Logical resource usage: 12.0/16 CPUs, 1.0/4 GPUs (...) +... +Number of trials: 4/4 (4 RUNNING) + +The final output should look something like this: ++-----------------------------+------------+-----------------+--------+--------+ +| Trial name | status | loc | lr | iter | +| | | | | | +|-----------------------------+------------+-----------------+--------+--------+ +| PPO_CartPole-v1_7104b_00000 | TERMINATED | 10.0.0.39:31197 | 0.005 | 10 | +| PPO_CartPole-v1_7104b_00001 | TERMINATED | 10.0.0.39:31202 | 0.003 | 11 | +| PPO_CartPole-v1_7104b_00002 | TERMINATED | 10.0.0.39:31203 | 0.001 | 10 | +| PPO_CartPole-v1_7104b_00003 | TERMINATED | 10.0.0.39:31204 | 0.0001 | 11 | ++-----------------------------+------------+-----------------+--------+--------+ + ++----------------+----------------------+----------------------+----------------------+ +| total time (s) | num_env_steps_sample | num_env_steps_traine | num_episodes_lifetim | +| | d_lifetime | d_lifetime | e | +|----------------+----------------------+----------------------+----------------------| +| 101.002 | 40000 | 40000 | 346 | +| 110.03 | 44000 | 44000 | 395 | +| 101.171 | 40000 | 40000 | 328 | +| 110.091 | 44000 | 44000 | 478 | ++----------------+----------------------+----------------------+----------------------+ +""" +from ray import tune +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_iters=50, default_reward=180, default_timesteps=100000 +) +parser.set_defaults( + num_env_runners=2, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + # This script only works on the new API stack. + .api_stack( + enable_rl_module_and_learner=True, + enable_env_runner_and_connector_v2=True, + ) + .environment("CartPole-v1") + # Define EnvRunner scaling. + .env_runners(num_env_runners=args.num_env_runners) + # Define Learner scaling. + .learners( + # How many Learner workers do we need? If you have more than 1 GPU, + # set this parameter to the number of GPUs available. + num_learners=args.num_learners, + # How many GPUs does each Learner need? If you have more than 1 GPU or only + # one Learner, you should set this to 1, otherwise, set this to some + # fraction. + num_gpus_per_learner=args.num_gpus_per_learner, + ) + # 4 tune trials altogether. + .training(lr=tune.grid_search([0.005, 0.003, 0.001, 0.0001])) + ) + + run_rllib_example_script_experiment(base_config, args, keep_config=True) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/gpus_on_env_runners.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/gpus_on_env_runners.py new file mode 100644 index 0000000000000000000000000000000000000000..fcaaf9cadbbb9d09be8552f4609f9e3c2fa20bd2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/gpus_on_env_runners.py @@ -0,0 +1,84 @@ +"""Example of using GPUs on the EnvRunners (b/c Env and/or RLModule require these). + +The number of GPUs required, just for your EnvRunners (excluding those needed for +training your RLModule) can be computed by: +`num_gpus = config.num_env_runners * config.num_gpus_per_env_runner` + +This example: + - shows how to write an Env that uses the GPU. + - shows how to configure your algorithm such that it allocates any number of GPUs + (including fractional < 1.0) to each (remote) EnvRunner worker. + + +How to run this script +---------------------- +`python [script file name].py --num-env_runners= +[number of EnvRunners, e.g. 2] --num-gpus-per-env-runner [int or some fraction <1.0]` + +The following command line combinations been tested on a 4 NVIDIA T4 GPUs (16 vCPU) +machine. +TODO (sven): Fix these +Note that for each run, 4 tune trials will be setup; see tune.grid_search over 4 +learning rates in the `base_config` below: +1) --num-learners=1 --num-gpus-per-learner=0.5 (2.0 GPUs used). +2) --num-learners=1 --num-gpus-per-learner=0.3 (1.2 GPUs used). +3) --num-learners=1 --num-gpus-per-learner=0.25 (1.0 GPU used). +4) non-sensical setting: --num-learners=2 --num-gpus-per-learner=0.5 (expect an +NCCL-related error due to the fact that torch will try to perform DDP sharding, +but notices that the shards sit on the same GPU). + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +Note that the shown GPU settings in this script also work in case you are not +running via tune, but instead are using the `--no-tune` command line option. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- +In the console output, you can see that only fractional GPUs are being used by RLlib: + +""" +from ray.rllib.examples.envs.classes.gpu_requiring_env import GPURequiringEnv +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_iters=50, default_reward=0.9, default_timesteps=100000 +) +parser.set_defaults( + num_env_runners=2, +) +parser.add_argument("--num-gpus-per-env-runner", type=float, default=0.5) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment(GPURequiringEnv) + # Define Learner scaling. + .env_runners( + # How many EnvRunner workers do we need? + num_env_runners=args.num_env_runners, + # How many GPUs does each EnvRunner require? Note that the memory on (a + # possibly fractional GPU) must be enough to accommodate the RLModule AND + # if applicable also the Env's GPU needs). + num_gpus_per_env_runner=args.num_gpus_per_env_runner, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/mixed_precision_training_float16_inference.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/mixed_precision_training_float16_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..ca733eb3af0e24270671d96530b2253a76925d4f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/gpus/mixed_precision_training_float16_inference.py @@ -0,0 +1,168 @@ +"""Example of using automatic mixed precision training on a torch RLModule. + +This example: + - shows how to write a custom callback for RLlib to convert those RLModules + only(!) on the EnvRunners to float16 precision. + - shows how to write a custom env-to-module ConnectorV2 piece to add float16 + observations to the action computing forward batch on the EnvRunners, but NOT + permanently write these changes into the episodes, such that on the + Learner side, the original float32 observations will be used (for the mixed + precision `forward_train` and `loss` computations). + - shows how to plugin torch's built-in `GradScaler` class to be used by the + TorchLearner to scale losses and unscale gradients in order to gain more stability + when training with mixed precision. + - shows how to write a custom TorchLearner to run the update step (overrides + `_update()`) within a `torch.amp.autocast()` context. This makes sure that . + - demonstrates how to plug in all the above custom components into an + `AlgorithmConfig` instance and start training with mixed-precision while + performing the inference on the EnvRunners with float16 precision. + + +How to run this script +---------------------- +`python [script file name].py + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +Note that the shown GPU settings in this script also work in case you are not +running via tune, but instead are using the `--no-tune` command line option. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- +In the console output, you should see something like this: + ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_485af_00000 | TERMINATED | 127.0.0.1:81045 | 22 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_episodes_lifetime | +| | | | +|------------------+------------------------+------------------------+ +| 281.3231 | 455.81 | 1426 | ++------------------+------------------------+------------------------+ +""" +import gymnasium as gym +import numpy as np +import torch + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import PPOTorchLearner +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + + +parser = add_rllib_example_script_args( + default_iters=200, default_reward=450.0, default_timesteps=200000 +) +parser.set_defaults( + algo="PPO", +) + + +def on_algorithm_init( + algorithm: Algorithm, + **kwargs, +) -> None: + """Callback making sure that all RLModules in the algo are `half()`'ed.""" + + # Switch all EnvRunner RLModules (assuming single RLModules) to float16. + algorithm.env_runner_group.foreach_env_runner( + lambda env_runner: env_runner.module.half() + ) + if algorithm.eval_env_runner_group: + algorithm.eval_env_runner_group.foreach_env_runner( + lambda env_runner: env_runner.module.half() + ) + + +class Float16Connector(ConnectorV2): + """ConnectorV2 piece preprocessing observations and rewards to be float16. + + Note that users can also write a gymnasium.Wrapper for observations and rewards + to achieve the same thing. + """ + + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ): + return gym.spaces.Box( + input_observation_space.low.astype(np.float16), + input_observation_space.high.astype(np.float16), + input_observation_space.shape, + np.float16, + ) + + def __call__(self, *, rl_module, batch, episodes, **kwargs): + for sa_episode in self.single_agent_episode_iterator(episodes): + obs = sa_episode.get_observations(-1) + float16_obs = obs.astype(np.float16) + self.add_batch_item( + batch, + column="obs", + item_to_add=float16_obs, + single_agent_episode=sa_episode, + ) + return batch + + +class PPOTorchMixedPrecisionLearner(PPOTorchLearner): + def _update(self, *args, **kwargs): + with torch.cuda.amp.autocast(): + results = super()._update(*args, **kwargs) + return results + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.algo == "PPO", "Must set --algo=PPO when running this script!" + + base_config = ( + (PPOConfig().environment("CartPole-v1")) + .env_runners( + env_to_module_connector=lambda env, spaces, device: Float16Connector() + ) + # Plug in our custom callback (on_algorithm_init) to make EnvRunner RLModules + # float16 models. + .callbacks(on_algorithm_init=on_algorithm_init) + # Plug in the torch built-int loss scaler class to stabilize gradient + # computations (by scaling the loss, then unscaling the gradients before + # applying them). This is using the built-in, experimental feature of + # TorchLearner. + .experimental(_torch_grad_scaler_class=torch.cuda.amp.GradScaler) + .training( + # Plug in the custom Learner class to activate mixed-precision training for + # our torch RLModule (uses `torch.amp.autocast()`). + learner_class=PPOTorchMixedPrecisionLearner, + # Switch off grad clipping entirely b/c we use our custom grad scaler with + # built-in inf/nan detection (see `step` method of `Float16GradScaler`). + grad_clip=None, + # Typical CartPole-v1 hyperparams known to work well: + gamma=0.99, + lr=0.0003, + num_epochs=6, + vf_loss_coeff=0.01, + use_kl_loss=True, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0e112543a93eb4be879c0dee276a79faae30138 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/__pycache__/hierarchical_training.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/__pycache__/hierarchical_training.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..757cf005734f59b411ad40d97cbdbe93c02096af Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/__pycache__/hierarchical_training.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/hierarchical_training.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/hierarchical_training.py new file mode 100644 index 0000000000000000000000000000000000000000..78926d75afdae0a816e455a0fa002983875d624f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/hierarchical/hierarchical_training.py @@ -0,0 +1,183 @@ +"""Example of running a hierarchichal training setup in RLlib using its multi-agent API. + +This example is very loosely based on this paper: +[1] Hierarchical RL Based on Subgoal Discovery and Subpolicy Specialization - +B. Bakker & J. Schmidhuber - 2003 + +The approach features one high level policy, which picks the next target state to be +reached by one of three low level policies as well as the actual low level policy to +take over control. +A low level policy - once chosen by the high level one - has up to 10 primitive +timesteps to reach the given target state. If it reaches it, both high level and low +level policy are rewarded and the high level policy takes another action (choses a new +target state and a new low level policy). +A global goal state must be reached to deem the overall task to be solved. Once one +of the lower level policies reaches that goal state, the high level policy receives +a large reward and the episode ends. +The approach utilizes the possibility for low level policies to specialize in reaching +certain sub-goals and the high level policy to know, which sub goals to pick next and +which "expert" (low level policy) to allow to reach the subgoal. + +This example: + - demonstrates how to write a relatively simple custom multi-agent environment and + have it behave, such that it mimics a hierarchical RL setup with higher- and lower + level agents acting on different abstract time axes (the higher level policy + only acts occasionally, picking a new lower level policy and the lower level + policies have each n primitive timesteps to reach the given target state, after + which control is handed back to the high level policy for the next pick). + - shows how to setup a plain multi-agent RL algo (here: PPO) to learn in this + hierarchical setup and solve tasks that are otherwise very difficult to solve + only with a single, primitive-action picking low level policy. + +We use the `SixRoomEnv` and `HierarchicalSixRoomEnv`, both sharing the same built-in +maps. The envs are similar to the FrozenLake-v1 env, but support walls (inner and outer) +through which the agent cannot walk. + + +How to run this script +---------------------- +`python [script file name].py --map=large --time-limit=50` + +Use the `--flat` option to disable the hierarchical setup and learn the simple (flat) +SixRoomEnv with only one policy. You should observe that it's much harder for the algo +to reach the global goal state in this setting. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only a PPO algorithm that uses hierarchical +training (`--flat` flag is NOT set) can actually learn with the command line options +`--map=large --time-limit=500 --max-steps-low-level=40 --num-low-level-agents=3`. + +4 policies in a hierarchical setup (1 high level "manager", 3 low level "experts"): ++---------------------+----------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|---------------------+----------+--------+------------------+ +| PPO_env_58b78_00000 | RUNNING | 100 | 278.23 | ++---------------------+----------+--------+------------------+ ++-------------------+--------------------------+---------------------------+ ... +| combined return | return high_level_policy | return low_level_policy_0 | +|-------------------+--------------------------+---------------------------+ ... +| -8.4 | -5.2 | -1.19 | ++-------------------+--------------------------+---------------------------+ ... +""" +from ray import tune +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.connectors.env_to_module.flatten_observations import FlattenObservations +from ray.rllib.examples.envs.classes.six_room_env import ( + HierarchicalSixRoomEnv, + SixRoomEnv, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +parser = add_rllib_example_script_args( + default_reward=7.0, + default_timesteps=4000000, + default_iters=800, +) +parser.add_argument( + "--flat", + action="store_true", + help="Use the non-hierarchical, single-agent flat `SixRoomEnv` instead.", +) +parser.add_argument( + "--map", + type=str, + choices=["small", "medium", "large"], + default="medium", + help="The built-in map to use.", +) +parser.add_argument( + "--time-limit", + type=int, + default=100, + help="The max. number of (primitive) timesteps per episode.", +) +parser.add_argument( + "--max-steps-low-level", + type=int, + default=15, + help="The max. number of steps a low-level policy can take after having been " + "picked by the high level policy. After this number of timesteps, control is " + "handed back to the high-level policy (to pick a next goal position plus the next " + "low level policy).", +) +parser.add_argument( + "--num-low-level-agents", + type=int, + default=3, + help="The number of low-level agents/policies to use.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Run the flat (non-hierarchical env). + if args.flat: + cls = SixRoomEnv + # Run in hierarchical mode. + else: + cls = HierarchicalSixRoomEnv + + tune.register_env("env", lambda cfg: cls(config=cfg)) + + base_config = ( + PPOConfig() + .environment( + "env", + env_config={ + "map": args.map, + "max_steps_low_level": args.max_steps_low_level, + "time_limit": args.time_limit, + "num_low_level_agents": args.num_low_level_agents, + }, + ) + .env_runners( + # num_envs_per_env_runner=10, + env_to_module_connector=( + lambda env, spaces, device: ( + FlattenObservations(multi_agent=not args.flat) + ) + ), + ) + .training( + train_batch_size_per_learner=4000, + minibatch_size=512, + lr=0.0003, + num_epochs=20, + entropy_coeff=0.025, + ) + ) + + # Configure a proper multi-agent setup for the hierarchical env. + if not args.flat: + + def policy_mapping_fn(agent_id, episode, **kwargs): + # Map each low level agent to its respective (low-level) policy. + if agent_id.startswith("low_level_"): + return f"low_level_policy_{agent_id[-1]}" + # Map the high level agent to the high level policy. + else: + return "high_level_policy" + + base_config.multi_agent( + policy_mapping_fn=policy_mapping_fn, + policies={"high_level_policy"} + | {f"low_level_policy_{i}" for i in range(args.num_low_level_agents)}, + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c4ab7fb0c7f760beeccc1019120ed9b9f6815a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa32056ddccbdc43ca4c9d3d15494962446a12c7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_w_connector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_w_connector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4780a9456615ee38dea36953cb42f62cde3158fb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_w_connector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_with_attention.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_with_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0d3508a9a205345032f90d174b944e70b5460e7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_with_attention.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_with_lstm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_with_lstm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b64936e962835f614cbf8c54bc69ac6b87c2af94 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/__pycache__/policy_inference_after_training_with_lstm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training.py new file mode 100644 index 0000000000000000000000000000000000000000..5cae0fdb077df05c388ad7f4844598d7bbca55ea --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training.py @@ -0,0 +1,234 @@ +"""Example on how to compute actions in production on an already trained policy. + +This example uses the simplest setup possible: An RLModule (policy net) recovered +from a checkpoint and a manual env-loop (CartPole-v1). No ConnectorV2s or EnvRunners are +used in this example. + +This example: + - shows how to use an already existing checkpoint to extract a single-agent RLModule + from (our policy network). + - shows how to setup this recovered policy net for action computations (with or + without using exploration). + - shows have the policy run through a very simple gymnasium based env-loop, w/o + using RLlib's ConnectorV2s or EnvRunners. + + +How to run this script +---------------------- +`python [script file name].py --stop-reward=200.0` + +Use the `--use-onnx-for-inference` option to perform action computations after training +through an ONNX runtime session. +Use the `--explore-during-inference` option to switch on exploratory behavior +during inference. Normally, you should not explore during inference, though, +unless your environment has a stochastic optimal solution. Note also that this option +doesn't work in combination with the `--use-onnx-for-inference` option. +Use the `--num-episodes-during-inference=[int]` option to set the number of +episodes to run through during the inference phase using the restored RLModule. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +Note that the shown GPU settings in this script also work in case you are not +running via tune, but instead are using the `--no-tune` command line option. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- + +For the training step - depending on your `--stop-reward` setting, you should see +something similar to this: + +Number of trials: 1/1 (1 TERMINATED) ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_6660c_00000 | TERMINATED | 127.0.0.1:43566 | 8 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | num_env_steps_sample | num_env_steps_traine | +| | d_lifetime | d_lifetime | ++------------------+------------------------+------------------------+ +| 21.0283 | 32000 | 32000 | ++------------------+------------------------+------------------------+ + +Then, after restoring the RLModule for the inference phase, your output should +look similar to: + +Training completed. Restoring new RLModule for action inference. +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Episode done: Total reward = 500.0 +Done performing action inference through 10 Episodes +""" +import os + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import convert_to_numpy, softmax +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +torch, _ = try_import_torch() + +parser = add_rllib_example_script_args(default_reward=200.0) +parser.add_argument( + "--use-onnx-for-inference", + action="store_true", + help="Whether to convert the loaded module to ONNX format and then perform " + "inference through this ONNX model.", +) +parser.add_argument( + "--explore-during-inference", + action="store_true", + help="Whether the trained policy should use exploration during action " + "inference.", +) +parser.add_argument( + "--num-episodes-during-inference", + type=int, + default=10, + help="Number of episodes to do inference over (after restoring from a checkpoint).", +) +parser.set_defaults( + # Make sure that - by default - we produce checkpoints during training. + checkpoint_freq=1, + checkpoint_at_end=True, + # Use CartPole-v1 by default. + env="CartPole-v1", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + if args.use_onnx_for_inference: + if args.explore_during_inference: + raise ValueError( + "Can't set `--explore-during-inference` and `--use-onnx-for-inference` " + "together! ONNX models use the original RLModule's `forward_inference` " + "only." + ) + import onnxruntime + + base_config = get_trainable_cls(args.algo).get_default_config() + + print("Training policy until desired reward/timesteps/iterations. ...") + results = run_rllib_example_script_experiment(base_config, args) + + print("Training completed. Restoring new RLModule for action inference.") + # Get the last checkpoint from the above training run. + best_result = results.get_best_result( + metric=f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}", mode="max" + ) + + # Create new RLModule and restore its state from the last algo checkpoint. + # Note that the checkpoint for the RLModule can be found deeper inside the algo + # checkpoint's subdirectories ([algo dir] -> "learner/" -> "module_state/" -> + # "[module ID]): + print("Restore RLModule from checkpoint ...", end="") + rl_module = RLModule.from_checkpoint( + os.path.join( + best_result.checkpoint.path, + "learner_group", + "learner", + "rl_module", + DEFAULT_MODULE_ID, + ) + ) + ort_session = None + print(" ok") + + # Create an env to do inference in. + env = gym.make(args.env) + obs, info = env.reset() + + num_episodes = 0 + episode_return = 0.0 + + while num_episodes < args.num_episodes_during_inference: + # Compute an action using a B=1 observation "batch". + input_dict = {Columns.OBS: np.expand_dims(obs, 0)} + if not args.use_onnx_for_inference: + input_dict = {Columns.OBS: torch.from_numpy(obs).unsqueeze(0)} + + # If ONNX and module has not been exported yet, do this here using + # the input_dict as example input. + elif ort_session is None: + tensor_input_dict = {Columns.OBS: torch.from_numpy(obs).unsqueeze(0)} + torch.onnx.export(rl_module, {"batch": tensor_input_dict}, f="test.onnx") + ort_session = onnxruntime.InferenceSession( + "test.onnx", providers=["CPUExecutionProvider"] + ) + + # No exploration (using ONNX). + if ort_session is not None: + rl_module_out = ort_session.run( + None, + { + key.name: val + for key, val in dict( + zip( + tree.flatten(ort_session.get_inputs()), + tree.flatten(input_dict), + ) + ).items() + }, + ) + # [0]=encoder outs; [1]=action logits + rl_module_out = {Columns.ACTION_DIST_INPUTS: rl_module_out[1]} + # No exploration (using RLModule). + elif not args.explore_during_inference: + rl_module_out = rl_module.forward_inference(input_dict) + # W/ exploration (using RLModule). + else: + rl_module_out = rl_module.forward_exploration(input_dict) + + # For discrete action spaces used here, normally, an RLModule "only" + # produces action logits, from which we then have to sample. + # However, you can also write custom RLModules that output actions + # directly, performing the sampling step already inside their + # `forward_...()` methods. + logits = convert_to_numpy(rl_module_out[Columns.ACTION_DIST_INPUTS]) + # Perform the sampling step in numpy for simplicity. + action = np.random.choice(env.action_space.n, p=softmax(logits[0])) + # Send the computed action `a` to the env. + obs, reward, terminated, truncated, _ = env.step(action) + episode_return += reward + # Is the episode `done`? -> Reset. + if terminated or truncated: + print(f"Episode done: Total reward = {episode_return}") + obs, info = env.reset() + num_episodes += 1 + episode_return = 0.0 + + print(f"Done performing action inference through {num_episodes} Episodes") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_w_connector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_w_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..f006ea21f0cbb99ee8d6c16b8c31fc0969876f59 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_w_connector.py @@ -0,0 +1,331 @@ +"""Example on how to compute actions in production on an already trained policy. + +This example uses a more complex setup including a gymnasium environment, an +RLModule (one or more neural networks/policies), an env-to-module/module-to-env +ConnectorV2 pair, and an Episode object to store the ongoing episode in. +The RLModule contains an LSTM that requires its own previous STATE_OUT as new input +at every episode step to compute a new action. + +This example: + - shows how to use an already existing checkpoint to extract a single-agent RLModule + from (our policy network). + - shows how to setup this recovered policy net for action computations (with or + without using exploration). + - shows how to create a more complex env-loop in which the action-computing RLModule + requires its own previous state outputs as new input and how to use RLlib's Episode + APIs to achieve this. + + +How to run this script +---------------------- +`python [script file name].py --stop-reward=200.0` + +Use the `--use-onnx-for-inference` option to perform action computations after training +through an ONNX runtime session. +Use the `--explore-during-inference` option to switch on exploratory behavior +during inference. Normally, you should not explore during inference, though, +unless your environment has a stochastic optimal solution. Note also that this option +doesn't work in combination with the `--use-onnx-for-inference` option. +Use the `--num-episodes-during-inference=[int]` option to set the number of +episodes to run through during the inference phase using the restored RLModule. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +Note that the shown GPU settings in this script also work in case you are not +running via tune, but instead are using the `--no-tune` command line option. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- + +For the training step - depending on your `--stop-reward` setting, you should see +something similar to this: + +Number of trials: 1/1 (1 TERMINATED) ++--------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|--------------------------------+------------+-----------------+--------+ +| PPO_stateless-cart_cc890_00000 | TERMINATED | 127.0.0.1:72238 | 7 | ++--------------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | num_env_steps_sample | num_env_steps_traine | +| | d_lifetime | d_lifetime | ++------------------+------------------------+------------------------+ +| 31.9655 | 28000 | 28000 | ++------------------+------------------------+------------------------+ + +Then, after restoring the RLModule for the inference phase, your output should +look similar to: + +Training completed. Creating an env-loop for inference ... +Env ... +Env-to-module ConnectorV2 ... +RLModule restored ... +Module-to-env ConnectorV2 ... +Episode done: Total reward = 103.0 +Episode done: Total reward = 90.0 +Episode done: Total reward = 100.0 +Episode done: Total reward = 111.0 +Episode done: Total reward = 85.0 +Episode done: Total reward = 90.0 +Episode done: Total reward = 100.0 +Episode done: Total reward = 102.0 +Episode done: Total reward = 97.0 +Episode done: Total reward = 81.0 +Done performing action inference through 10 Episodes +""" +import os + +import tree # pip install dm_tree + +from ray.rllib.connectors.env_to_module import EnvToModulePipeline +from ray.rllib.connectors.module_to_env import ModuleToEnvPipeline +from ray.rllib.core import ( + COMPONENT_ENV_RUNNER, + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + COMPONENT_LEARNER_GROUP, + COMPONENT_LEARNER, + COMPONENT_RL_MODULE, + DEFAULT_MODULE_ID, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.examples.envs.classes.stateless_cartpole import StatelessCartPole +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +torch, _ = try_import_torch() + + +def _env_creator(cfg): + return StatelessCartPole(cfg) + + +register_env("stateless-cart", _env_creator) + + +parser = add_rllib_example_script_args(default_reward=200.0) +parser.add_argument( + "--use-onnx-for-inference", + action="store_true", + help="Whether to convert the loaded module to ONNX format and then perform " + "inference through this ONNX model.", +) +parser.add_argument( + "--explore-during-inference", + action="store_true", + help="Whether the trained policy should use exploration during action " + "inference.", +) +parser.add_argument( + "--num-episodes-during-inference", + type=int, + default=10, + help="Number of episodes to do inference over (after restoring from a checkpoint).", +) +parser.set_defaults( + # Make sure that - by default - we produce checkpoints during training. + checkpoint_freq=1, + checkpoint_at_end=True, + # Use StatelessCartPole by default. + env="stateless-cart", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + if args.use_onnx_for_inference: + if args.explore_during_inference: + raise ValueError( + "Can't set `--explore-during-inference` and `--use-onnx-for-inference` " + "together! ONNX models use the original RLModule's `forward_inference` " + "only." + ) + import onnxruntime + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .training( + num_epochs=6, + lr=0.0003, + vf_loss_coeff=0.01, + ) + # Add an LSTM setup to the default RLModule used. + .rl_module(model_config=DefaultModelConfig(use_lstm=True)) + ) + + print("Training LSTM-policy until desired reward/timesteps/iterations. ...") + results = run_rllib_example_script_experiment(base_config, args) + + # Get the last checkpoint from the above training run. + metric_key = metric = f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + best_result = results.get_best_result(metric=metric_key, mode="max") + + print( + "Training completed (R=" + f"{best_result.metrics[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]}). " + "Creating an env-loop for inference ..." + ) + + print("Env ...", end="") + env = _env_creator(base_config.env_config) + print(" ok") + + # Create the env-to-module pipeline from the checkpoint. + print("Restore env-to-module connector from checkpoint ...", end="") + env_to_module = EnvToModulePipeline.from_checkpoint( + os.path.join( + best_result.checkpoint.path, + COMPONENT_ENV_RUNNER, + COMPONENT_ENV_TO_MODULE_CONNECTOR, + ) + ) + # For ONNX, we remove the NumpyToTensor connector piece from the pipeline, + # because ONNX operates only on numpy arrays. + if args.use_onnx_for_inference: + env_to_module.remove("NumpyToTensor") + print(" ok") + + print("Restore RLModule from checkpoint ...", end="") + # Create RLModule from a checkpoint. + rl_module = RLModule.from_checkpoint( + os.path.join( + best_result.checkpoint.path, + COMPONENT_LEARNER_GROUP, + COMPONENT_LEARNER, + COMPONENT_RL_MODULE, + DEFAULT_MODULE_ID, + ) + ) + ort_session = None + print(" ok") + + # For the module-to-env pipeline, we will use the convenient config utility. + print("Restore module-to-env connector from checkpoint ...", end="") + module_to_env = ModuleToEnvPipeline.from_checkpoint( + os.path.join( + best_result.checkpoint.path, + COMPONENT_ENV_RUNNER, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + ) + ) + print(" ok") + + # Now our setup is complete: + # [gym.Env] -> env-to-module -> [RLModule] -> module-to-env -> [gym.Env] ... repeat + num_episodes = 0 + + obs, _ = env.reset() + episode = SingleAgentEpisode( + observations=[obs], + observation_space=env.observation_space, + action_space=env.action_space, + ) + + while num_episodes < args.num_episodes_during_inference: + shared_data = {} + input_dict = env_to_module( + episodes=[episode], # ConnectorV2 pipelines operate on lists of episodes. + rl_module=rl_module, + explore=args.explore_during_inference, + shared_data=shared_data, + ) + + # If ONNX and module has not been exported yet, do this here using + # the input_dict as example input. + if args.use_onnx_for_inference and ort_session is None: + tensor_input_dict = tree.map_structure( + lambda s: torch.from_numpy(s), input_dict + ) + torch.onnx.export(rl_module, {"batch": tensor_input_dict}, f="test.onnx") + ort_session = onnxruntime.InferenceSession( + "test.onnx", providers=["CPUExecutionProvider"] + ) + + # No exploration (using ONNX). + if ort_session is not None: + rl_module_out = ort_session.run( + None, + { + key.name: val + for key, val in dict( + zip( + tree.flatten(ort_session.get_inputs()), + tree.flatten(input_dict), + ) + ).items() + }, + ) + # [0] and [1]: LSTM states; [2]=encoder outs; [3]=action logits + rl_module_out = { + Columns.STATE_OUT: { + "h": torch.from_numpy(rl_module_out[0]), + "c": torch.from_numpy(rl_module_out[1]), + }, + Columns.ACTION_DIST_INPUTS: torch.from_numpy(rl_module_out[3]), + } + # No exploration (using RLModule). + elif not args.explore_during_inference: + rl_module_out = rl_module.forward_inference(input_dict) + # W/ exploration (using RLModule). + else: + rl_module_out = rl_module.forward_exploration(input_dict) + + to_env = module_to_env( + batch=rl_module_out, + episodes=[episode], # ConnectorV2 pipelines operate on lists of episodes. + rl_module=rl_module, + explore=args.explore_during_inference, + shared_data=shared_data, + ) + # Send the computed action to the env. Note that the RLModule and the + # connector pipelines work on batched data (B=1 in this case), whereas the Env + # is not vectorized here, so we need to use `action[0]`. + action = to_env.pop(Columns.ACTIONS)[0] + obs, reward, terminated, truncated, _ = env.step(action) + # Keep our `SingleAgentEpisode` instance updated at all times. + episode.add_env_step( + obs, + action, + reward, + terminated=terminated, + truncated=truncated, + # Same here: [0] b/c RLModule output is batched (w/ B=1). + extra_model_outputs={k: v[0] for k, v in to_env.items()}, + ) + + # Is the episode `done`? -> Reset. + if episode.is_done: + print(f"Episode done: Total reward = {episode.get_return()}") + obs, info = env.reset() + episode = SingleAgentEpisode( + observations=[obs], + observation_space=env.observation_space, + action_space=env.action_space, + ) + num_episodes += 1 + + print(f"Done performing action inference through {num_episodes} Episodes") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_with_attention.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_with_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..b67c806cd1e2d223381ed8a2ed7686bfcaddc6b8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_with_attention.py @@ -0,0 +1,196 @@ +# @OldAPIStack +""" +Example showing how you can use your trained policy for inference +(computing actions) in an environment. + +Includes options for LSTM-based models (--use-lstm), attention-net models +(--use-attention), and plain (non-recurrent) models. +""" +import argparse +import gymnasium as gym +import numpy as np +import os + +import ray +from ray import tune +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.tune.registry import get_trainable_cls +from ray.tune.result import TRAINING_ITERATION + +parser = argparse.ArgumentParser() +parser.add_argument( + "--run", type=str, default="PPO", help="The RLlib-registered algorithm to use." +) +parser.add_argument("--num-cpus", type=int, default=0) +parser.add_argument( + "--framework", + choices=["tf", "tf2", "torch"], + default="torch", + help="The DL framework specifier.", +) +parser.add_argument( + "--prev-n-actions", + type=int, + default=0, + help="Feed n most recent actions to the attention net as part of its input.", +) +parser.add_argument( + "--prev-n-rewards", + type=int, + default=0, + help="Feed n most recent rewards to the attention net as part of its input.", +) +parser.add_argument( + "--stop-iters", + type=int, + default=200, + help="Number of iterations to train before we do inference.", +) +parser.add_argument( + "--stop-timesteps", + type=int, + default=100000, + help="Number of timesteps to train before we do inference.", +) +parser.add_argument( + "--stop-reward", + type=float, + default=150.0, + help="Reward at which we stop training before we do inference.", +) +parser.add_argument( + "--explore-during-inference", + action="store_true", + help="Whether the trained policy should use exploration during action " + "inference.", +) +parser.add_argument( + "--num-episodes-during-inference", + type=int, + default=10, + help="Number of episodes to do inference over after training.", +) + +if __name__ == "__main__": + args = parser.parse_args() + + ray.init(num_cpus=args.num_cpus or None) + + config = ( + get_trainable_cls(args.run) + .get_default_config() + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .environment("FrozenLake-v1") + # Run with tracing enabled for tf2? + .framework(args.framework) + .training( + model={ + "use_attention": True, + "attention_num_transformer_units": 1, + "attention_use_n_prev_actions": args.prev_n_actions, + "attention_use_n_prev_rewards": args.prev_n_rewards, + "attention_dim": 32, + "attention_memory_inference": 10, + "attention_memory_training": 10, + }, + ) + # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0. + .resources(num_gpus=int(os.environ.get("RLLIB_NUM_GPUS", "0"))) + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + + print("Training policy until desired reward/timesteps/iterations. ...") + tuner = tune.Tuner( + args.run, + param_space=config, + run_config=tune.RunConfig( + stop=stop, + verbose=2, + checkpoint_config=tune.CheckpointConfig( + checkpoint_frequency=1, + checkpoint_at_end=True, + ), + ), + ) + results = tuner.fit() + + print("Training completed. Restoring new Algorithm for action inference.") + # Get the last checkpoint from the above training run. + checkpoint = results.get_best_result().checkpoint + # Create new Algorithm and restore its state from the last checkpoint. + algo = Algorithm.from_checkpoint(checkpoint) + + # Create the env to do inference in. + env = gym.make("FrozenLake-v1") + obs, info = env.reset() + + # In case the model needs previous-reward/action inputs, keep track of + # these via these variables here (we'll have to pass them into the + # compute_actions methods below). + init_prev_a = prev_a = None + init_prev_r = prev_r = None + + # Set attention net's initial internal state. + num_transformers = config["model"]["attention_num_transformer_units"] + memory_inference = config["model"]["attention_memory_inference"] + attention_dim = config["model"]["attention_dim"] + init_state = state = [ + np.zeros([memory_inference, attention_dim], np.float32) + for _ in range(num_transformers) + ] + # Do we need prev-action/reward as part of the input? + if args.prev_n_actions: + init_prev_a = prev_a = np.array([0] * args.prev_n_actions) + if args.prev_n_rewards: + init_prev_r = prev_r = np.array([0.0] * args.prev_n_rewards) + + num_episodes = 0 + + while num_episodes < args.num_episodes_during_inference: + # Compute an action (`a`). + a, state_out, _ = algo.compute_single_action( + observation=obs, + state=state, + prev_action=prev_a, + prev_reward=prev_r, + explore=args.explore_during_inference, + policy_id="default_policy", # <- default value + ) + # Send the computed action `a` to the env. + obs, reward, done, truncated, _ = env.step(a) + # Is the episode `done`? -> Reset. + if done: + obs, info = env.reset() + num_episodes += 1 + state = init_state + prev_a = init_prev_a + prev_r = init_prev_r + # Episode is still ongoing -> Continue. + else: + # Append the just received state-out (most recent timestep) to the + # cascade (memory) of our state-ins and drop the oldest state-in. + state = [ + np.concatenate([state[i], [state_out[i]]], axis=0)[1:] + for i in range(num_transformers) + ] + if init_prev_a is not None: + prev_a = a + if init_prev_r is not None: + prev_r = reward + + algo.stop() + + ray.shutdown() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_with_lstm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_with_lstm.py new file mode 100644 index 0000000000000000000000000000000000000000..950e88ceee892ec84625f2cf523a45ce56378ee2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/inference/policy_inference_after_training_with_lstm.py @@ -0,0 +1,185 @@ +# @OldAPIStack +""" +Example showing how you can use your trained policy for inference +(computing actions) in an environment. + +Includes options for LSTM-based models (--use-lstm), attention-net models +(--use-attention), and plain (non-recurrent) models. +""" +import argparse +import gymnasium as gym +import numpy as np +import os + +import ray +from ray import tune +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.tune.registry import get_trainable_cls +from ray.tune.result import TRAINING_ITERATION + +parser = argparse.ArgumentParser() +parser.add_argument( + "--run", type=str, default="PPO", help="The RLlib-registered algorithm to use." +) +parser.add_argument("--num-cpus", type=int, default=0) +parser.add_argument( + "--framework", + choices=["tf", "tf2", "torch"], + default="torch", + help="The DL framework specifier.", +) +parser.add_argument( + "--prev-action", + action="store_true", + help="Feed most recent action to the LSTM as part of its input.", +) +parser.add_argument( + "--prev-reward", + action="store_true", + help="Feed most recent reward to the LSTM as part of its input.", +) +parser.add_argument( + "--stop-iters", + type=int, + default=2, + help="Number of iterations to train before we do inference.", +) +parser.add_argument( + "--stop-timesteps", + type=int, + default=100000, + help="Number of timesteps to train before we do inference.", +) +parser.add_argument( + "--stop-reward", + type=float, + default=0.8, + help="Reward at which we stop training before we do inference.", +) +parser.add_argument( + "--explore-during-inference", + action="store_true", + help="Whether the trained policy should use exploration during action " + "inference.", +) +parser.add_argument( + "--num-episodes-during-inference", + type=int, + default=10, + help="Number of episodes to do inference over after training.", +) + +if __name__ == "__main__": + args = parser.parse_args() + + ray.init(num_cpus=args.num_cpus or None) + + config = ( + get_trainable_cls(args.run) + .get_default_config() + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .environment("FrozenLake-v1") + # Run with tracing enabled for tf2? + .framework(args.framework) + .training( + model={ + "use_lstm": True, + "lstm_cell_size": 256, + "lstm_use_prev_action": args.prev_action, + "lstm_use_prev_reward": args.prev_reward, + }, + ) + # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0. + .resources(num_gpus=int(os.environ.get("RLLIB_NUM_GPUS", "0"))) + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + + print("Training policy until desired reward/timesteps/iterations. ...") + tuner = tune.Tuner( + args.run, + param_space=config, + run_config=tune.RunConfig( + stop=stop, + verbose=2, + checkpoint_config=tune.CheckpointConfig( + checkpoint_frequency=1, + checkpoint_at_end=True, + ), + ), + ) + results = tuner.fit() + + print("Training completed. Restoring new Algorithm for action inference.") + # Get the last checkpoint from the above training run. + checkpoint = results.get_best_result().checkpoint + # Create new Algorithm from the last checkpoint. + algo = Algorithm.from_checkpoint(checkpoint) + + # Create the env to do inference in. + env = gym.make("FrozenLake-v1") + obs, info = env.reset() + + # In case the model needs previous-reward/action inputs, keep track of + # these via these variables here (we'll have to pass them into the + # compute_actions methods below). + init_prev_a = prev_a = None + init_prev_r = prev_r = None + + # Set LSTM's initial internal state. + lstm_cell_size = config["model"]["lstm_cell_size"] + # range(2) b/c h- and c-states of the LSTM. + if algo.config.enable_rl_module_and_learner: + init_state = state = algo.get_policy().model.get_initial_state() + else: + init_state = state = [np.zeros([lstm_cell_size], np.float32) for _ in range(2)] + # Do we need prev-action/reward as part of the input? + if args.prev_action: + init_prev_a = prev_a = 0 + if args.prev_reward: + init_prev_r = prev_r = 0.0 + + num_episodes = 0 + + while num_episodes < args.num_episodes_during_inference: + # Compute an action (`a`). + a, state_out, _ = algo.compute_single_action( + observation=obs, + state=state, + prev_action=prev_a, + prev_reward=prev_r, + explore=args.explore_during_inference, + policy_id="default_policy", # <- default value + ) + # Send the computed action `a` to the env. + obs, reward, done, truncated, info = env.step(a) + # Is the episode `done`? -> Reset. + if done: + obs, info = env.reset() + num_episodes += 1 + state = init_state + prev_a = init_prev_a + prev_r = init_prev_r + # Episode is still ongoing -> Continue. + else: + state = state_out + if init_prev_a is not None: + prev_a = a + if init_prev_r is not None: + prev_r = reward + + algo.stop() + + ray.shutdown() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4dd43d73ae3c055497bd4411e710740fcd6b685 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/ppo_with_custom_loss_fn.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/ppo_with_custom_loss_fn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38a537bae467578ead434a9f9089e38dab5a3908 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/ppo_with_custom_loss_fn.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/ppo_with_torch_lr_schedulers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/ppo_with_torch_lr_schedulers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5731a9e3305c7af3bd2fe22543f11273def45888 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/ppo_with_torch_lr_schedulers.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/separate_vf_lr_and_optimizer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/separate_vf_lr_and_optimizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce78c65b314c50230171d9eeed3ca110eb294fbf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/__pycache__/separate_vf_lr_and_optimizer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48a41589c2239c00a2b97ef0f46c0161a65e38a5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/custom_ppo_loss_fn_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/custom_ppo_loss_fn_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12872fe7dc7aca045d125c155b658bf2700a1993 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/custom_ppo_loss_fn_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/intrinsic_curiosity_learners.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/intrinsic_curiosity_learners.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7eae62a8898879810663cbb78a6e6e64aea9f7c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/intrinsic_curiosity_learners.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/separate_vf_lr_and_optimizer_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/separate_vf_lr_and_optimizer_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcd121745b7cfc91748986db69bef9de44f790ce Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/separate_vf_lr_and_optimizer_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/vpg_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/vpg_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfe98b3033a899f72b26bb7e37b0e02ed0d870e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/__pycache__/vpg_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/custom_ppo_loss_fn_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/custom_ppo_loss_fn_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..e63cd3c563e0e8d8434d7a8f1dce3bdc9313a060 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/custom_ppo_loss_fn_learner.py @@ -0,0 +1,54 @@ +from typing import Any, Dict + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import PPOTorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModuleID, TensorType + +torch, _ = try_import_torch() + + +class PPOTorchLearnerWithWeightRegularizerLoss(PPOTorchLearner): + """A custom PPO torch learner adding a weight regularizer term to the loss. + + We compute a naive regularizer term averaging over all parameters of the RLModule + and add this mean value (multiplied by the regularizer coefficient) to the base PPO + loss. + The experiment shows that even with a large learning rate, our custom Learner is + still able to learn properly as it's forced to keep the weights small. + """ + + @override(PPOTorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: PPOConfig, + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + + base_total_loss = super().compute_loss_for_module( + module_id=module_id, + config=config, + batch=batch, + fwd_out=fwd_out, + ) + + # Compute the mean of all the RLModule's weights. + parameters = self.get_parameters(self.module[module_id]) + mean_weight = torch.mean(torch.stack([w.mean() for w in parameters])) + + self.metrics.log_value( + key=(module_id, "mean_weight"), + value=mean_weight, + window=1, + ) + + total_loss = ( + base_total_loss + + config.learner_config_dict["regularizer_coeff"] * mean_weight + ) + + return total_loss diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/intrinsic_curiosity_learners.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/intrinsic_curiosity_learners.py new file mode 100644 index 0000000000000000000000000000000000000000..dd37dab0cb114d637a94d35897d11ef4082b629e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/intrinsic_curiosity_learners.py @@ -0,0 +1,162 @@ +from typing import Any, List, Optional + +import gymnasium as gym +import torch + +from ray.rllib.algorithms.dqn.torch.dqn_torch_learner import DQNTorchLearner +from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import PPOTorchLearner +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa + AddNextObservationsFromEpisodesToTrainBatch, +) +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core import Columns, DEFAULT_MODULE_ID +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.typing import EpisodeType + +ICM_MODULE_ID = "_intrinsic_curiosity_model" + + +class DQNTorchLearnerWithCuriosity(DQNTorchLearner): + def build(self) -> None: + super().build() + add_intrinsic_curiosity_connectors(self) + + +class PPOTorchLearnerWithCuriosity(PPOTorchLearner): + def build(self) -> None: + super().build() + add_intrinsic_curiosity_connectors(self) + + +def add_intrinsic_curiosity_connectors(torch_learner: TorchLearner) -> None: + """Adds two connector pieces to the Learner pipeline, needed for ICM training. + + - The `AddNextObservationsFromEpisodesToTrainBatch` connector makes sure the train + batch contains the NEXT_OBS for ICM's forward- and inverse dynamics net training. + - The `IntrinsicCuriosityModelConnector` piece computes intrinsic rewards from the + ICM and adds the results to the extrinsic reward of the main module's train batch. + + Args: + torch_learner: The TorchLearner, to whose Learner pipeline the two ICM connector + pieces should be added. + """ + learner_config_dict = torch_learner.config.learner_config_dict + + # Assert, we are only training one policy (RLModule) and we have the ICM + # in our MultiRLModule. + assert ( + len(torch_learner.module) == 2 + and DEFAULT_MODULE_ID in torch_learner.module + and ICM_MODULE_ID in torch_learner.module + ) + + # Make sure both curiosity loss settings are explicitly set in the + # `learner_config_dict`. + if ( + "forward_loss_weight" not in learner_config_dict + or "intrinsic_reward_coeff" not in learner_config_dict + ): + raise KeyError( + "When using the IntrinsicCuriosityTorchLearner, both `forward_loss_weight` " + " and `intrinsic_reward_coeff` must be part of your config's " + "`learner_config_dict`! Add these values through: `config.training(" + "learner_config_dict={'forward_loss_weight': .., 'intrinsic_reward_coeff': " + "..})`." + ) + + if torch_learner.config.add_default_connectors_to_learner_pipeline: + # Prepend a "add-NEXT_OBS-from-episodes-to-train-batch" connector piece + # (right after the corresponding "add-OBS-..." default piece). + torch_learner._learner_connector.insert_after( + AddObservationsFromEpisodesToBatch, + AddNextObservationsFromEpisodesToTrainBatch(), + ) + # Append the ICM connector, computing intrinsic rewards and adding these to + # the main model's extrinsic rewards. + torch_learner._learner_connector.insert_after( + NumpyToTensor, + IntrinsicCuriosityModelConnector( + intrinsic_reward_coeff=( + torch_learner.config.learner_config_dict["intrinsic_reward_coeff"] + ) + ), + ) + + +class IntrinsicCuriosityModelConnector(ConnectorV2): + """Learner ConnectorV2 piece to compute intrinsic rewards based on an ICM. + + For more details, see here: + [1] Curiosity-driven Exploration by Self-supervised Prediction + Pathak, Agrawal, Efros, and Darrell - UC Berkeley - ICML 2017. + https://arxiv.org/pdf/1705.05363.pdf + + This connector piece: + - requires two RLModules to be present in the MultiRLModule: + DEFAULT_MODULE_ID (the policy model to be trained) and ICM_MODULE_ID (the instrinsic + curiosity architecture). + - must be located toward the end of to your Learner pipeline (after the + `NumpyToTensor` piece) in order to perform a forward pass on the ICM model with the + readily compiled batch and a following forward-loss computation to get the intrinsi + rewards. + - these intrinsic rewards will then be added to the (extrinsic) rewards in the main + model's train batch. + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + intrinsic_reward_coeff: float, + **kwargs, + ): + """Initializes a CountBasedCuriosity instance. + + Args: + intrinsic_reward_coeff: The weight with which to multiply the intrinsic + reward before adding it to the extrinsic rewards of the main model. + """ + super().__init__(input_observation_space, input_action_space) + + self.intrinsic_reward_coeff = intrinsic_reward_coeff + + def __call__( + self, + *, + rl_module: RLModule, + batch: Any, + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Assert that the batch is ready. + assert DEFAULT_MODULE_ID in batch and ICM_MODULE_ID not in batch + assert ( + Columns.OBS in batch[DEFAULT_MODULE_ID] + and Columns.NEXT_OBS in batch[DEFAULT_MODULE_ID] + ) + # TODO (sven): We are performing two forward passes per update right now. + # Once here in the connector (w/o grad) to just get the intrinsic rewards + # and once in the learner to actually compute the ICM loss and update the ICM. + # Maybe we can save one of these, but this would currently harm the DDP-setup + # for multi-GPU training. + with torch.no_grad(): + # Perform ICM forward pass. + fwd_out = rl_module[ICM_MODULE_ID].forward_train(batch[DEFAULT_MODULE_ID]) + + # Add the intrinsic rewards to the main module's extrinsic rewards. + batch[DEFAULT_MODULE_ID][Columns.REWARDS] += ( + self.intrinsic_reward_coeff * fwd_out[Columns.INTRINSIC_REWARDS] + ) + + # Duplicate the batch such that the ICM also has data to learn on. + batch[ICM_MODULE_ID] = batch[DEFAULT_MODULE_ID] + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/separate_vf_lr_and_optimizer_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/separate_vf_lr_and_optimizer_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..7095503f5f620bb7d83ec50d4b2494bbf0a7ea3b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/separate_vf_lr_and_optimizer_learner.py @@ -0,0 +1,83 @@ +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import PPOTorchLearner +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModuleID + +torch, _ = try_import_torch() + + +class PPOTorchLearnerWithSeparateVfOptimizer(PPOTorchLearner): + """A custom PPO torch learner with 2 optimizers, for policy and value function. + + Overrides the Learner's standard `configure_optimizers_for_module()` method to + register the additional vf optimizer. + + The standard PPOLearner only uses a single optimizer (and single learning rate) to + update the model, regardless of whether the value function network + is separate from the policy network or whether they have shared components. + + We may leave the loss function of PPO completely untouched. It already returns a + sum of policy loss and vf loss (and entropy loss), and thus - given that the neural + networks used to compute each of these terms are separate and don't share any + components - gradients are computed separately per neural network (policy vs vf) + and applied separately through the two optimizers. + """ + + @override(TorchLearner) + def configure_optimizers_for_module( + self, + module_id: ModuleID, + config: "AlgorithmConfig" = None, + ) -> None: + """Registers 2 optimizers for the given ModuleID with this Learner.""" + + # Make sure the RLModule has the correct properties. + module = self.module[module_id] + # TODO (sven): We should move this into a new `ValueFunction` API, which + # should has-a `get_value_function_params` method. This way, any custom + # RLModule that implements this API can be used here, not just the standard + # PPO one. + assert ( + hasattr(module, "pi") + and hasattr(module, "vf") + and hasattr(module, "encoder") + and hasattr(module.encoder, "actor_encoder") + and hasattr(module.encoder, "critic_encoder") + ) + assert config.model_config["vf_share_layers"] is False + + # Get all policy-related parameters from the RLModule. + pi_params = ( + # Actor encoder and policy head. + self.get_parameters(self.module[module_id].encoder.actor_encoder) + + self.get_parameters(self.module[module_id].pi) + ) + # Register the policy optimizer. + self.register_optimizer( + module_id=module_id, + optimizer_name="optim_for_pi", + optimizer=torch.optim.Adam(params=pi_params), + params=pi_params, + # For the policy learning rate, we use the "main" lr in the AlgorithmConfig. + lr_or_lr_schedule=config.lr, + ) + + # Get all value function-related parameters from the RLModule. + vf_params = ( + # Critic encoder and value head. + self.get_parameters(self.module[module_id].encoder.critic_encoder) + + self.get_parameters(self.module[module_id].vf) + ) + # Register the value function optimizer. + self.register_optimizer( + module_id=module_id, + optimizer_name="optim_for_vf", + optimizer=torch.optim.Adam(params=vf_params), + params=vf_params, + # For the value function learning rate, we use a user-provided custom + # setting in the `learner_config_dict` in the AlgorithmConfig. If this + # is not provided, use the same lr as for the policy optimizer. + lr_or_lr_schedule=config.learner_config_dict.get("lr_vf", config.lr), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/vpg_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/vpg_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..17b7e527b7c96c1bff1d0d3ede4af47ed58f271c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/classes/vpg_torch_learner.py @@ -0,0 +1,72 @@ +import torch +from typing import Any, Dict, TYPE_CHECKING + +import numpy as np + +from ray.rllib.connectors.learner import ComputeReturnsToGo +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import ModuleID, TensorType + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + +class VPGTorchLearner(TorchLearner): + @override(TorchLearner) + def build(self) -> None: + super().build() + + # Prepend the returns-to-go connector piece to have that information + # available in the train batch. + if self.config.add_default_connectors_to_learner_pipeline: + self._learner_connector.prepend(ComputeReturnsToGo(gamma=self.config.gamma)) + + @override(TorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + rl_module = self.module[module_id] + + # Create the action distribution from the parameters output by the RLModule. + action_dist_inputs = fwd_out[Columns.ACTION_DIST_INPUTS] + action_dist_class = rl_module.get_train_action_dist_cls() + action_dist = action_dist_class.from_logits(action_dist_inputs) + + # Compute log probabilities of the actions taken during sampling. + log_probs = action_dist.logp(batch[Columns.ACTIONS]) + + # Compute the policy gradient loss. + # Since we're not using a baseline, we use returns to go directly. + loss = -torch.mean(log_probs * batch[Columns.RETURNS_TO_GO]) + + # Just for exercise, log the average return to go per discrete action. + for act, ret_to_go in zip(batch[Columns.ACTIONS], batch[Columns.RETURNS_TO_GO]): + self.metrics.log_value( + key=(module_id, f"action_{act}_return_to_go_mean"), + value=ret_to_go, + reduce="mean", + clear_on_reduce=True, + ) + + return loss + + @override(Learner) + def after_gradient_based_update(self, *, timesteps): + # This is to check if in the multi-gpu case, the weights across workers are + # the same. Only for testing purposes. + if self.config.report_mean_weights: + for module_id in self.module.keys(): + parameters = convert_to_numpy( + self.get_parameters(self.module[module_id]) + ) + mean_ws = np.mean([w.mean() for w in parameters]) + self.metrics.log_value((module_id, "mean_weight"), mean_ws, window=1) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/ppo_with_custom_loss_fn.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/ppo_with_custom_loss_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..f59db79c3ff6357fd554c8ddafd79e1803fc6305 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/ppo_with_custom_loss_fn.py @@ -0,0 +1,134 @@ +"""Example of how to write a custom loss function (based on the existing PPO loss). + +This example shows: + - how to subclass an existing (torch) Learner and override its + `compute_loss_for_module()` method. + - how you can add your own loss terms to the subclassed "base loss", in this + case here a weights regularizer term with the intention to keep the learnable + parameters of the RLModule reasonably small. + - how to add custom settings (here: the regularizer coefficient) to the + `AlgorithmConfig` in order to not have to subclass and write your own + (you could still do that, but are not required to). + - how to plug in the custom Learner into your config and then run the + experiment. + +See the :py:class:`~ray.rllib.examples.learners.classes.custom_loss_fn_learner.PPOTorchLearnerWithWeightRegularizerLoss` # noqa +class for details on how to override the main (PPO) loss function. + +We compute a naive regularizer term averaging over all parameters of the RLModule and +add this mean value (multiplied by the regularizer coefficient) to the base PPO loss. +The experiment shows that even with a large learning rate, our custom Learner is still +able to learn properly as it's forced to keep the weights small. + + +How to run this script +---------------------- +`python [script file name].py --regularizer-coeff=0.02 +--lr=0.01` + +Use the `--regularizer-coeff` option to set the value of the coefficient with which +the mean NN weight is being multiplied (inside the total loss) and the `--lr` option +to set the learning rate. Experiments using a large learning rate and no regularization +(`--regularizer-coeff=0.0`) should NOT learn a decently working policy. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that - given a large learning rate - only with +weight regularization (`--regularizer-coeff` > 0.0), the algo has a chance to learn +a decent policy: + +With --regularizer-coeff=0.02 and --lr=0.01 +(trying to reach 250.0 return on CartPole in 100k env steps): ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_4a3a0_00000 | TERMINATED | 127.0.0.1:16845 | 18 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+---------------------+ +| total time (s) | num_env_steps_sampled_ | episode_return_mean | +| | _lifetime | | +|------------------+------------------------+---------------------+ +| 16.8842 | 72000 | 256.35 | ++------------------+------------------------+---------------------+ + +With --regularizer-coeff=0.0 and --lr=0.01 +(trying to reach 250.0 return on CartPole in 100k env steps): + +[HAS SIGNIFICANT PROBLEMS REACHING THE DESIRED RETURN] +""" + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.learners.classes.custom_ppo_loss_fn_learner import ( + PPOTorchLearnerWithWeightRegularizerLoss, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +torch, _ = try_import_torch() + + +parser = add_rllib_example_script_args( + default_reward=250.0, + default_timesteps=200000, +) +parser.add_argument( + "--regularizer-coeff", + type=float, + default=0.02, + help="The coefficient with which to multiply the mean NN-weight by (and then add " + "the result of this operation to the main loss term).", +) +parser.add_argument( + "--lr", + type=float, + default=0.01, + help="The learning rate to use.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.algo == "PPO", "Must set --algo=PPO when running this script!" + + base_config = ( + PPOConfig() + .environment("CartPole-v1") + .training( + # This is the most important setting in this script: We point our PPO + # algorithm to use the custom Learner (instead of the default + # PPOTorchLearner). + learner_class=PPOTorchLearnerWithWeightRegularizerLoss, + # We use this simple method here to inject a new setting that our + # custom Learner class uses in its loss function. This is convenient + # and avoids having to subclass `PPOConfig` only to add a few new settings + # to it. Within our Learner, we can access this new setting through: + # `self.config.learner_config_dict['regularizer_coeff']` + learner_config_dict={"regularizer_coeff": args.regularizer_coeff}, + # Some settings to make this example learn better. + num_epochs=6, + vf_loss_coeff=0.01, + # The learning rate, settable through the command line `--lr` arg. + lr=args.lr, + ) + .rl_module( + model_config=DefaultModelConfig(vf_share_layers=True), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/ppo_with_torch_lr_schedulers.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/ppo_with_torch_lr_schedulers.py new file mode 100644 index 0000000000000000000000000000000000000000..710353017b082b924a63f9d16cb89915615740ea --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/ppo_with_torch_lr_schedulers.py @@ -0,0 +1,208 @@ +"""Example of how to use PyTorch's learning rate schedulers to design a complex +learning rate schedule for training. + +Two learning rate schedules are applied in sequence to the learning rate of the +optimizer. In this way even more complex learning rate schedules can be assembled. + +This example shows: + - how to configure multiple learning rate schedulers, as a chained pipeline, in + PyTorch using partial initialization with `functools.partial`. + + +How to run this script +---------------------- +`python [script file name].py --lr-const-factor=0.9 +--lr-const-iters=10 --lr-exp-decay=0.9` + +Use the `--lr-const-factor` to define the facotr by which to multiply the +learning rate in the first `--lr-const-iters` iterations. Use the +`--lr-const-iters` to set the number of iterations in which the learning rate +should be adapted by the `--lr-const-factor`. Use `--lr-exp-decay` to define +the learning rate decay to be applied after the constant factor multiplication. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect to observe decent learning behavior from your console output: + +With `--lr-const-factor=0.1`, `--lr-const-iters=10, and `--lr-exp_decay=0.3`. ++-----------------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|-----------------------------+------------+--------+------------------+ +| PPO_CartPole-v1_7fc44_00000 | TERMINATED | 50 | 59.6542 | ++-----------------------------+------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetime | num_env_steps_traine | +| | | d_lifetime | ++------------------------+------------------------+------------------------| +| 451.2 | 9952 | 210047 | ++------------------------+------------------------+------------------------+ +""" +import functools +import numpy as np +from typing import Optional + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.learner.learner import DEFAULT_OPTIMIZER +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import add_rllib_example_script_args + +torch, _ = try_import_torch() + + +class LRChecker(RLlibCallback): + def on_algorithm_init( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + **kwargs, + ) -> None: + # Store the expected learning rates for each iteration. + self.lr = [] + # Retrieve the chosen configuration parameters from the config. + lr_factor = algorithm.config._torch_lr_scheduler_classes[0].keywords["factor"] + lr_total_iters = algorithm.config._torch_lr_scheduler_classes[0].keywords[ + "total_iters" + ] + lr_gamma = algorithm.config._torch_lr_scheduler_classes[1].keywords["gamma"] + # Compute the learning rates for all iterations up to `lr_const_iters`. + for i in range(1, lr_total_iters + 1): + # The initial learning rate. + lr = algorithm.config.lr + # In the first 10 iterations we multiply by `lr_const_factor`. + if i < lr_total_iters: + lr *= lr_factor + # Finally, we have an exponential decay of `lr_exp_decay`. + lr *= lr_gamma**i + self.lr.append(lr) + + def on_train_result( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + result: dict, + **kwargs, + ) -> None: + + # Check for the first `lr_total_iters + 1` iterations, if expected + # and actual learning rates correspond. + if ( + algorithm.training_iteration + <= algorithm.config._torch_lr_scheduler_classes[0].keywords["total_iters"] + ): + actual_lr = algorithm.learner_group._learner.get_optimizer( + DEFAULT_MODULE_ID, DEFAULT_OPTIMIZER + ).param_groups[0]["lr"] + # Assert the learning rates are close enough. + assert np.isclose( + actual_lr, + self.lr[algorithm.training_iteration - 1], + atol=1e-9, + rtol=1e-9, + ) + + +parser = add_rllib_example_script_args(default_reward=450.0, default_timesteps=250000) +parser.add_argument( + "--lr-const-factor", + type=float, + default=0.9, + help="The factor by which the learning rate should be multiplied.", +) +parser.add_argument( + "--lr-const-iters", + type=int, + default=10, + help=( + "The number of iterations by which the learning rate should be " + "multiplied by the factor." + ), +) +parser.add_argument( + "--lr-exp-decay", + type=float, + default=0.99, + help="The rate by which the learning rate should exponentially decay.", +) + +if __name__ == "__main__": + # Use `parser` to add your own custom command line options to this script + # and (if needed) use their values to set up `config` below. + args = parser.parse_args() + + config = ( + PPOConfig() + .environment("CartPole-v1") + .training( + lr=0.03, + num_sgd_iter=6, + vf_loss_coeff=0.01, + ) + .rl_module( + model_config=DefaultModelConfig( + fcnet_hiddens=[32], + fcnet_activation="linear", + vf_share_layers=True, + ), + ) + .evaluation( + evaluation_num_env_runners=1, + evaluation_interval=1, + evaluation_parallel_to_training=True, + evaluation_config=PPOConfig.overrides(exploration=False), + ) + .experimental( + # Add two learning rate schedulers to be applied in sequence. + _torch_lr_scheduler_classes=[ + # Multiplies the learning rate by a factor of 0.1 for 10 iterations. + functools.partial( + torch.optim.lr_scheduler.ConstantLR, + factor=args.lr_const_factor, + total_iters=args.lr_const_iters, + ), + # Decays the learning rate after each gradients step by + # `args.lr_exp_decay`. + functools.partial( + torch.optim.lr_scheduler.ExponentialLR, gamma=args.lr_exp_decay + ), + ] + ) + .callbacks( + LRChecker, + ) + ) + + stop = { + f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}": args.stop_timesteps, + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": ( + args.stop_reward + ), + } + + if __name__ == "__main__": + from ray.rllib.utils.test_utils import run_rllib_example_script_experiment + + run_rllib_example_script_experiment(config, args, stop=stop) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/separate_vf_lr_and_optimizer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/separate_vf_lr_and_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..7293599ac3fb5bf4b37a39db12f6632b539fba9d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/learners/separate_vf_lr_and_optimizer.py @@ -0,0 +1,131 @@ +"""Example of how to run any value function based algo (e.g. PPO) with 2 optimizers. + +One optimizer (with its own learning rate and other configurations) is responsible for +updating the policy network, the other (with its own learning rate and other +configurations) for updating the value function network. + +This example shows: + - how to subclass an existing (torch) Learner and override its + `configure_optimizers_for_module()` method. + - how to call `Learner.register_optimizer()` from within your custom + `configure_optimizers_for_module()` method in order to specify, which optimizer + (type, learning rate, other settings) is responsible for which neural network + parameters. + - how to add custom settings (here: the additional learning rate for the + vf-optimizer) to the `AlgorithmConfig` in order to not have to subclass and write + your own (you could still do that, but are not required to). + - how to plug in the custom Learner into your config and then run the + experiment. + +See the :py:class:`~ray.rllib.examples.learners.classes.separate_vf_lr_and_optimizer_learner.PPOTorchLearnerWithSeparateVfOptimizer` # noqa +class for details on how to override the main (torch) `configure_optimizers_for_module` +function. + +We assume here that the users properly sets up their RLModule to have separate policy- +and value function networks. If any model pieces are shared between the two optimizers, +you should experience learning instability up to the point where your algorithm can't +learn any useful policy anymore. + + +How to run this script +---------------------- +`python [script file name].py --lr-vf=0.001 --lr-policy=0.0005` + +Use the `--lr-policy` option to set the policy learning rate (used by the policy +optimizer) and the `--lr-vf` option to set the value function learning rate (used by the +value function optimizer). + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect to observe decent learning behavior from your console output: + +With --lr-vf=0.0005 and --lr-policy=0.001 ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_7b404_00000 | TERMINATED | 127.0.0.1:16845 | 19 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+---------------------+ +| total time (s) | num_env_steps_sampled_ | episode_return_mean | +| | _lifetime | | +|------------------+------------------------+---------------------+ +| 19.4179 | 76000 | 459.94 | ++------------------+------------------------+---------------------+ +""" + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.learners.classes.separate_vf_lr_and_optimizer_learner import ( + PPOTorchLearnerWithSeparateVfOptimizer, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +torch, _ = try_import_torch() + + +parser = add_rllib_example_script_args(default_reward=450.0) +parser.add_argument( + "--lr-vf", + type=float, + default=0.0005, + help="The learning rate used in the value function optimizer.", +) +parser.add_argument( + "--lr-policy", + type=float, + default=0.001, + help="The learning rate used in the policy optimizer.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.algo == "PPO", "Must set --algo=PPO when running this script!" + + base_config = ( + PPOConfig() + .environment("CartPole-v1") + .training( + # This is the most important setting in this script: We point our PPO + # algorithm to use the custom Learner (instead of the default + # PPOTorchLearner). + learner_class=PPOTorchLearnerWithSeparateVfOptimizer, + # We use this simple method here to inject a new setting that our + # custom Learner class uses in its `configure_optimizers_for_module` + # method. This is convenient and avoids having to subclass `PPOConfig` only + # to add a few new settings to it. Within our Learner, we can access this + # new setting through: + # `self.config.learner_config_dict['lr_vf']` + learner_config_dict={"lr_vf": args.lr_vf}, + # Some settings to make this example learn better. + num_epochs=6, + # Since we are using separate optimizers for the two NN components, the + # value of `vf_loss_coeff` does not matter anymore. We set this to 1.0 here. + vf_loss_coeff=1.0, + # The policy learning rate, settable through the command line `--lr` arg. + lr=args.lr_policy, + ) + .rl_module( + # Another very important setting is this here. Make sure you use + # completely separate NNs for policy and value-functions. + model_config=DefaultModelConfig(vf_share_layers=False), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5466b228d8489b41bec18feb45442443f6c148bb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/custom_metrics_in_algorithm_training_step.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/custom_metrics_in_algorithm_training_step.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52797d80d93471886a7e96884274cfc684125dfe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/custom_metrics_in_algorithm_training_step.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/custom_metrics_in_env_runners.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/custom_metrics_in_env_runners.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37f6a3e81d6e7f859cb58a8cb088d675e75e49cb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/__pycache__/custom_metrics_in_env_runners.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/custom_metrics_in_algorithm_training_step.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/custom_metrics_in_algorithm_training_step.py new file mode 100644 index 0000000000000000000000000000000000000000..2b6084155ef0cdca0ea6f34dd88349ae4c33159b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/custom_metrics_in_algorithm_training_step.py @@ -0,0 +1,105 @@ +"""Example of logging custom metrics inside the `Algorithm.training_step()` method. + +RLlib provides a MetricsLogger instance inside most components of an Algorithm, +including the Algorithm itself. + +This example: +- Shows how to subclass a custom Algorithm class (VPG) and override its +`training_step()` method. +- Shows how to use the MetricsLogger instance of Algorithm to log the ratio between +the time spent on sampling over the time spent on the learning update. For on-policy +algorithms, this ratio indicates, where scaling would yield the largest speedups, on +the EnvRunner side or on the Learner side. +- Shows how to access the logged metrics at the end of an iteration through the returned +result dict and how to assert, the new metrics has been properly logged. + + +How to run this script +---------------------- +`python [script file name].py --wandb-key [your WandB key] +--wandb-project [some project name]` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see something similar to the below on your terminal when running +this script: + ++-----------------------------------------------+------------+--------+ +| Trial name | status | iter | +| | | | +|-----------------------------------------------+------------+--------+ +| MyVPGWithExtraMetrics_CartPole-v1_d2c5c_00000 | TERMINATED | 100 | ++-----------------------------------------------+------------+--------+ ++------------------+-----------------------+------------------------+ +| total time (s) | episode_return_mean | ratio_time_sampling_ | +| | | over_learning | +|------------------+-----------------------+------------------------| +| 10.0308 | 50.91 | 4.84769 | ++------------------+-----------------------+------------------------+ + +Found logged `ratio_time_sampling_over_learning` in result dict. +""" +from ray.rllib.algorithms import AlgorithmConfig +from ray.rllib.examples.algorithms.classes.vpg import VPG, VPGConfig +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics import ( + ENV_RUNNER_SAMPLING_TIMER, + LEARNER_UPDATE_TIMER, + TIMERS, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + + +class MyVPGWithExtraMetrics(VPG): + @override(VPG) + def training_step(self) -> None: + # Call the actual VPG training_step. + super().training_step() + + # Look up some already logged metrics through the `peek()` method. + time_spent_on_sampling = self.metrics.peek((TIMERS, ENV_RUNNER_SAMPLING_TIMER)) + time_spent_on_learning = self.metrics.peek((TIMERS, LEARNER_UPDATE_TIMER)) + + # Log extra metrics, still for this training step. + self.metrics.log_value( + "ratio_time_sampling_over_learning", + time_spent_on_sampling / time_spent_on_learning, + ) + + @classmethod + @override(VPG) + def get_default_config(cls) -> AlgorithmConfig: + return VPGConfig(algo_class=cls) + + +parser = add_rllib_example_script_args(default_reward=50.0) +parser.set_defaults(default_timesteps=50000) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = MyVPGWithExtraMetrics.get_default_config().environment("CartPole-v1") + + results = run_rllib_example_script_experiment(base_config, args) + + # Check, whether the logged metrics are present. + if args.no_tune: + assert "ratio_time_sampling_over_learning" in results + else: + assert "ratio_time_sampling_over_learning" in results[0].metrics + + print("Found logged `ratio_time_sampling_over_learning` in result dict.") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/custom_metrics_in_env_runners.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/custom_metrics_in_env_runners.py new file mode 100644 index 0000000000000000000000000000000000000000..61f6b16a744be10bdbc3de2bbb165e00422473b1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/metrics/custom_metrics_in_env_runners.py @@ -0,0 +1,350 @@ +"""Example of adding custom metrics to the results returned by `EnvRunner.sample()`. + +We use the `MetricsLogger` class, which RLlib provides inside all its components (only +when using the new API stack through +`config.api_stack(enable_rl_module_and_learner=True, +enable_env_runner_and_connector_v2=True)`), +and which offers a unified API to log individual values per iteration, per episode +timestep, per episode (as a whole), per loss call, etc.. +`MetricsLogger` objects are available in all custom API code, for example inside your +custom `Algorithm.training_step()` methods, custom loss functions, custom callbacks, +and custom EnvRunners. + +This example: + - demonstrates how to write a custom RLlibCallback subclass, which overrides some + EnvRunner-bound methods, such as `on_episode_start`, `on_episode_step`, and + `on_episode_end`. + - shows how to temporarily store per-timestep data inside the currently running + episode within the EnvRunner (and the callback methods). + - shows how to extract this temporary data again when the episode is done in order + to further process the data into a single, reportable metric. + - explains how to use the `MetricsLogger` API to create and log different metrics + to the final Algorithm's iteration output. These include - but are not limited to - + a 2D heatmap (image) per episode, an average per-episode metric (over a sliding + window of 200 episodes), a maximum per-episode metric (over a sliding window of 100 + episodes), and an EMA-smoothed metric. + +In this script, we define a custom `RLlibCallback` class and then override some of +its methods in order to define custom behavior during episode sampling. In particular, +we add custom metrics to the Algorithm's published result dict (once per +iteration) before it is sent back to Ray Tune (and possibly a WandB logger). + +For demonstration purposes only, we log the following custom metrics: +- A 2D heatmap showing the frequency of all accumulated y/x-locations of Ms Pacman +during an episode. We create and log a separate heatmap per episode and limit the number +of heatmaps reported back to the algorithm by each EnvRunner to 10 (`window=10`). +- The maximum per-episode distance travelled by Ms Pacman over a sliding window of 100 +episodes. +- The average per-episode distance travelled by Ms Pacman over a sliding window of 200 +episodes. +- The EMA-smoothed number of lives of Ms Pacman at each timestep (across all episodes). + + +How to run this script +---------------------- +`python [script file name].py --wandb-key [your WandB key] +--wandb-project [some project name]` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +This script has not been finetuned to actually learn the environment. Its purpose +is to show how you can create and log custom metrics during episode sampling and +have these stats be sent to WandB for further analysis. + +However, you should see training proceeding over time like this: ++---------------------+----------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+----------+----------------+--------+------------------+ +| PPO_env_efd16_00000 | RUNNING | 127.0.0.1:6181 | 4 | 72.4725 | ++---------------------+----------+----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetim | num_env_steps_traine | +| | e | d_lifetime | +|------------------------+------------------------+------------------------| +| 76.4 | 45 | 8053 | ++------------------------+------------------------+------------------------+ +""" +from typing import Optional, Sequence + +import gymnasium as gym +import matplotlib.pyplot as plt +from matplotlib.colors import Normalize +import numpy as np + +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.env.wrappers.atari_wrappers import wrap_atari_for_new_api_stack +from ray.rllib.utils.images import resize +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + + +class MsPacmanHeatmapCallback(RLlibCallback): + """A custom callback to extract information from MsPacman and log these. + + This callback logs: + - the positions of MsPacman over an episode to produce heatmaps from this data. + At each episode timestep, the current pacman (y/x)-position is determined and added + to the episode's temporary storage. At the end of an episode, a simple 2D heatmap + is created from this data and the heatmap is logged to the MetricsLogger (to be + viewed in WandB). + - the max distance travelled by MsPacman per episode, then averaging these max + values over a window of size=100. + - the mean distance travelled by MsPacman per episode (over an infinite window). + - the number of lifes of MsPacman EMA-smoothed over time. + + This callback can be setup to only log stats on certain EnvRunner indices through + the `env_runner_indices` c'tor arg. + """ + + def __init__(self, env_runner_indices: Optional[Sequence[int]] = None): + """Initializes an MsPacmanHeatmapCallback instance. + + Args: + env_runner_indices: The (optional) EnvRunner indices, for this callback + should be active. If None, activates the heatmap for all EnvRunners. + If a Sequence type, only logs/heatmaps, if the EnvRunner index is found + in `env_runner_indices`. + """ + super().__init__() + # Only create heatmap on certain EnvRunner indices? + self._env_runner_indices = env_runner_indices + + # Mapping from episode ID to max distance travelled thus far. + self._episode_start_position = {} + + def on_episode_start( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + # Skip, if this EnvRunner's index is not in `self._env_runner_indices`. + if ( + self._env_runner_indices is not None + and env_runner.worker_index not in self._env_runner_indices + ): + return + + yx_pos = self._get_pacman_yx_pos(env) + self._episode_start_position[episode.id_] = yx_pos + + # Create two lists holding custom per-timestep data. + episode.custom_data["pacman_yx_pos"] = [] + episode.custom_data["pacman_dist_travelled"] = [] + + def on_episode_step( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + """Adds current pacman y/x-position to episode's temporary data.""" + + # Skip, if this EnvRunner's index is not in `self._env_runner_indices`. + if ( + self._env_runner_indices is not None + and env_runner.worker_index not in self._env_runner_indices + ): + return + + yx_pos = self._get_pacman_yx_pos(env) + episode.custom_data["pacman_yx_pos"].append(yx_pos) + + # Compute distance to start position. + dist_travelled = np.sqrt( + np.sum( + np.square( + np.array(self._episode_start_position[episode.id_]) + - np.array(yx_pos) + ) + ) + ) + episode.custom_data["pacman_dist_travelled"].append(dist_travelled) + + def on_episode_end( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + # Skip, if this EnvRunner's index is not in `self._env_runner_indices`. + if ( + self._env_runner_indices is not None + and env_runner.worker_index not in self._env_runner_indices + ): + return + + # Erase the start position record. + del self._episode_start_position[episode.id_] + + # Get all pacman y/x-positions from the episode. + yx_positions = episode.custom_data["pacman_yx_pos"] + # h x w + heatmap = np.zeros((80, 100), dtype=np.int32) + for yx_pos in yx_positions: + if yx_pos != (-1, -1): + heatmap[yx_pos[0], yx_pos[1]] += 1 + + # Create the actual heatmap image. + # Normalize the heatmap to values between 0 and 1 + norm = Normalize(vmin=heatmap.min(), vmax=heatmap.max()) + # Use a colormap (e.g., 'hot') to map normalized values to RGB + colormap = plt.get_cmap("coolwarm") # try "hot" and "viridis" as well? + # Returns a (64, 64, 4) array (RGBA). + heatmap_rgb = colormap(norm(heatmap)) + # Convert RGBA to RGB by dropping the alpha channel and converting to uint8. + heatmap_rgb = (heatmap_rgb[:, :, :3] * 255).astype(np.uint8) + # Log the image. + metrics_logger.log_value( + "pacman_heatmap", + heatmap_rgb, + reduce=None, + window=10, # Log 10 images at most per EnvRunner/training iteration. + ) + + # Get the max distance travelled for this episode. + dist_travelled = np.max(episode.custom_data["pacman_dist_travelled"]) + + # Log the max. dist travelled in this episode (window=100). + metrics_logger.log_value( + "pacman_max_dist_travelled", + dist_travelled, + # For future reductions (e.g. over n different episodes and all the + # data coming from other env runners), reduce by max. + reduce=None, + # Always keep the last 100 values and max over this window. + # Note that this means that over time, if the values drop to lower + # numbers again, the reported `pacman_max_dist_travelled` might also + # decrease again (meaning `window=100` makes this not a "lifetime max"). + window=100, + # Some percentiles to compute + percentiles=[75, 95, 99], + clear_on_reduce=True, + ) + + # Log the average dist travelled per episode (window=200). + metrics_logger.log_value( + "pacman_mean_dist_travelled", + dist_travelled, + reduce="mean", # <- default + # Always keep the last 200 values and average over this window. + window=200, + ) + + # Log the number of lifes (as EMA-smoothed; no window). + metrics_logger.log_value( + "pacman_lifes", + episode.get_infos(-1)["lives"], + reduce="mean", # <- default (must be "mean" for EMA smothing) + ema_coeff=0.01, # <- default EMA coefficient (`window` must be None) + ) + + def on_train_result(self, *, result: dict, **kwargs) -> None: + print( + "Max distance travelled per episode (percentiles) for this training iteration: ", + result["env_runners"]["pacman_max_dist_travelled"], + ) + + def _get_pacman_yx_pos(self, env): + # If we have a vector env, only render the sub-env at index 0. + if isinstance(env.unwrapped, gym.vector.VectorEnv): + image = env.envs[0].render() + else: + image = env.render() + # Downsize to 100x100 for our utility function to work with. + image = resize(image, 100, 100) + # Crop image at bottom 20% (where lives are shown, which may confuse the pacman + # detector). + image = image[:80] + # Define the yellow color range in RGB (Ms. Pac-Man is yellowish). + # We allow some range around yellow to account for variation. + yellow_lower = np.array([200, 130, 65], dtype=np.uint8) + yellow_upper = np.array([220, 175, 105], dtype=np.uint8) + # Create a mask that highlights the yellow pixels + mask = np.all((image >= yellow_lower) & (image <= yellow_upper), axis=-1) + # Find the coordinates of the yellow pixels + yellow_pixels = np.argwhere(mask) + if yellow_pixels.size == 0: + return (-1, -1) + + # Calculate the centroid of the yellow pixels to get Ms. Pac-Man's position + y, x = yellow_pixels.mean(axis=0).astype(int) + return y, x + + +parser = add_rllib_example_script_args(default_reward=450.0) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + register_env( + "env", + lambda cfg: wrap_atari_for_new_api_stack( + gym.make("ale_py:ALE/MsPacman-v5", **cfg, **{"render_mode": "rgb_array"}), + framestack=4, + ), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + "env", + env_config={ + # Make analogous to old v4 + NoFrameskip. + "frameskip": 1, + "full_action_space": False, + "repeat_action_probability": 0.0, + }, + ) + .callbacks(MsPacmanHeatmapCallback) + .training( + # Make learning time fast, but note that this example may not + # necessarily learn well (its purpose is to demo the + # functionality of callbacks and the MetricsLogger). + train_batch_size_per_learner=2000, + minibatch_size=512, + num_epochs=6, + ) + .rl_module( + model_config_dict={ + "vf_share_layers": True, + "conv_filters": [[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]], + "conv_activation": "relu", + "post_fcnet_hiddens": [256], + } + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30e253ab076cab0b5a383bad08322b284d60bc41 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/custom_heuristic_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/custom_heuristic_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38aca9c91b428d233caa3258cea7c712de61b4a0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/custom_heuristic_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/different_spaces_for_agents.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/different_spaces_for_agents.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1488d363d006ff1d11df687ab8802a4997c42e0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/different_spaces_for_agents.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/multi_agent_cartpole.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/multi_agent_cartpole.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fec124cb8a39cca6921387a201d15e36ed37e25 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/multi_agent_cartpole.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/multi_agent_pendulum.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/multi_agent_pendulum.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e4500d3819f41c48136d28347428f26e4050854 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/multi_agent_pendulum.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_independent_learning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_independent_learning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4804f9b194a15a20d8ee8dc788a92d1045af4a2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_independent_learning.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_parameter_sharing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_parameter_sharing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0747d0505bb651882ef5482eac85e2940c94f941 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_parameter_sharing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_shared_value_function.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_shared_value_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9127b13d5bf9077850d85fdf03432b747a1098ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/pettingzoo_shared_value_function.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/rock_paper_scissors_heuristic_vs_learned.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/rock_paper_scissors_heuristic_vs_learned.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c810b68b43b1483b7aedcc21fc571c3e4175c31 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/rock_paper_scissors_heuristic_vs_learned.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/rock_paper_scissors_learned_vs_learned.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/rock_paper_scissors_learned_vs_learned.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbd5372d5cf1f208598ebb7fee72b036689f50d6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/rock_paper_scissors_learned_vs_learned.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/self_play_league_based_with_open_spiel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/self_play_league_based_with_open_spiel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22c0a67df26b3728dd6163928788679fd9b42ca7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/self_play_league_based_with_open_spiel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/self_play_with_open_spiel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/self_play_with_open_spiel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9680e55d441feec0ddc9b7db7e94a8cb7ec976a3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/self_play_with_open_spiel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/two_step_game_with_grouped_agents.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/two_step_game_with_grouped_agents.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f3ef382ceb3c0dee3e3a2e31979819953646a8f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/__pycache__/two_step_game_with_grouped_agents.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/custom_heuristic_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/custom_heuristic_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..45753d0bbc1be72e3e6f83ade165562dfc810ff4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/custom_heuristic_policy.py @@ -0,0 +1,100 @@ +"""Example of running a custom heuristic (hand-coded) policy alongside trainable ones. + +This example has two RLModules (as action computing policies): + (1) one trained by a PPOLearner + (2) one hand-coded policy that acts at random in the env (doesn't learn). + +The environment is MultiAgentCartPole, in which there are n agents both policies + + +How to run this script +---------------------- +`python [script file name].py --num-agents=2` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see the PPO policy ("learnable_policy") does much +better than "random": + ++-------------------+------------+----------+------+----------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|-------------------+------------+----------+------+----------------+ +| PPO_multi_agen... | TERMINATED | 127. ... | 20 | 58.646 | ++-------------------+------------+----------+------+----------------+ + ++--------+-------------------+-----------------+--------------------+ +| ts | combined reward | reward random | reward | +| | | | learnable_policy | ++--------+-------------------+-----------------+--------------------| +| 80000 | 481.26 | 78.41 | 464.41 | ++--------+-------------------+-----------------+--------------------+ +""" + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.examples.rl_modules.classes.random_rlm import RandomRLModule +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import register_env + + +parser = add_rllib_example_script_args( + default_iters=40, default_reward=500.0, default_timesteps=200000 +) +parser.set_defaults( + num_agents=2, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents == 2, "Must set --num-agents=2 when running this script!" + + # Simple environment with n independent cartpole entities. + register_env( + "multi_agent_cartpole", + lambda _: MultiAgentCartPole({"num_agents": args.num_agents}), + ) + + base_config = ( + PPOConfig() + .environment("multi_agent_cartpole") + .multi_agent( + policies={"learnable_policy", "random"}, + # Map to either random behavior or PPO learning behavior based on + # the agent's ID. + policy_mapping_fn=lambda agent_id, *args, **kwargs: [ + "learnable_policy", + "random", + ][agent_id % 2], + # We need to specify this here, b/c the `forward_train` method of + # `RandomRLModule` (ModuleID="random") throws a not-implemented error. + policies_to_train=["learnable_policy"], + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + "learnable_policy": RLModuleSpec(), + "random": RLModuleSpec(module_class=RandomRLModule), + } + ), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/different_spaces_for_agents.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/different_spaces_for_agents.py new file mode 100644 index 0000000000000000000000000000000000000000..7d139458eb8db2b95a8f832eb6d9155e5364c1a7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/different_spaces_for_agents.py @@ -0,0 +1,108 @@ +""" +Example showing how to create a multi-agent env, in which the different agents +have different observation and action spaces. + +These spaces do NOT necessarily have to be specified manually by the user. Instead, +RLlib tries to automatically infer them from the env provided spaces dicts +(agentID -> obs/act space) and the policy mapping fn (mapping agent IDs to policy IDs). + +How to run this script +---------------------- +`python [script file name].py --num-agents=2` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` +""" + +import gymnasium as gym + +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + + +class BasicMultiAgentMultiSpaces(MultiAgentEnv): + """A simple multi-agent example environment where agents have different spaces. + + agent0: obs=Box(10,), act=Discrete(2) + agent1: obs=Box(20,), act=Discrete(3) + + The logic of the env doesn't really matter for this example. The point of this env + is to show how to use multi-agent envs, in which the different agents utilize + different obs- and action spaces. + """ + + def __init__(self, config=None): + self.agents = ["agent0", "agent1"] + + self.terminateds = set() + self.truncateds = set() + + # Provide full (preferred format) observation- and action-spaces as Dicts + # mapping agent IDs to the individual agents' spaces. + self.observation_spaces = { + "agent0": gym.spaces.Box(low=-1.0, high=1.0, shape=(10,)), + "agent1": gym.spaces.Box(low=-1.0, high=1.0, shape=(20,)), + } + self.action_spaces = { + "agent0": gym.spaces.Discrete(2), + "agent1": gym.spaces.Discrete(3), + } + + super().__init__() + + def reset(self, *, seed=None, options=None): + self.terminateds = set() + self.truncateds = set() + return {i: self.get_observation_space(i).sample() for i in self.agents}, {} + + def step(self, action_dict): + obs, rew, terminated, truncated, info = {}, {}, {}, {}, {} + for i, action in action_dict.items(): + obs[i] = self.get_observation_space(i).sample() + rew[i] = 0.0 + terminated[i] = False + truncated[i] = False + info[i] = {} + terminated["__all__"] = len(self.terminateds) == len(self.agents) + truncated["__all__"] = len(self.truncateds) == len(self.agents) + return obs, rew, terminated, truncated, info + + +parser = add_rllib_example_script_args( + default_iters=10, default_reward=80.0, default_timesteps=10000 +) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment(env=BasicMultiAgentMultiSpaces) + .training(train_batch_size=1024) + .multi_agent( + # Use a simple set of policy IDs. Spaces for the individual policies + # are inferred automatically using reverse lookup via the + # `policy_mapping_fn` and the env provided spaces for the different + # agents. Alternatively, you could use: + # policies: {main0: PolicySpec(...), main1: PolicySpec} + policies={"main0", "main1"}, + # Simple mapping fn, mapping agent0 to main0 and agent1 to main1. + policy_mapping_fn=(lambda aid, episode, **kw: f"main{aid[-1]}"), + # Only train main0. + policies_to_train=["main0"], + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/multi_agent_cartpole.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/multi_agent_cartpole.py new file mode 100644 index 0000000000000000000000000000000000000000..3639595d3161e3afa079990c23f15bb66ac9d9de --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/multi_agent_cartpole.py @@ -0,0 +1,66 @@ +"""Simple example of setting up an agent-to-module mapping function. + +How to run this script +---------------------- +`python [script file name].py --num-agents=2` + +Control the number of agents and policies (RLModules) via --num-agents and +--num-policies. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` +""" + +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +parser = add_rllib_example_script_args( + default_iters=200, + default_timesteps=100000, + default_reward=600.0, +) +# TODO (sven): This arg is currently ignored (hard-set to 2). +parser.add_argument( + "--num-policies", + type=int, + default=2, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda _: MultiAgentCartPole(config={"num_agents": args.num_agents}), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env" if args.num_agents > 0 else "CartPole-v1") + .env_runners( + num_envs_per_env_runner=20, + ) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/multi_agent_pendulum.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/multi_agent_pendulum.py new file mode 100644 index 0000000000000000000000000000000000000000..926cc72d49ce8b94b23ef3e3578893af72f6a94e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/multi_agent_pendulum.py @@ -0,0 +1,77 @@ +"""Simple example of setting up an agent-to-module mapping function. + +How to run this script +---------------------- +`python [script file name].py --num-agents=2` + +Control the number of agents and policies (RLModules) via --num-agents and +--num-policies. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` +""" + +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentPendulum +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +parser = add_rllib_example_script_args( + default_iters=200, + default_timesteps=100000, + default_reward=-400.0, +) +# TODO (sven): This arg is currently ignored (hard-set to 2). +parser.add_argument( + "--num-policies", + type=int, + default=2, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env" if args.num_agents > 0 else "Pendulum-v1") + .training( + train_batch_size_per_learner=512, + minibatch_size=64, + lambda_=0.1, + gamma=0.95, + lr=0.0003, + model={"fcnet_activation": "relu"}, + vf_clip_param=10.0, + ) + .rl_module( + model_config=DefaultModelConfig(fcnet_activation="relu"), + ) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # Augment + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_independent_learning.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_independent_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..86fb57e5c885769d0f2b4e455e424fe32b1ab576 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_independent_learning.py @@ -0,0 +1,105 @@ +"""Runs the PettingZoo Waterworld env in RLlib using independent multi-agent learning. + +See: https://pettingzoo.farama.org/environments/sisl/waterworld/ +for more details on the environment. + + +How to run this script +---------------------- +`python [script file name].py --num-agents=2` + +Control the number of agents and policies (RLModules) via --num-agents and +--num-policies. + +This works with hundreds of agents and policies, but note that initializing +many policies might take some time. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +The above options can reach a combined reward of 0.0 or more after about 500k env +timesteps. Keep in mind, though, that due to the separate value functions (and +learned policies in general), one agent's gain (in per-agent reward) might cause the +other agent's reward to decrease at the same time. However, over time, both agents +should simply improve. + ++---------------------+------------+-----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +|---------------------+------------+-----------------+--------+------------------+ +| PPO_env_a82fc_00000 | TERMINATED | 127.0.0.1:28346 | 124 | 363.599 | ++---------------------+------------+-----------------+--------+------------------+ + ++--------+-------------------+--------------------+--------------------+ +| ts | combined reward | reward pursuer_1 | reward pursuer_0 | ++--------+-------------------+--------------------+--------------------| +| 496000 | 2.24542 | -34.6869 | 36.9324 | ++--------+-------------------+--------------------+--------------------+ + +Note that the two agents (`pursuer_0` and `pursuer_1`) are optimized on the exact same +objective and thus differences in the rewards can be attributed to weight initialization +(and sampling randomness) only. +""" + +from pettingzoo.sisl import waterworld_v4 + +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnv +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + + +parser = add_rllib_example_script_args( + default_iters=200, + default_timesteps=1000000, + default_reward=0.0, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents > 0, "Must set --num-agents > 0 when running this script!" + + # Here, we use the "Agent Environment Cycle" (AEC) PettingZoo environment type. + # For a "Parallel" environment example, see the rock paper scissors examples + # in this same repository folder. + register_env("env", lambda _: PettingZooEnv(waterworld_v4.env())) + + # Policies are called just like the agents (exact 1:1 mapping). + policies = {f"pursuer_{i}" for i in range(args.num_agents)} + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env") + .multi_agent( + policies=policies, + # Exact 1:1 mapping from AgentID to ModuleID. + policy_mapping_fn=(lambda aid, *args, **kwargs: aid), + ) + .training( + vf_loss_coeff=0.005, + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={p: RLModuleSpec() for p in policies}, + ), + model_config=DefaultModelConfig(vf_share_layers=True), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_parameter_sharing.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_parameter_sharing.py new file mode 100644 index 0000000000000000000000000000000000000000..026d594dbc317273d8d5ef7cff17bbd0b4993d2f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_parameter_sharing.py @@ -0,0 +1,102 @@ +"""Runs the PettingZoo Waterworld multi-agent env in RLlib using single policy learning. + +Other than the `pettingzoo_independent_learning.py` example (in this same folder), +this example simply trains a single policy (shared by all agents). + +See: https://pettingzoo.farama.org/environments/sisl/waterworld/ +for more details on the environment. + + +How to run this script +---------------------- +`python [script file name].py --num-agents=2` + +Control the number of agents and policies (RLModules) via --num-agents and +--num-policies. + +This works with hundreds of agents and policies, but note that initializing +many policies might take some time. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +The above options can reach a combined reward of roughly ~0.0 after about 500k-1M env +timesteps. Keep in mind, though, that in this setup, the agents do not have the +opportunity to benefit from or even out other agents' mistakes (and behavior in general) +as everyone is using the same policy. Hence, this example learns a more generic policy, +which might be less specialized to certain "niche exploitation opportunities" inside +the env: + ++---------------------+----------+-----------------+--------+-----------------+ +| Trial name | status | loc | iter | total time (s) | +|---------------------+----------+-----------------+--------+-----------------+ +| PPO_env_91f49_00000 | RUNNING | 127.0.0.1:63676 | 200 | 605.176 | ++---------------------+----------+-----------------+--------+-----------------+ + ++--------+-------------------+-------------+ +| ts | combined reward | reward p0 | ++--------+-------------------+-------------| +| 800000 | 0.323752 | 0.161876 | ++--------+-------------------+-------------+ +""" +from pettingzoo.sisl import waterworld_v4 + +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnv +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + + +parser = add_rllib_example_script_args( + default_iters=200, + default_timesteps=1000000, + default_reward=0.0, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents > 0, "Must set --num-agents > 0 when running this script!" + + # Here, we use the "Agent Environment Cycle" (AEC) PettingZoo environment type. + # For a "Parallel" environment example, see the rock paper scissors examples + # in this same repository folder. + register_env("env", lambda _: PettingZooEnv(waterworld_v4.env())) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env") + .multi_agent( + policies={"p0"}, + # All agents map to the exact same policy. + policy_mapping_fn=(lambda aid, *args, **kwargs: "p0"), + ) + .training( + model={ + "vf_share_layers": True, + }, + vf_loss_coeff=0.005, + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={"p0": RLModuleSpec()}, + ), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_shared_value_function.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_shared_value_function.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c8bb9a4ffb933f99f32c65eaa167e0d75e196d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/pettingzoo_shared_value_function.py @@ -0,0 +1,7 @@ +msg = """ +This script is NOT yet ready, but will be available soon at this location. It will +feature a MultiRLModule with one shared value function and n policy heads for +cooperative multi-agent learning. +""" + +raise NotImplementedError(msg) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/rock_paper_scissors_heuristic_vs_learned.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/rock_paper_scissors_heuristic_vs_learned.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e9df60c77ff2a1f5f4485fb3c4d236057dc6ad --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/rock_paper_scissors_heuristic_vs_learned.py @@ -0,0 +1,153 @@ +"""A simple multi-agent env with two agents play rock paper scissors. + +This demonstrates running the following policies in competition: + Agent 1: heuristic policy of repeating the same move + OR: heuristic policy of beating the last opponent move + Agent 2: Simple, feedforward PPO policy + OR: PPO Policy with an LSTM network + +How to run this script +---------------------- +`python [script file name].py --num-agents=2 [--use-lstm]?` + +Without `--use-lstm`, Agent 2 should quickly reach a reward of ~7.0, always +beating the `always_same` policy, but only 50% of the time beating the `beat_last` +policy. + +With `--use-lstm`, Agent 2 should eventually(!) reach a reward of >9.0 (always +beating both the `always_same` policy and the `beat_last` policy). + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` +""" + +import random + +import gymnasium as gym +from pettingzoo.classic import rps_v2 + +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.wrappers.pettingzoo_env import ParallelPettingZooEnv +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.rllib.examples.rl_modules.classes import ( + AlwaysSameHeuristicRLM, + BeatLastHeuristicRLM, +) +from ray.tune.registry import get_trainable_cls, register_env + + +parser = add_rllib_example_script_args( + default_iters=50, + default_timesteps=200000, + default_reward=6.0, +) +parser.set_defaults( + num_agents=2, +) +parser.add_argument( + "--use-lstm", + action="store_true", + help="Whether to use an LSTM wrapped module instead of a simple MLP one. With LSTM " + "the reward diff can reach 7.0, without only 5.0.", +) + + +register_env( + "pettingzoo_rps", + lambda _: ParallelPettingZooEnv(rps_v2.parallel_env()), +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents == 2, "Must set --num-agents=2 when running this script!" + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("pettingzoo_rps") + .env_runners( + env_to_module_connector=lambda env, spaces, device: ( + # `agent_ids=...`: Only flatten obs for the learning RLModule. + FlattenObservations(multi_agent=True, agent_ids={"player_0"}), + ), + ) + .multi_agent( + policies={"always_same", "beat_last", "learned"}, + # Let learning Policy always play against either heuristic one: + # `always_same` or `beat_last`. + policy_mapping_fn=lambda aid, episode: ( + "learned" + if aid == "player_0" + else random.choice(["always_same", "beat_last"]) + ), + # Must define this as both heuristic RLMs will throw an error, if their + # `forward_train` is called. + policies_to_train=["learned"], + ) + .training( + vf_loss_coeff=0.005, + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + "always_same": RLModuleSpec( + module_class=AlwaysSameHeuristicRLM, + observation_space=gym.spaces.Discrete(4), + action_space=gym.spaces.Discrete(3), + ), + "beat_last": RLModuleSpec( + module_class=BeatLastHeuristicRLM, + observation_space=gym.spaces.Discrete(4), + action_space=gym.spaces.Discrete(3), + ), + "learned": RLModuleSpec( + model_config=DefaultModelConfig( + use_lstm=args.use_lstm, + # Use a simpler FCNet when we also have an LSTM. + fcnet_hiddens=[32] if args.use_lstm else [256, 256], + lstm_cell_size=256, + max_seq_len=15, + vf_share_layers=True, + ), + ), + } + ), + ) + ) + + # Make `args.stop_reward` "point" to the reward of the learned policy. + stop = { + TRAINING_ITERATION: args.stop_iters, + f"{ENV_RUNNER_RESULTS}/module_episode_returns_mean/learned": args.stop_reward, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + } + + run_rllib_example_script_experiment( + base_config, + args, + stop=stop, + success_metric={ + f"{ENV_RUNNER_RESULTS}/module_episode_returns_mean/learned": ( + args.stop_reward + ), + }, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/rock_paper_scissors_learned_vs_learned.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/rock_paper_scissors_learned_vs_learned.py new file mode 100644 index 0000000000000000000000000000000000000000..e8656b01db7bc78896a584c4ba71c19ac24d52ab --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/rock_paper_scissors_learned_vs_learned.py @@ -0,0 +1,92 @@ +"""A simple multi-agent env with two agents play rock paper scissors. + +This demonstrates running two learning policies in competition, both using the same +RLlib algorithm (PPO by default). + +The combined reward as well as individual rewards should roughly remain at 0.0 as no +policy should - in the long run - be able to learn a better strategy than chosing +actions at random. However, it could be possible that - for some time - one or the other +policy can exploit a "stochastic weakness" of the opponent policy. For example a policy +`A` learns that its opponent `B` has learnt to choose "paper" more often, which in +return makes `A` choose "scissors" more often as a countermeasure. +""" + +import re + +from pettingzoo.classic import rps_v2 + +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.wrappers.pettingzoo_env import ParallelPettingZooEnv +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + + +parser = add_rllib_example_script_args( + default_iters=50, + default_timesteps=200000, + default_reward=6.0, +) +parser.set_defaults( + num_agents=2, +) +parser.add_argument( + "--use-lstm", + action="store_true", + help="Whether to use an LSTM wrapped module instead of a simple MLP one. With LSTM " + "the reward diff can reach 7.0, without only 5.0.", +) + + +register_env( + "pettingzoo_rps", + lambda _: ParallelPettingZooEnv(rps_v2.parallel_env()), +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents == 2, "Must set --num-agents=2 when running this script!" + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("pettingzoo_rps") + .env_runners( + env_to_module_connector=( + lambda env, spaces, device: FlattenObservations(multi_agent=True) + ), + ) + .multi_agent( + policies={"p0", "p1"}, + # `player_0` uses `p0`, `player_1` uses `p1`. + policy_mapping_fn=lambda aid, episode: re.sub("^player_", "p", aid), + ) + .training( + vf_loss_coeff=0.005, + ) + .rl_module( + model_config=DefaultModelConfig( + use_lstm=args.use_lstm, + # Use a simpler FCNet when we also have an LSTM. + fcnet_hiddens=[32] if args.use_lstm else [256, 256], + lstm_cell_size=256, + max_seq_len=15, + vf_share_layers=True, + ), + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + "p0": RLModuleSpec(), + "p1": RLModuleSpec(), + } + ), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/self_play_league_based_with_open_spiel.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/self_play_league_based_with_open_spiel.py new file mode 100644 index 0000000000000000000000000000000000000000..9091640c07620513dae4b0755e89e447fbc31c7d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/self_play_league_based_with_open_spiel.py @@ -0,0 +1,285 @@ +"""Example showing how to implement a league-based training workflow. + +Uses the open spiel adapter of RLlib with the "markov_soccer" game and +a simplified multi-agent, league-based setup: +https://deepmind.com/blog/article/AlphaStar-Grandmaster-level-in- \ +StarCraft-II-using-multi-agent-reinforcement-learning + +Our league consists of three groups of policies: +- main policies: The current main policy plus prior versions of it. +- main exploiters: Trained by playing only against different "main policies". +- league exploiters: Trained by playing against any policy in the league. + +We start with 1 policy from each group, setting all 3 of these to an initial +PPO policy and allowing all 3 policies to be trained. +After each train update - via our custom callback - we decide for each +trainable policy, whether to make a copy and freeze it. Frozen policies +will not be altered anymore. However, they remain in the league for +future matches against trainable policies. +Matchmaking happens via a policy_mapping_fn, which needs to be altered +after every change (addition) to the league. The mapping function +randomly maps agents in a way, such that: +- Frozen main exploiters play against the one (currently trainable) main + policy. +- Trainable main exploiters play against any main policy (including already + frozen main policies). +- Frozen league exploiters play against any trainable policy in the league. +- Trainable league exploiters play against any policy in the league. + +After training for n iterations, a configurable number of episodes can +be played by the user against the "main" agent on the command line. +""" +import functools + +import numpy as np +import torch + +import ray +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.utils import try_import_pyspiel, try_import_open_spiel +from ray.rllib.env.wrappers.open_spiel import OpenSpielEnv +from ray.rllib.examples.multi_agent.utils import ( + ask_user_for_action, + SelfPlayLeagueBasedCallback, + SelfPlayLeagueBasedCallbackOldAPIStack, +) +from ray.rllib.examples._old_api_stack.policy.random_policy import RandomPolicy +from ray.rllib.examples.rl_modules.classes.random_rlm import RandomRLModule +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.utils.metrics import NUM_ENV_STEPS_SAMPLED_LIFETIME +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +open_spiel = try_import_open_spiel(error=True) +pyspiel = try_import_pyspiel(error=True) + +# Import after try_import_open_spiel, so we can error out with hints +from open_spiel.python.rl_environment import Environment # noqa: E402 + + +parser = add_rllib_example_script_args(default_timesteps=2000000) +parser.set_defaults( + env="markov_soccer", + num_env_runners=2, + checkpoint_freq=1, + checkpoint_at_end=True, +) +parser.add_argument( + "--win-rate-threshold", + type=float, + default=0.85, + help="Win-rate at which we setup another opponent by freezing the " + "current main policy and playing against a uniform distribution " + "of previously frozen 'main's from here on.", +) +parser.add_argument( + "--min-league-size", + type=float, + default=8, + help="Minimum number of policies/RLModules to consider the test passed. " + "The initial league size is 2: `main` and `random`. " + "`--min-league-size=3` thus means that one new policy/RLModule has been " + "added so far (b/c the `main` one has reached the `--win-rate-threshold " + "against the `random` Policy/RLModule).", +) +parser.add_argument( + "--num-episodes-human-play", + type=int, + default=0, + help="How many episodes to play against the user on the command " + "line after training has finished.", +) +parser.add_argument( + "--from-checkpoint", + type=str, + default=None, + help="Full path to a checkpoint file for restoring a previously saved " + "Algorithm state.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + register_env( + "open_spiel_env", + lambda _: OpenSpielEnv(pyspiel.load_game(args.env)), + ) + + def policy_mapping_fn(agent_id, episode, worker=None, **kwargs): + # At first, only have main play against the random main exploiter. + return "main" if episode.episode_id % 2 == agent_id else "main_exploiter_0" + + def agent_to_module_mapping_fn(agent_id, episode, **kwargs): + # At first, only have main play against the random main exploiter. + return "main" if hash(episode.id_) % 2 == agent_id else "main_exploiter_0" + + def _get_multi_agent(): + names = { + # Our main policy, we'd like to optimize. + "main", + # First frozen version of main (after we reach n% win-rate). + "main_0", + # Initial main exploiters (one random, one trainable). + "main_exploiter_0", + "main_exploiter_1", + # Initial league exploiters (one random, one trainable). + "league_exploiter_0", + "league_exploiter_1", + } + if not args.old_api_stack: + policies = names + spec = { + mid: RLModuleSpec( + module_class=( + RandomRLModule + if mid in ["main_exploiter_0", "league_exploiter_0"] + else None + ), + model_config=DefaultModelConfig( + fcnet_hiddens=[1024, 1024], + # fcnet_activation="tanh", + ), + ) + for mid in names + } + else: + policies = { + mid: PolicySpec( + policy_class=( + RandomPolicy + if mid in ["main_exploiter_0", "league_exploiter_0"] + else None + ) + ) + for mid in names + } + spec = None + return {"policies": policies, "spec": spec} + + config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("open_spiel_env") + # Set up the main piece in this experiment: The league-bases self-play + # callback, which controls adding new policies/Modules to the league and + # properly matching the different policies in the league with each other. + .callbacks( + functools.partial( + SelfPlayLeagueBasedCallback + if not args.old_api_stack + else SelfPlayLeagueBasedCallbackOldAPIStack, + win_rate_threshold=args.win_rate_threshold, + ) + ) + .env_runners( + num_envs_per_env_runner=1 if not args.old_api_stack else 5, + ) + .training( + num_epochs=20, + ) + .multi_agent( + # Initial policy map: All PPO. This will be expanded + # to more policy snapshots. This is done in the + # custom callback defined above (`LeagueBasedSelfPlayCallback`). + policies=_get_multi_agent()["policies"], + policy_mapping_fn=( + agent_to_module_mapping_fn + if not args.old_api_stack + else policy_mapping_fn + ), + # At first, only train main_0 (until good enough to win against + # random). + policies_to_train=["main"], + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs=_get_multi_agent()["spec"] + ), + ) + ) + + # Run everything as configured. + # Train the "main" policy to play really well using self-play. + results = None + if not args.from_checkpoint: + stop = { + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + TRAINING_ITERATION: args.stop_iters, + "league_size": args.min_league_size, + } + results = run_rllib_example_script_experiment( + config, args, stop=stop, keep_ray_up=True + ) + + # Restore trained Algorithm (set to non-explore behavior) and play against + # human on command line. + if args.num_episodes_human_play > 0: + num_episodes = 0 + # Switch off exploration for better inference performance. + config.explore = False + algo = config.build() + if args.from_checkpoint: + algo.restore(args.from_checkpoint) + else: + checkpoint = results.get_best_result().checkpoint + if not checkpoint: + raise ValueError("No last checkpoint found in results!") + algo.restore(checkpoint) + + if not args.old_api_stack: + rl_module = algo.get_module("main") + + # Play from the command line against the trained agent + # in an actual (non-RLlib-wrapped) open-spiel env. + human_player = 1 + env = Environment(args.env) + + while num_episodes < args.num_episodes_human_play: + print("You play as {}".format("o" if human_player else "x")) + time_step = env.reset() + while not time_step.last(): + player_id = time_step.observations["current_player"] + if player_id == human_player: + action = ask_user_for_action(time_step) + else: + obs = np.array(time_step.observations["info_state"][player_id]) + if not args.old_api_stack: + action = np.argmax( + rl_module.forward_inference( + {"obs": torch.from_numpy(obs).unsqueeze(0).float()} + )["action_dist_inputs"][0].numpy() + ) + else: + action = algo.compute_single_action(obs, policy_id="main") + # In case computer chooses an invalid action, pick a + # random one. + legal = time_step.observations["legal_actions"][player_id] + if action not in legal: + action = np.random.choice(legal) + time_step = env.step([action]) + print(f"\n{env.get_state}") + + print(f"\n{env.get_state}") + + print("End of game!") + if time_step.rewards[human_player] > 0: + print("You win") + elif time_step.rewards[human_player] < 0: + print("You lose") + else: + print("Draw") + # Switch order of players + human_player = 1 - human_player + + num_episodes += 1 + + algo.stop() + + ray.shutdown() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/self_play_with_open_spiel.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/self_play_with_open_spiel.py new file mode 100644 index 0000000000000000000000000000000000000000..f55208ac0fa087bf5177c84e174ce635b815d0ee --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/self_play_with_open_spiel.py @@ -0,0 +1,248 @@ +"""Example showing how one can implement a simple self-play training workflow. + +Uses the open spiel adapter of RLlib with the "connect_four" game and +a multi-agent setup with a "main" policy and n "main_v[x]" policies +(x=version number), which are all at-some-point-frozen copies of +"main". At the very beginning, "main" plays against RandomPolicy. + +Checks for the training progress after each training update via a custom +callback. We simply measure the win rate of "main" vs the opponent +("main_v[x]" or RandomPolicy at the beginning) by looking through the +achieved rewards in the episodes in the train batch. If this win rate +reaches some configurable threshold, we add a new policy to +the policy map (a frozen copy of the current "main" one) and change the +policy_mapping_fn to make new matches of "main" vs any of the previous +versions of "main" (including the just added one). + +After training for n iterations, a configurable number of episodes can +be played by the user against the "main" agent on the command line. +""" + +import functools + +import numpy as np +import torch + +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.utils import try_import_pyspiel, try_import_open_spiel +from ray.rllib.env.wrappers.open_spiel import OpenSpielEnv +from ray.rllib.examples.rl_modules.classes.random_rlm import RandomRLModule +from ray.rllib.examples.multi_agent.utils import ( + ask_user_for_action, + SelfPlayCallback, + SelfPlayCallbackOldAPIStack, +) +from ray.rllib.examples._old_api_stack.policy.random_policy import RandomPolicy +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.utils.metrics import NUM_ENV_STEPS_SAMPLED_LIFETIME +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +open_spiel = try_import_open_spiel(error=True) +pyspiel = try_import_pyspiel(error=True) + +# Import after try_import_open_spiel, so we can error out with hints. +from open_spiel.python.rl_environment import Environment # noqa: E402 + + +parser = add_rllib_example_script_args(default_timesteps=2000000) +parser.set_defaults( + env="connect_four", + checkpoint_freq=1, + checkpoint_at_end=True, +) +parser.add_argument( + "--win-rate-threshold", + type=float, + default=0.95, + help="Win-rate at which we setup another opponent by freezing the " + "current main policy and playing against a uniform distribution " + "of previously frozen 'main's from here on.", +) +parser.add_argument( + "--min-league-size", + type=float, + default=3, + help="Minimum number of policies/RLModules to consider the test passed. " + "The initial league size is 2: `main` and `random`. " + "`--min-league-size=3` thus means that one new policy/RLModule has been " + "added so far (b/c the `main` one has reached the `--win-rate-threshold " + "against the `random` Policy/RLModule).", +) +parser.add_argument( + "--num-episodes-human-play", + type=int, + default=10, + help="How many episodes to play against the user on the command " + "line after training has finished.", +) +parser.add_argument( + "--from-checkpoint", + type=str, + default=None, + help="Full path to a checkpoint file for restoring a previously saved " + "Algorithm state.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + register_env("open_spiel_env", lambda _: OpenSpielEnv(pyspiel.load_game(args.env))) + + def agent_to_module_mapping_fn(agent_id, episode, **kwargs): + # agent_id = [0|1] -> module depends on episode ID + # This way, we make sure that both modules sometimes play agent0 + # (start player) and sometimes agent1 (player to move 2nd). + return "main" if hash(episode.id_) % 2 == agent_id else "random" + + def policy_mapping_fn(agent_id, episode, worker, **kwargs): + # e.g. episode ID = 10234 + # -> agent `0` -> main (b/c epsID % 2 == 0) + # -> agent `1` -> random (b/c epsID % 2 == 1) + return "main" if episode.episode_id % 2 == agent_id else "random" + + config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("open_spiel_env") + # Set up the main piece in this experiment: The league-bases self-play + # callback, which controls adding new policies/Modules to the league and + # properly matching the different policies in the league with each other. + .callbacks( + functools.partial( + ( + SelfPlayCallback + if not args.old_api_stack + else SelfPlayCallbackOldAPIStack + ), + win_rate_threshold=args.win_rate_threshold, + ) + ) + .env_runners( + num_env_runners=(args.num_env_runners or 2), + num_envs_per_env_runner=1 if not args.old_api_stack else 5, + ) + .multi_agent( + # Initial policy map: Random and default algo one. This will be expanded + # to more policy snapshots taken from "main" against which "main" + # will then play (instead of "random"). This is done in the + # custom callback defined above (`SelfPlayCallback`). + policies=( + { + # Our main policy, we'd like to optimize. + "main": PolicySpec(), + # An initial random opponent to play against. + "random": PolicySpec(policy_class=RandomPolicy), + } + if args.old_api_stack + else {"main", "random"} + ), + # Assign agent 0 and 1 randomly to the "main" policy or + # to the opponent ("random" at first). Make sure (via episode_id) + # that "main" always plays against "random" (and not against + # another "main"). + policy_mapping_fn=( + agent_to_module_mapping_fn + if not args.old_api_stack + else policy_mapping_fn + ), + # Always just train the "main" policy. + policies_to_train=["main"], + ) + .rl_module( + model_config=DefaultModelConfig(fcnet_hiddens=[512, 512]), + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + "main": RLModuleSpec(), + "random": RLModuleSpec(module_class=RandomRLModule), + } + ), + ) + ) + + # Only for PPO, change the `num_epochs` setting. + if args.algo == "PPO": + config.training(num_epochs=20) + + stop = { + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + TRAINING_ITERATION: args.stop_iters, + "league_size": args.min_league_size, + } + + # Train the "main" policy to play really well using self-play. + results = None + if not args.from_checkpoint: + results = run_rllib_example_script_experiment( + config, args, stop=stop, keep_ray_up=True + ) + + # Restore trained Algorithm (set to non-explore behavior) and play against + # human on command line. + if args.num_episodes_human_play > 0: + num_episodes = 0 + config.explore = False + algo = config.build() + if args.from_checkpoint: + algo.restore(args.from_checkpoint) + else: + checkpoint = results.get_best_result().checkpoint + if not checkpoint: + raise ValueError("No last checkpoint found in results!") + algo.restore(checkpoint) + + if not args.old_api_stack: + rl_module = algo.get_module("main") + + # Play from the command line against the trained agent + # in an actual (non-RLlib-wrapped) open-spiel env. + human_player = 1 + env = Environment(args.env) + + while num_episodes < args.num_episodes_human_play: + print("You play as {}".format("o" if human_player else "x")) + time_step = env.reset() + while not time_step.last(): + player_id = time_step.observations["current_player"] + if player_id == human_player: + action = ask_user_for_action(time_step) + else: + obs = np.array(time_step.observations["info_state"][player_id]) + if not args.old_api_stack: + action = np.argmax( + rl_module.forward_inference( + {"obs": torch.from_numpy(obs).unsqueeze(0).float()} + )["action_dist_inputs"][0].numpy() + ) + else: + action = algo.compute_single_action(obs, policy_id="main") + # In case computer chooses an invalid action, pick a + # random one. + legal = time_step.observations["legal_actions"][player_id] + if action not in legal: + action = np.random.choice(legal) + time_step = env.step([action]) + print(f"\n{env.get_state}") + + print(f"\n{env.get_state}") + + print("End of game!") + if time_step.rewards[human_player] > 0: + print("You win") + elif time_step.rewards[human_player] < 0: + print("You lose") + else: + print("Draw") + # Switch order of players. + human_player = 1 - human_player + + num_episodes += 1 + + algo.stop() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/two_step_game_with_grouped_agents.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/two_step_game_with_grouped_agents.py new file mode 100644 index 0000000000000000000000000000000000000000..2c4871c77145748c438dd2f3431d8fd28ed78e9a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/two_step_game_with_grouped_agents.py @@ -0,0 +1,91 @@ +"""The two-step game from the QMIX paper: +https://arxiv.org/pdf/1803.11485.pdf + +See also: rllib/examples/centralized_critic.py for centralized critic PPO on this game. + +How to run this script +---------------------- +`python [script file name].py --num-agents=2` + +Note that in this script, we use an multi-agent environment in which both +agents that normally play this game have been merged into one agent with ID +"agents" and observation- and action-spaces being 2-tupled (1 item for each +agent). The "agents" agent is mapped to the policy with ID "p0". + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +Which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect a reward of 8.0 (the max to reach in thie game) eventually +being achieved by a simple PPO policy (no tuning, just using RLlib's default settings): + ++---------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|---------------------------------+------------+-----------------+--------+ +| PPO_grouped_twostep_4354b_00000 | TERMINATED | 127.0.0.1:42602 | 20 | ++---------------------------------+------------+-----------------+--------+ + ++------------------+-------+-------------------+-------------+ +| total time (s) | ts | combined reward | reward p0 | ++------------------+-------+-------------------+-------------| +| 87.5756 | 80000 | 8 | 8 | ++------------------+-------+-------------------+-------------+ +""" + +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.envs.classes.multi_agent.two_step_game import ( + TwoStepGameWithGroupedAgents, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import register_env, get_trainable_cls + + +parser = add_rllib_example_script_args(default_reward=7.0) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents == 2, "Must set --num-agents=2 when running this script!" + + register_env( + "grouped_twostep", + lambda config: TwoStepGameWithGroupedAgents(config), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("grouped_twostep") + .env_runners( + env_to_module_connector=lambda env, spaces, device: FlattenObservations( + multi_agent=True + ), + ) + .multi_agent( + policies={"p0"}, + policy_mapping_fn=lambda aid, *a, **kw: "p0", + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + "p0": RLModuleSpec(), + }, + ) + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f61ce378bce38dcc3a1a07b33f0df450829168 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__init__.py @@ -0,0 +1,43 @@ +import sys + +from ray.rllib.examples.multi_agent.utils.self_play_callback import SelfPlayCallback +from ray.rllib.examples.multi_agent.utils.self_play_league_based_callback import ( + SelfPlayLeagueBasedCallback, +) +from ray.rllib.examples.multi_agent.utils.self_play_callback_old_api_stack import ( + SelfPlayCallbackOldAPIStack, +) +from ray.rllib.examples.multi_agent.utils.self_play_league_based_callback_old_api_stack import ( # noqa + SelfPlayLeagueBasedCallbackOldAPIStack, +) + + +def ask_user_for_action(time_step): + """Asks the user for a valid action on the command line and returns it. + + Re-queries the user until she picks a valid one. + + Args: + time_step: The open spiel Environment time-step object. + """ + pid = time_step.observations["current_player"] + legal_moves = time_step.observations["legal_actions"][pid] + choice = -1 + while choice not in legal_moves: + print("Choose an action from {}:".format(legal_moves)) + sys.stdout.flush() + choice_str = input() + try: + choice = int(choice_str) + except ValueError: + continue + return choice + + +__all__ = [ + "ask_user_for_action", + "SelfPlayCallback", + "SelfPlayLeagueBasedCallback", + "SelfPlayCallbackOldAPIStack", + "SelfPlayLeagueBasedCallbackOldAPIStack", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d80f29e0dbe78c0c3b2a5ae490dc2628d2520f9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_callback.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_callback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8bfd21a54b950685c842df4ffc27f120edaaa55 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_callback.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_callback_old_api_stack.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_callback_old_api_stack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ac9b2b6873d93f2f3409f787c13fe53300cd782 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_callback_old_api_stack.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_league_based_callback.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_league_based_callback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f887c35753807638ba32920742f6c7e19aa9cca Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_league_based_callback.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_league_based_callback_old_api_stack.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_league_based_callback_old_api_stack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96a74363ff8cd71a9fc2d324a855859a87451b18 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/__pycache__/self_play_league_based_callback_old_api_stack.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..99b6abc8a59ace21684083f8121993f27fcce1de --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback.py @@ -0,0 +1,97 @@ +from collections import defaultdict + +import numpy as np + +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.metrics import ENV_RUNNER_RESULTS + + +class SelfPlayCallback(RLlibCallback): + def __init__(self, win_rate_threshold): + super().__init__() + # 0=RandomPolicy, 1=1st main policy snapshot, + # 2=2nd main policy snapshot, etc.. + self.current_opponent = 0 + + self.win_rate_threshold = win_rate_threshold + + # Report the matchup counters (who played against whom?). + self._matching_stats = defaultdict(int) + + def on_episode_end( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + # Compute the win rate for this episode and log it with a window of 100. + main_agent = 0 if episode.module_for(0) == "main" else 1 + rewards = episode.get_rewards() + if main_agent in rewards: + main_won = rewards[main_agent][-1] == 1.0 + metrics_logger.log_value( + "win_rate", + main_won, + reduce="mean", + window=100, + ) + + def on_train_result(self, *, algorithm, metrics_logger=None, result, **kwargs): + win_rate = result[ENV_RUNNER_RESULTS]["win_rate"] + print(f"Iter={algorithm.iteration} win-rate={win_rate} -> ", end="") + # If win rate is good -> Snapshot current policy and play against + # it next, keeping the snapshot fixed and only improving the "main" + # policy. + if win_rate > self.win_rate_threshold: + self.current_opponent += 1 + new_module_id = f"main_v{self.current_opponent}" + print(f"adding new opponent to the mix ({new_module_id}).") + + # Re-define the mapping function, such that "main" is forced + # to play against any of the previously played modules + # (excluding "random"). + def agent_to_module_mapping_fn(agent_id, episode, **kwargs): + # agent_id = [0|1] -> policy depends on episode ID + # This way, we make sure that both modules sometimes play + # (start player) and sometimes agent1 (player to move 2nd). + opponent = "main_v{}".format( + np.random.choice(list(range(1, self.current_opponent + 1))) + ) + if hash(episode.id_) % 2 == agent_id: + self._matching_stats[("main", opponent)] += 1 + return "main" + else: + return opponent + + main_module = algorithm.get_module("main") + algorithm.add_module( + module_id=new_module_id, + module_spec=RLModuleSpec.from_module(main_module), + new_agent_to_module_mapping_fn=agent_to_module_mapping_fn, + ) + # TODO (sven): Maybe we should move this convenience step back into + # `Algorithm.add_module()`? Would be less explicit, but also easier. + algorithm.set_state( + { + "learner_group": { + "learner": { + "rl_module": { + new_module_id: main_module.get_state(), + } + } + } + } + ) + else: + print("not good enough; will keep learning ...") + + # +2 = main + random + result["league_size"] = self.current_opponent + 2 + + print(f"Matchups:\n{self._matching_stats}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback_old_api_stack.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback_old_api_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..42b05b94501708de34f3653150e384b3c95f4818 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback_old_api_stack.py @@ -0,0 +1,78 @@ +import numpy as np + +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.metrics import ENV_RUNNER_RESULTS + + +@Deprecated(help="Use the example for the new RLlib API stack.", error=False) +class SelfPlayCallbackOldAPIStack(RLlibCallback): + def __init__(self, win_rate_threshold): + super().__init__() + # 0=RandomPolicy, 1=1st main policy snapshot, + # 2=2nd main policy snapshot, etc.. + self.current_opponent = 0 + + self.win_rate_threshold = win_rate_threshold + + def on_train_result(self, *, algorithm, result, **kwargs): + # Get the win rate for the train batch. + # Note that normally, you should set up a proper evaluation config, + # such that evaluation always happens on the already updated policy, + # instead of on the already used train_batch. + main_rew = result[ENV_RUNNER_RESULTS]["hist_stats"].pop("policy_main_reward") + opponent_rew = list(result[ENV_RUNNER_RESULTS]["hist_stats"].values())[0] + assert len(main_rew) == len(opponent_rew) + won = 0 + for r_main, r_opponent in zip(main_rew, opponent_rew): + if r_main > r_opponent: + won += 1 + win_rate = won / len(main_rew) + result["win_rate"] = win_rate + print(f"Iter={algorithm.iteration} win-rate={win_rate} -> ", end="") + # If win rate is good -> Snapshot current policy and play against + # it next, keeping the snapshot fixed and only improving the "main" + # policy. + if win_rate > self.win_rate_threshold: + self.current_opponent += 1 + new_pol_id = f"main_v{self.current_opponent}" + print(f"adding new opponent to the mix ({new_pol_id}).") + + # Re-define the mapping function, such that "main" is forced + # to play against any of the previously played policies + # (excluding "random"). + def policy_mapping_fn(agent_id, episode, worker, **kwargs): + # agent_id = [0|1] -> policy depends on episode ID + # This way, we make sure that both policies sometimes play + # (start player) and sometimes agent1 (player to move 2nd). + return ( + "main" + if episode.episode_id % 2 == agent_id + else "main_v{}".format( + np.random.choice(list(range(1, self.current_opponent + 1))) + ) + ) + + main_policy = algorithm.get_policy("main") + new_policy = algorithm.add_policy( + policy_id=new_pol_id, + policy_cls=type(main_policy), + policy_mapping_fn=policy_mapping_fn, + config=main_policy.config, + observation_space=main_policy.observation_space, + action_space=main_policy.action_space, + ) + + # Set the weights of the new policy to the main policy. + # We'll keep training the main policy, whereas `new_pol_id` will + # remain fixed. + main_state = main_policy.get_state() + new_policy.set_state(main_state) + # We need to sync the just copied local weights (from main policy) + # to all the remote workers as well. + algorithm.env_runner_group.sync_weights() + else: + print("not good enough; will keep learning ...") + + # +2 = main + random + result["league_size"] = self.current_opponent + 2 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_league_based_callback.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_league_based_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..782e723188187bb82ce32b951ffbebc70efa3b47 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_league_based_callback.py @@ -0,0 +1,299 @@ +from collections import defaultdict +from pprint import pprint +import re + +import numpy as np + +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.metrics import ENV_RUNNER_RESULTS + + +class SelfPlayLeagueBasedCallback(RLlibCallback): + def __init__(self, win_rate_threshold): + super().__init__() + # All policies in the league. + self.main_policies = {"main", "main_0"} + self.main_exploiters = {"main_exploiter_0", "main_exploiter_1"} + self.league_exploiters = {"league_exploiter_0", "league_exploiter_1"} + # Set of currently trainable policies in the league. + self.trainable_policies = {"main"} + # Set of currently non-trainable (frozen) policies in the league. + self.non_trainable_policies = { + "main_0", + "league_exploiter_0", + "main_exploiter_0", + } + # The win-rate value reaching of which leads to a new module being added + # to the leage (frozen copy of main). + self.win_rate_threshold = win_rate_threshold + # Store the win rates for league overview printouts. + self.win_rates = {} + + # Report the matchup counters (who played against whom?). + self._matching_stats = defaultdict(int) + + def on_episode_end( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + + num_learning_policies = ( + episode.module_for(0) in env_runner.config.policies_to_train + ) + (episode.module_for(1) in env_runner.config.policies_to_train) + # Make sure the mapping function doesn't match two non-trainables together. + # This would be a waste of EnvRunner resources. + # assert num_learning_policies > 0 + # Ignore matches between two learning policies and don't count win-rates for + # these. + assert num_learning_policies > 0, ( + f"agent=0 -> mod={episode.module_for(0)}; " + f"agent=1 -> mod={episode.module_for(1)}; " + f"EnvRunner.config.policies_to_train={env_runner.config.policies_to_train}" + ) + if num_learning_policies == 1: + # Compute the win rate for this episode (only looking at non-trained + # opponents, such as random or frozen policies) and log it with some window. + rewards_dict = episode.get_rewards() + for aid, rewards in rewards_dict.items(): + mid = episode.module_for(aid) + won = rewards[-1] == 1.0 + metrics_logger.log_value( + f"win_rate_{mid}", + won, + window=100, + ) + + def on_train_result(self, *, algorithm, metrics_logger=None, result, **kwargs): + local_worker = algorithm.env_runner + + # Avoid `self` being pickled into the remote function below. + _trainable_policies = self.trainable_policies + + # Get the win rate for the train batch. + # Note that normally, one should set up a proper evaluation config, + # such that evaluation always happens on the already updated policy, + # instead of on the already used train_batch. + league_changed = False + keys = [ + k for k in result[ENV_RUNNER_RESULTS].keys() if k.startswith("win_rate_") + ] + for key in keys: + module_id = key[9:] + self.win_rates[module_id] = result[ENV_RUNNER_RESULTS][key] + + # Policy is frozen; ignore. + if module_id in self.non_trainable_policies: + continue + + print( + f"Iter={algorithm.iteration} {module_id}'s " + f"win-rate={self.win_rates[module_id]} -> ", + end="", + ) + + # If win rate is good -> Snapshot current policy and decide, + # whether to freeze the copy or not. + if self.win_rates[module_id] > self.win_rate_threshold: + is_main = re.match("^main(_\\d+)?$", module_id) + initializing_exploiters = False + + # First time, main manages a decent win-rate against random: + # Add league_exploiter_1 and main_exploiter_1 as trainables to the mix. + if is_main and len(self.trainable_policies) == 1: + initializing_exploiters = True + self.trainable_policies.add("league_exploiter_1") + self.trainable_policies.add("main_exploiter_1") + # If main manages to win (above threshold) against the entire league + # -> increase the league by another frozen copy of main, + # main-exploiters or league-exploiters. + else: + keep_training = ( + False + if is_main + else np.random.choice([True, False], p=[0.3, 0.7]) + ) + if module_id in self.main_policies: + new_mod_id = re.sub( + "(main)(_\\d+)?$", + f"\\1_{len(self.main_policies) - 1}", + module_id, + ) + self.main_policies.add(new_mod_id) + elif module_id in self.main_exploiters: + new_mod_id = re.sub( + "_\\d+$", f"_{len(self.main_exploiters)}", module_id + ) + self.main_exploiters.add(new_mod_id) + else: + new_mod_id = re.sub( + "_\\d+$", f"_{len(self.league_exploiters)}", module_id + ) + self.league_exploiters.add(new_mod_id) + + if keep_training: + self.trainable_policies.add(new_mod_id) + else: + self.non_trainable_policies.add(new_mod_id) + + print(f"adding new opponents to the mix ({new_mod_id}).") + + # Initialize state variablers for agent-to-module mapping. Note, we + # need to keep track of the league-exploiter to always match a + # non-trainable policy with a trainable one - otherwise matches are + # a waste of resources. + self.type_count = 0 + self.exploiter = None + + def agent_to_module_mapping_fn(agent_id, episode, **kwargs): + # Pick whether this is ... + type_ = np.random.choice([1, 2]) + + # Each second third call reset state variables. Note, there will + # be always two agents playing against each others. + if self.type_count >= 2: + # Reset the counter. + self.type_count = 0 + # Set the exploiter to `None`. + self.exploiter = None + + # Increment the counter for each agent. + self.type_count += 1 + + # 1) League exploiter vs any other. + if type_ == 1: + # Note, the exploiter could be either of `type_==1` or `type_==2`. + if not self.exploiter: + self.exploiter = "league_exploiter_" + str( + np.random.choice( + list(range(len(self.league_exploiters))) + ) + ) + # This league exploiter is frozen: Play against a + # trainable policy. + if self.exploiter not in self.trainable_policies: + opponent = np.random.choice(list(self.trainable_policies)) + # League exploiter is trainable: Play against any other + # non-trainable policy. + else: + opponent = np.random.choice( + list(self.non_trainable_policies) + ) + + # Only record match stats once per match. + if hash(episode.id_) % 2 == agent_id: + self._matching_stats[(self.exploiter, opponent)] += 1 + return self.exploiter + else: + return opponent + + # 2) Main exploiter vs main. + else: + # Note, the exploiter could be either of `type_==1` or `type_==2`. + if not self.exploiter: + self.exploiter = "main_exploiter_" + str( + np.random.choice(list(range(len(self.main_exploiters)))) + ) + # Main exploiter is frozen: Play against the main + # policy. + if self.exploiter not in self.trainable_policies: + main = "main" + # Main exploiter is trainable: Play against any + # frozen main. + else: + main = np.random.choice(list(self.main_policies - {"main"})) + + # Only record match stats once per match. + if hash(episode.id_) % 2 == agent_id: + self._matching_stats[(self.exploiter, main)] += 1 + return self.exploiter + else: + return main + + multi_rl_module = local_worker.module + main_module = multi_rl_module["main"] + + # Set the weights of the new polic(y/ies). + if initializing_exploiters: + main_state = main_module.get_state() + multi_rl_module["main_0"].set_state(main_state) + multi_rl_module["league_exploiter_1"].set_state(main_state) + multi_rl_module["main_exploiter_1"].set_state(main_state) + # We need to sync the just copied local weights to all the + # remote workers and remote Learner workers as well. + algorithm.env_runner_group.sync_weights( + policies=["main_0", "league_exploiter_1", "main_exploiter_1"] + ) + algorithm.learner_group.set_weights(multi_rl_module.get_state()) + else: + algorithm.add_module( + module_id=new_mod_id, + module_spec=RLModuleSpec.from_module(main_module), + ) + # TODO (sven): Maybe we should move this convenience step back into + # `Algorithm.add_module()`? Would be less explicit, but also + # easier. + algorithm.set_state( + { + "learner_group": { + "learner": { + "rl_module": { + new_mod_id: multi_rl_module[ + module_id + ].get_state(), + } + } + } + } + ) + + algorithm.env_runner_group.foreach_env_runner( + lambda env_runner: env_runner.config.multi_agent( + policy_mapping_fn=agent_to_module_mapping_fn, + # This setting doesn't really matter for EnvRunners (no + # training going on there, but we'll update this as well + # here for good measure). + policies_to_train=_trainable_policies, + ), + local_env_runner=True, + ) + # Set all Learner workers' should_module_be_updated to the new + # value. + algorithm.learner_group.foreach_learner( + func=lambda learner: learner.config.multi_agent( + policies_to_train=_trainable_policies, + ), + timeout_seconds=0.0, # fire-and-forget + ) + league_changed = True + else: + print("not good enough; will keep learning ...") + + # Add current league size to results dict. + result["league_size"] = len(self.non_trainable_policies) + len( + self.trainable_policies + ) + + if league_changed: + self._print_league() + + def _print_league(self): + print("--- League ---") + print("Matchups:") + pprint(self._matching_stats) + print("Trainable policies (win-rates):") + for p in sorted(self.trainable_policies): + wr = self.win_rates[p] if p in self.win_rates else 0.0 + print(f"\t{p}: {wr}") + print("Frozen policies:") + for p in sorted(self.non_trainable_policies): + wr = self.win_rates[p] if p in self.win_rates else 0.0 + print(f"\t{p}: {wr}") + print() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_league_based_callback_old_api_stack.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_league_based_callback_old_api_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..dc39fa8fac9a7ba658aefdd2edeb4199097aaa2b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/multi_agent/utils/self_play_league_based_callback_old_api_stack.py @@ -0,0 +1,201 @@ +import re + +import numpy as np + +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.metrics import ENV_RUNNER_RESULTS + + +@Deprecated(help="Use the example for the new RLlib API stack", error=False) +class SelfPlayLeagueBasedCallbackOldAPIStack(RLlibCallback): + def __init__(self, win_rate_threshold): + super().__init__() + # All policies in the league. + self.main_policies = {"main", "main_0"} + self.main_exploiters = {"main_exploiter_0", "main_exploiter_1"} + self.league_exploiters = {"league_exploiter_0", "league_exploiter_1"} + # Set of currently trainable policies in the league. + self.trainable_policies = {"main"} + # Set of currently non-trainable (frozen) policies in the league. + self.non_trainable_policies = { + "main_0", + "league_exploiter_0", + "main_exploiter_0", + } + # The win-rate value reaching of which leads to a new module being added + # to the leage (frozen copy of main). + self.win_rate_threshold = win_rate_threshold + # Store the win rates for league overview printouts. + self.win_rates = {} + + def on_train_result(self, *, algorithm, result, **kwargs): + # Avoid `self` being pickled into the remote function below. + _trainable_policies = self.trainable_policies + + # Get the win rate for the train batch. + # Note that normally, you should set up a proper evaluation config, + # such that evaluation always happens on the already updated policy, + # instead of on the already used train_batch. + for policy_id, rew in result[ENV_RUNNER_RESULTS]["hist_stats"].items(): + mo = re.match("^policy_(.+)_reward$", policy_id) + if mo is None: + continue + policy_id = mo.group(1) + + # Calculate this policy's win rate. + won = 0 + for r in rew: + if r > 0.0: # win = 1.0; loss = -1.0 + won += 1 + win_rate = won / len(rew) + self.win_rates[policy_id] = win_rate + + # Policy is frozen; ignore. + if policy_id in self.non_trainable_policies: + continue + + print( + f"Iter={algorithm.iteration} {policy_id}'s " f"win-rate={win_rate} -> ", + end="", + ) + + # If win rate is good -> Snapshot current policy and decide, + # whether to freeze the copy or not. + if win_rate > self.win_rate_threshold: + is_main = re.match("^main(_\\d+)?$", policy_id) + initializing_exploiters = False + + # First time, main manages a decent win-rate against random: + # Add league_exploiter_0 and main_exploiter_0 to the mix. + if is_main and len(self.trainable_policies) == 1: + initializing_exploiters = True + self.trainable_policies.add("league_exploiter_0") + self.trainable_policies.add("main_exploiter_0") + else: + keep_training = ( + False + if is_main + else np.random.choice([True, False], p=[0.3, 0.7]) + ) + if policy_id in self.main_policies: + new_pol_id = re.sub( + "_\\d+$", f"_{len(self.main_policies) - 1}", policy_id + ) + self.main_policies.add(new_pol_id) + elif policy_id in self.main_exploiters: + new_pol_id = re.sub( + "_\\d+$", f"_{len(self.main_exploiters)}", policy_id + ) + self.main_exploiters.add(new_pol_id) + else: + new_pol_id = re.sub( + "_\\d+$", f"_{len(self.league_exploiters)}", policy_id + ) + self.league_exploiters.add(new_pol_id) + + if keep_training: + self.trainable_policies.add(new_pol_id) + else: + self.non_trainable_policies.add(new_pol_id) + + print(f"adding new opponents to the mix ({new_pol_id}).") + + # Update our mapping function accordingly. + def policy_mapping_fn(agent_id, episode, worker=None, **kwargs): + # Pick, whether this is ... + type_ = np.random.choice([1, 2]) + + # 1) League exploiter vs any other. + if type_ == 1: + league_exploiter = "league_exploiter_" + str( + np.random.choice(list(range(len(self.league_exploiters)))) + ) + # This league exploiter is frozen: Play against a + # trainable policy. + if league_exploiter not in self.trainable_policies: + opponent = np.random.choice(list(self.trainable_policies)) + # League exploiter is trainable: Play against any other + # non-trainable policy. + else: + opponent = np.random.choice( + list(self.non_trainable_policies) + ) + print(f"{league_exploiter} vs {opponent}") + return ( + league_exploiter + if episode.episode_id % 2 == agent_id + else opponent + ) + + # 2) Main exploiter vs main. + else: + main_exploiter = "main_exploiter_" + str( + np.random.choice(list(range(len(self.main_exploiters)))) + ) + # Main exploiter is frozen: Play against the main + # policy. + if main_exploiter not in self.trainable_policies: + main = "main" + # Main exploiter is trainable: Play against any + # frozen main. + else: + main = np.random.choice(list(self.main_policies - {"main"})) + # print(f"{main_exploiter} vs {main}") + return ( + main_exploiter + if episode.episode_id % 2 == agent_id + else main + ) + + # Set the weights of the new polic(y/ies). + if initializing_exploiters: + main_state = algorithm.get_policy("main").get_state() + pol_map = algorithm.env_runner.policy_map + pol_map["main_0"].set_state(main_state) + pol_map["league_exploiter_1"].set_state(main_state) + pol_map["main_exploiter_1"].set_state(main_state) + # We need to sync the just copied local weights to all the + # remote workers as well. + algorithm.env_runner_group.sync_weights( + policies=["main_0", "league_exploiter_1", "main_exploiter_1"] + ) + + def _set(worker): + worker.set_policy_mapping_fn(policy_mapping_fn) + worker.set_is_policy_to_train(_trainable_policies) + + algorithm.env_runner_group.foreach_env_runner(_set) + else: + base_pol = algorithm.get_policy(policy_id) + new_policy = algorithm.add_policy( + policy_id=new_pol_id, + policy_cls=type(base_pol), + policy_mapping_fn=policy_mapping_fn, + policies_to_train=self.trainable_policies, + config=base_pol.config, + observation_space=base_pol.observation_space, + action_space=base_pol.action_space, + ) + main_state = base_pol.get_state() + new_policy.set_state(main_state) + # We need to sync the just copied local weights to all the + # remote workers as well. + algorithm.env_runner_group.sync_weights(policies=[new_pol_id]) + + self._print_league() + + else: + print("not good enough; will keep learning ...") + + def _print_league(self): + print("--- League ---") + print("Trainable policies (win-rates):") + for p in sorted(self.trainable_policies): + wr = self.win_rates[p] if p in self.win_rates else 0.0 + print(f"\t{p}: {wr}") + print("Frozen policies:") + for p in sorted(self.non_trainable_policies): + wr = self.win_rates[p] if p in self.win_rates else 0.0 + print(f"\t{p}: {wr}") + print() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8df94a0f1f279a29df5493a12d174e1c9b90bae6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/cartpole_recording.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/cartpole_recording.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1d2f16298da3335231afb07eb6d4fbe014e933f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/cartpole_recording.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/custom_input_api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/custom_input_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d231d72f9b39db72adc0d2a9aeea99307c8c6d51 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/custom_input_api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/offline_rl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/offline_rl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1be4d94ea8c22d4ccf74ab2076bf5b9a6cbd6995 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/offline_rl.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/offline_rl_with_image_data.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/offline_rl_with_image_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55a39130d28b9aeacb5b581c10ae5b7f3b0104c3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/offline_rl_with_image_data.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/pretrain_bc_single_agent_evaluate_as_multi_agent.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/pretrain_bc_single_agent_evaluate_as_multi_agent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c32a258689ee0825408c6bb11f00c520a8becd3e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/pretrain_bc_single_agent_evaluate_as_multi_agent.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/saving_experiences.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/saving_experiences.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e10b170777489cb71babc20d5321936decdfa865 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/saving_experiences.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/train_w_bc_finetune_w_ppo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/train_w_bc_finetune_w_ppo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6b0ec0eff032321301a507e72f0cfdb8f0423a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/__pycache__/train_w_bc_finetune_w_ppo.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/cartpole_recording.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/cartpole_recording.py new file mode 100644 index 0000000000000000000000000000000000000000..f1e0db30407b82a075e9aae5b16f3062fa49fb66 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/cartpole_recording.py @@ -0,0 +1,166 @@ +"""Example showing how to record expert data from a trained policy. + +This example: + - demonstrates how you can train a single-agent expert PPO Policy (RLModule) + and checkpoint it. + - shows how you can then record expert data from the trained PPO Policy to + disk during evaluation. + +How to run this script +---------------------- +`python [script file name].py --checkpoint-at-end` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +Results to expect +----------------- +In the console output you can see that the episode return of 350.0 is reached +before the timestep stop criteria is touched. Afterwards evaluation starts and +runs 10 iterations while recording the data. The number of recorded experiences +might differ from evaluation run to evaluation run because evaluation +`EnvRunner`s sample episodes while recording timesteps and episodes contain +usually different numbers of timesteps. Note, this is different when recording +episodes - in this case each row is one episode. + ++-----------------------------+------------+----------------------+ +| Trial name | status | loc | +| | | | +|-----------------------------+------------+----------------------+ +| PPO_CartPole-v1_df83f_00000 | TERMINATED | 192.168.0.119:233661 | ++-----------------------------+------------+----------------------+ ++--------+------------------+------------------------+------------------------+ +| iter | total time (s) | num_training_step_ca | num_env_steps_sample | +| | | lls_per_iteration | d_lifetime | ++--------+------------------+------------------------+------------------------| +| 21 | 25.9162 | 1 | 84000 | ++--------+------------------+------------------------+------------------------+ + +... + +Number of experiences recorded: 26644 +""" + +import ray + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core import COMPONENT_RL_MODULE +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import add_rllib_example_script_args + +parser = add_rllib_example_script_args( + default_timesteps=200000, + default_reward=350.0, +) +parser.set_defaults( + checkpoint_at_end=True, + max_concurrent_trials=1, +) +# Use `parser` to add your own custom command line options to this script +# and (if needed) use their values to set up `config` below. +args = parser.parse_args() + +config = ( + PPOConfig() + .env_runners( + num_env_runners=5, + ) + .environment("CartPole-v1") + .rl_module( + model_config=DefaultModelConfig( + fcnet_hiddens=[32], + fcnet_activation="linear", + vf_share_layers=True, + ), + ) + .training( + lr=0.0003, + num_epochs=6, + vf_loss_coeff=0.01, + ) + .evaluation( + evaluation_num_env_runners=1, + evaluation_interval=1, + evaluation_parallel_to_training=True, + evaluation_config=PPOConfig.overrides(explore=False), + ) +) + +stop = { + f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}": args.stop_timesteps, + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": ( + args.stop_reward + ), +} + + +if __name__ == "__main__": + from ray.rllib.utils.test_utils import run_rllib_example_script_experiment + + results = run_rllib_example_script_experiment(config, args, stop=stop) + + # Store the best checkpoint for recording. + best_checkpoint = results.get_best_result( + metric=f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}", + mode="max", + ).checkpoint.path + + # Configure the algorithm for offline recording. + config.offline_data( + output="local:///tmp/cartpole/", + # Store columnar (tabular) data. + output_write_episodes=False, + # Each file should hold 1,000 rows. + output_max_rows_per_file=1000, + output_write_remaining_data=True, + # LZ4-compress columns 'obs', 'new_obs', and 'actions' to + # save disk space and increase performance. Note, this means + # that you have to use `input_compress_columns` in the same + # way when using the data for training in `RLlib`. + output_compress_columns=[Columns.OBS, Columns.ACTIONS], + ) + # Change the evaluation settings to sample exactly 50 episodes + # per evaluation iteration and increase the number of evaluation + # env-runners to 5. + config.evaluation( + evaluation_num_env_runners=5, + evaluation_duration=50, + evaluation_duration_unit="episodes", + evaluation_interval=1, + evaluation_parallel_to_training=False, + evaluation_config=PPOConfig.overrides(explore=False), + ) + + # Build the algorithm for evaluation. + algo = config.build() + # Load the checkpoint stored above. + algo.restore_from_path( + best_checkpoint, + component=COMPONENT_RL_MODULE, + ) + + # Evaluate over 10 iterations and record the data. + for i in range(10): + print(f"Iteration: {i + 1}:\n") + res = algo.evaluate() + print(res) + + # Stop the algorithm. + algo.stop() + + # Check the number of rows in the dataset. + ds = ray.data.read_parquet("local:///tmp/cartpole") + print(f"Number of experiences recorded: {ds.count()}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6c2d3d36a3453dd55156127d08daadf845008d9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/image_offline_data.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/image_offline_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9f77db6fb39a0bd69828936a59122e43a83fde5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/image_offline_data.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/image_offline_prelearner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/image_offline_prelearner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0f00b6226d4ae6017ff01b0d40c05acde077fa9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/__pycache__/image_offline_prelearner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/image_offline_data.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/image_offline_data.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4ab5f5116fa3e625aa5440bb36ed28c4728e29 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/image_offline_data.py @@ -0,0 +1,73 @@ +import io +import logging +import numpy as np + +from PIL import Image +from typing import Any, Dict + +from ray import data +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.offline.offline_data import OfflineData +from ray.rllib.offline.offline_prelearner import OfflinePreLearner +from ray.rllib.utils.annotations import override + +logger = logging.getLogger(__name__) + + +class ImageOfflineData(OfflineData): + """This class overrides `OfflineData` to read in raw image data. + + The image data is from Ray Data`s S3 example bucket, namely + `ray-example-data/batoidea/JPEGImages/`. + To read in this data the raw bytes have to be decoded and then + converted to `numpy` arrays. Each image array has a dimension + (32, 32, 3). + + To just read in the raw image data and convert it to arrays it + suffices to override the `OfflineData.__init__` method only. + Note, that further transformations of the data - specifically + into `SingleAgentEpisode` data - will be performed in a custom + `OfflinePreLearner` defined in the `image_offline_prelearner` + file. You could hard-code the usage of this prelearner here, + but you will use the `prelearner_class` attribute in the + `AlgorithmConfig` instead. + """ + + @override(OfflineData) + def __init__(self, config: AlgorithmConfig): + + # Set class attributes. + self.config = config + self.is_multi_agent = self.config.is_multi_agent + self.materialize_mapped_data = False + self.path = self.config.input_ + + self.data_read_batch_size = self.config.input_read_batch_size + self.data_is_mapped = False + + # Define your function to map images to numpy arrays. + def map_to_numpy(row: Dict[str, Any]) -> Dict[str, Any]: + # Convert to byte stream. + bytes_stream = io.BytesIO(row["bytes"]) + # Convert to image. + image = Image.open(bytes_stream) + # Return an array of the image. + return {"array": np.array(image)} + + try: + # Load the dataset and transform to arrays on-the-fly. + self.data = data.read_binary_files(self.path).map(map_to_numpy) + except Exception as e: + logger.error(e) + + # Define further attributes needed in the `sample` method. + self.batch_iterator = None + self.map_batches_kwargs = self.config.map_batches_kwargs + self.iter_batches_kwargs = self.config.iter_batches_kwargs + # Use a custom OfflinePreLearner if needed. + self.prelearner_class = self.config.prelearner_class or OfflinePreLearner + + # For remote learner setups. + self.locality_hints = None + self.learner_handles = None + self.module_spec = None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/image_offline_prelearner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/image_offline_prelearner.py new file mode 100644 index 0000000000000000000000000000000000000000..001af304929ec2554fb6f3936ec788f42ab2f261 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/classes/image_offline_prelearner.py @@ -0,0 +1,101 @@ +import gymnasium as gym +import numpy as np +import random +import uuid + +from typing import Any, Dict, List, Optional, Tuple, Union + +from ray.actor import ActorHandle +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.offline.offline_prelearner import OfflinePreLearner, SCHEMA +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType, ModuleID + + +class ImageOfflinePreLearner(OfflinePreLearner): + """This class transforms image data to `MultiAgentBatch`es. + + While the `ImageOfflineData` class transforms raw image + bytes to `numpy` arrays, this class maps these data in + `SingleAgentEpisode` instances through the learner connector + pipeline and finally outputs a >`MultiAgentBatch` ready for + training in RLlib's `Learner`s. + + Note, the basic transformation from images to `SingleAgentEpisode` + instances creates synthetic data that does not rely on any MDP + and therefore no agent can learn from it. However, this example + should show how to transform data into this form through + overriding the `OfflinePreLearner`. + """ + + def __init__( + self, + config: "AlgorithmConfig", + learner: Union[Learner, List[ActorHandle]], + spaces: Optional[Tuple[gym.Space, gym.Space]] = None, + module_spec: Optional[MultiRLModuleSpec] = None, + module_state: Optional[Dict[ModuleID, Any]] = None, + **kwargs: Dict[str, Any], + ): + # Set up necessary class attributes. + self.config = config + self.action_space = spaces[1] + self.observation_space = spaces[0] + self.input_read_episodes = self.config.input_read_episodes + self.input_read_sample_batches = self.config.input_read_sample_batches + self._policies_to_train = "default_policy" + self._is_multi_agent = False + + # Build the `MultiRLModule` needed for the learner connector. + self._module = module_spec.build() + + # Build the learner connector pipeline. + self._learner_connector = self.config.build_learner_connector( + input_observation_space=self.observation_space, + input_action_space=self.action_space, + ) + + @override(OfflinePreLearner) + @staticmethod + def _map_to_episodes( + is_multi_agent: bool, + batch: Dict[str, Union[list, np.ndarray]], + schema: Dict[str, str] = SCHEMA, + to_numpy: bool = False, + input_compress_columns: Optional[List[str]] = None, + observation_space: gym.Space = None, + action_space: gym.Space = None, + **kwargs: Dict[str, Any], + ) -> Dict[str, List[EpisodeType]]: + + # Define a container for the episodes. + episodes = [] + + # Batches come in as numpy arrays. + for i, obs in enumerate(batch["array"]): + + # Construct your episode. + episode = SingleAgentEpisode( + id_=uuid.uuid4().hex, + observations=[obs, obs], + observation_space=observation_space, + actions=[action_space.sample()], + action_space=action_space, + rewards=[random.random()], + terminated=True, + truncated=False, + len_lookback_buffer=0, + t_started=0, + ) + + # Numpy'ize, if necessary. + if to_numpy: + episode.to_numpy() + + # Store the episode in the container. + episodes.append(episode) + + return {"episodes": episodes} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/custom_input_api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/custom_input_api.py new file mode 100644 index 0000000000000000000000000000000000000000..6c6cd515abae591a24ad81f101064589e9b39d01 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/custom_input_api.py @@ -0,0 +1,134 @@ +# @OldAPIStack + +"""Example of creating a custom input API + +Custom input apis are useful when your data source is in a custom format or +when it is necessary to use an external data loading mechanism. +In this example, we train an rl agent on user specified input data. +Instead of using the built in JsonReader, we will create our own custom input +api, and show how to pass config arguments to it. + +To train CQL on the pendulum environment: +$ python custom_input_api.py --input-files=../tests/data/pendulum/enormous.zip +""" + +import argparse +import os + +import ray +from ray import tune +from ray.rllib.offline import JsonReader, ShuffledInput, IOContext, InputReader +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, +) +from ray.tune.registry import get_trainable_cls, register_input +from ray.tune.result import TRAINING_ITERATION + +parser = argparse.ArgumentParser() +parser.add_argument( + "--run", type=str, default="CQL", help="The RLlib-registered algorithm to use." +) +parser.add_argument( + "--framework", + choices=["tf", "tf2", "torch"], + default="torch", + help="The DL framework specifier.", +) +parser.add_argument("--stop-iters", type=int, default=100) +parser.add_argument( + "--input-files", + type=str, + default=os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "../../tests/data/pendulum/small.json", + ), +) + + +class CustomJsonReader(JsonReader): + """ + Example custom InputReader implementation (extended from JsonReader). + + This gets wrapped in ShuffledInput to comply with offline rl algorithms. + """ + + def __init__(self, ioctx: IOContext): + """ + The constructor must take an IOContext to be used in the input config. + Args: + ioctx: use this to access the `input_config` arguments. + """ + super().__init__(ioctx.input_config["input_files"], ioctx) + + +def input_creator(ioctx: IOContext) -> InputReader: + """ + The input creator method can be used in the input registry or set as the + config["input"] parameter. + + Args: + ioctx: use this to access the `input_config` arguments. + + Returns: + instance of ShuffledInput to work with some offline rl algorithms + """ + return ShuffledInput(CustomJsonReader(ioctx)) + + +if __name__ == "__main__": + ray.init() + args = parser.parse_args() + + # make absolute path because relative path looks in result directory + args.input_files = os.path.abspath(args.input_files) + + # we register our custom input creator with this convenient function + register_input("custom_input", input_creator) + + # Config modified from rllib/tuned_examples/cql/pendulum-cql.yaml + default_config = get_trainable_cls(args.run).get_default_config() + config = ( + default_config.environment("Pendulum-v1", clip_actions=True) + .framework(args.framework) + .offline_data( + # We can either use the tune registry ... + input_="custom_input", + # ... full classpath + # input_: "ray.rllib.examples.offline_rl.custom_input_api.CustomJsonReader" + # ... or a direct function to connect our input api. + # input_: input_creator + input_config={"input_files": args.input_files}, # <- passed to IOContext + actions_in_input_normalized=True, + ) + .training(train_batch_size=2000) + .evaluation( + evaluation_interval=1, + evaluation_num_env_runners=2, + evaluation_duration=10, + evaluation_parallel_to_training=True, + evaluation_config=default_config.overrides( + input_="sampler", + explore=False, + ), + ) + .reporting(metrics_num_episodes_for_smoothing=5) + ) + + if args.run == "CQL": + config.training( + twin_q=True, + num_steps_sampled_before_learning_starts=0, + bc_iters=100, + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": -600, + } + + tuner = tune.Tuner( + args.run, param_space=config, run_config=tune.RunConfig(stop=stop, verbose=1) + ) + tuner.fit() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/offline_rl.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/offline_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..5679fc1ac63b3eb403864ef94d1245736623388b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/offline_rl.py @@ -0,0 +1,167 @@ +# @OldAPIStack + +"""Example on how to use CQL to learn from an offline JSON file. + +Important node: Make sure that your offline data file contains only +a single timestep per line to mimic the way SAC pulls samples from +the buffer. + +Generate the offline json file by running an SAC algo until it reaches expert +level on your command line. For example: +$ cd ray +$ rllib train -f rllib/tuned_examples/sac/pendulum-sac.yaml --no-ray-ui + +Also make sure that in the above SAC yaml file (pendulum-sac.yaml), +you specify an additional "output" key with any path on your local +file system. In that path, the offline json files will be written to. + +Use the generated file(s) as "input" in the CQL config below +(`config["input"] = [list of your json files]`), then run this script. +""" + +import argparse +import numpy as np + +from ray.rllib.policy.sample_batch import convert_ma_batch_to_sample_batch +from ray.rllib.algorithms import cql as cql +from ray.rllib.execution.rollout_ops import ( + synchronous_parallel_sample, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, +) + +torch, _ = try_import_torch() + +parser = argparse.ArgumentParser() +parser.add_argument( + "--as-test", + action="store_true", + help="Whether this script should be run as a test: --stop-reward must " + "be achieved within --stop-timesteps AND --stop-iters.", +) +parser.add_argument( + "--stop-iters", type=int, default=5, help="Number of iterations to train." +) +parser.add_argument( + "--stop-reward", type=float, default=50.0, help="Reward at which we stop training." +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # See rllib/tuned_examples/cql/pendulum-cql.yaml for comparison. + config = ( + cql.CQLConfig() + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .framework(framework="torch") + .env_runners(num_env_runners=0) + .training( + n_step=3, + bc_iters=0, + clip_actions=False, + tau=0.005, + target_entropy="auto", + q_model_config={ + "fcnet_hiddens": [256, 256], + "fcnet_activation": "relu", + }, + policy_model_config={ + "fcnet_hiddens": [256, 256], + "fcnet_activation": "relu", + }, + optimization_config={ + "actor_learning_rate": 3e-4, + "critic_learning_rate": 3e-4, + "entropy_learning_rate": 3e-4, + }, + train_batch_size=256, + target_network_update_freq=1, + num_steps_sampled_before_learning_starts=256, + ) + .reporting(min_train_timesteps_per_iteration=1000) + .debugging(log_level="INFO") + .environment("Pendulum-v1", normalize_actions=True) + .offline_data( + input_config={ + "paths": ["tests/data/pendulum/enormous.zip"], + "format": "json", + } + ) + .evaluation( + evaluation_num_env_runners=1, + evaluation_interval=1, + evaluation_duration=10, + evaluation_parallel_to_training=False, + evaluation_config=cql.CQLConfig.overrides(input_="sampler"), + ) + ) + # evaluation_parallel_to_training should be False b/c iterations are very long + # and this would cause evaluation to lag one iter behind training. + + # Check, whether we can learn from the given file in `num_iterations` + # iterations, up to a reward of `min_reward`. + num_iterations = 5 + min_reward = -300 + + cql_algorithm = cql.CQL(config=config) + learnt = False + for i in range(num_iterations): + print(f"Iter {i}") + eval_results = cql_algorithm.train().get(EVALUATION_RESULTS) + if eval_results: + print( + "... R={}".format(eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]) + ) + # Learn until some reward is reached on an actual live env. + if eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= min_reward: + # Test passed gracefully. + if args.as_test: + print("Test passed after {} iterations.".format(i)) + quit(0) + learnt = True + break + + # Get policy and model. + cql_policy = cql_algorithm.get_policy() + cql_model = cql_policy.model + + # If you would like to query CQL's learnt Q-function for arbitrary + # (cont.) actions, do the following: + obs_batch = torch.from_numpy(np.random.random(size=(5, 3))) + action_batch = torch.from_numpy(np.random.random(size=(5, 1))) + q_values = cql_model.get_q_values(obs_batch, action_batch)[0] + # If you are using the "twin_q", there'll be 2 Q-networks and + # we usually consider the min of the 2 outputs, like so: + twin_q_values = cql_model.get_twin_q_values(obs_batch, action_batch)[0] + final_q_values = torch.min(q_values, twin_q_values)[0] + print(f"final_q_values={final_q_values.detach().numpy()}") + + # Example on how to do evaluation on the trained Algorithm. + # using the data from our buffer. + # Get a sample (MultiAgentBatch). + + batch = synchronous_parallel_sample(worker_set=cql_algorithm.env_runner_group) + batch = convert_ma_batch_to_sample_batch(batch) + obs = torch.from_numpy(batch["obs"]) + # Pass the observations through our model to get the + # features, which then to pass through the Q-head. + model_out, _ = cql_model({"obs": obs}) + # The estimated Q-values from the (historic) actions in the batch. + q_values_old = cql_model.get_q_values( + model_out, torch.from_numpy(batch["actions"]) + )[0] + # The estimated Q-values for the new actions computed by our policy. + actions_new = cql_policy.compute_actions_from_input_dict({"obs": obs})[0] + q_values_new = cql_model.get_q_values(model_out, torch.from_numpy(actions_new))[0] + print(f"Q-val batch={q_values_old.detach().numpy()}") + print(f"Q-val policy={q_values_new.detach().numpy()}") + + cql_algorithm.stop() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/offline_rl_with_image_data.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/offline_rl_with_image_data.py new file mode 100644 index 0000000000000000000000000000000000000000..1a88aeeb323869353cc811f40e161f516aa49d44 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/offline_rl_with_image_data.py @@ -0,0 +1,112 @@ +"""Example showing how to customize an offline data pipeline. + +This example: + - demonstrates how you can customized your offline data pipeline. + - shows how you can override the `OfflineData` to read raw image + data and transform it into `numpy ` arrays. + - explains how you can override the `OfflinePreLearner` to + transform data further into `SingleAgentEpisode` instances that + can be processes by the learner connector pipeline. + +How to run this script +---------------------- +`python [script file name].py --checkpoint-at-end` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +Results to expect +----------------- +2024-12-03 19:59:23,043 INFO streaming_executor.py:109 -- Execution plan +of Dataset: InputDataBuffer[Input] -> TaskPoolMapOperator[ReadBinary] -> +TaskPoolMapOperator[Map(map_to_numpy)] -> LimitOperator[limit=128] +✔️ Dataset execution finished in 10.01 seconds: 100%|███████████████████ +███████████████████████████████████████████████████████████████████████| +3.00/3.00 [00:10<00:00, 3.34s/ row] +- ReadBinary->SplitBlocks(11): Tasks: 0; Queued blocks: 0; Resources: 0.0 +CPU, 0.0B object store: 100%|█████████████████████████████████████████| +3.00/3.00 [00:10<00:00, 3.34s/ row] +- Map(map_to_numpy): Tasks: 0; Queued blocks: 0; Resources: 0.0 CPU, +0.0B object store: 100%|███████████████████████████████████████████████████| +3.00/3.00 [00:10<00:00, 3.34s/ row] +- limit=128: Tasks: 0; Queued blocks: 0; Resources: 0.0 CPU, 3.0KB object +store: 100%|██████████████████████████████████████████████████████████| +3.00/3.00 [00:10<00:00, 3.34s/ row] +Batch: {'batch': [MultiAgentBatch({}, env_steps=3)]} +""" + +import gymnasium as gym +import numpy as np + +from ray.rllib.algorithms.bc import BCConfig +from ray.rllib.algorithms.bc.bc_catalog import BCCatalog +from ray.rllib.algorithms.bc.torch.bc_torch_rl_module import BCTorchRLModule +from ray.rllib.core.rl_module.rl_module import RLModuleSpec, DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.examples.offline_rl.classes.image_offline_data import ImageOfflineData +from ray.rllib.examples.offline_rl.classes.image_offline_prelearner import ( + ImageOfflinePreLearner, +) + +# Create an Algorithm configuration. +# TODO: Make this an actually running/learning example with RLunplugged +# data from S3 and add this to the CI. +config = ( + BCConfig() + .environment( + action_space=gym.spaces.Discrete(2), + observation_space=gym.spaces.Box(0, 255, (32, 32, 3), np.float32), + ) + .offline_data( + input_=["s3://anonymous@ray-example-data/batoidea/JPEGImages/"], + prelearner_class=ImageOfflinePreLearner, + ) +) + +# Specify an `RLModule` and wrap it with a `MultiRLModuleSpec`. Note, +# on `Learner`` side any `RLModule` is an `MultiRLModule`. +module_spec = MultiRLModuleSpec( + rl_module_specs={ + "default_policy": RLModuleSpec( + model_config=DefaultModelConfig( + conv_filters=[[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]], + conv_activation="relu", + ), + inference_only=False, + module_class=BCTorchRLModule, + catalog_class=BCCatalog, + action_space=gym.spaces.Discrete(2), + observation_space=gym.spaces.Box(0, 255, (32, 32, 3), np.float32), + ), + }, +) + +# Construct your `OfflineData` class instance. +offline_data = ImageOfflineData(config) + +# Check, how the data is transformed. Note, the +# example dataset has only 3 such images. +batch = offline_data.data.take_batch(3) + +# Construct your `OfflinePreLearner`. +offline_prelearner = ImageOfflinePreLearner( + config=config, + learner=None, + spaces=( + config.observation_space, + config.action_space, + ), + module_spec=module_spec, +) + +# Transform the raw data to `MultiAgentBatch` data. +batch = offline_prelearner(batch) + +# Show the transformed batch. +print(f"Batch: {batch}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/pretrain_bc_single_agent_evaluate_as_multi_agent.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/pretrain_bc_single_agent_evaluate_as_multi_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..c23a90110461f647116b164094e60fad1cead99a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/pretrain_bc_single_agent_evaluate_as_multi_agent.py @@ -0,0 +1,177 @@ +# @HybridAPIStack + +"""Example showing how to train a (SA) BC RLModule while evaluating in a MA setup. + +Here, SA=single-agent and MA=multi-agent. + +Note that the BC Algorithm - by default - runs on the hybrid API stack, using RLModules, +but not `ConnectorV2` and `SingleAgentEpisode` yet. + +This example: + - demonstrates how you can train a single-agent BC Policy (RLModule) from a JSON + file, which contains SampleBatch (expert or non-expert) data. + - shows how you can run evaluation in a multi-agent setup (for example vs one + or more heuristic policies), while training the BC Policy. + + +How to run this script +---------------------- +`python [script file name].py --checkpoint-at-end` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that the episode returns of the "main" policy on +the evaluation track keep increasing as BC manages to more and more clone the behavior +found in our (expert) JSON file. + +After 50-100 iterations, you should see the episode reward reach 450.0. +Note that the opponent (random) policy does not learn as it's a) not a trainable +RLModule and b) not being trained via the BCConfig. It's only used for evaluation +purposes here. + ++---------------------+------------+-----------------+--------+--------+ +| Trial name | status | loc | iter | ts | +|---------------------+------------+-----------------+--------+--------+ +| BC_None_ee65e_00000 | TERMINATED | 127.0.0.1:35031 | 93 | 203754 | ++---------------------+------------+-----------------+--------+--------+ ++----------------------+------------------------+ +| eps. return (main) | eps. return (random) | +|----------------------+------------------------| +| 452.4 | 28.3 | ++----------------------+------------------------+ +""" +import os +from pathlib import Path + +import gymnasium as gym + +from ray import tune +from ray.rllib.algorithms.bc import BCConfig +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.examples._old_api_stack.policy.random_policy import RandomPolicy +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EVALUATION_RESULTS, + NUM_ENV_STEPS_TRAINED, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.result import TIME_TOTAL_S, TRAINING_ITERATION +from ray.tune.registry import register_env + +parser = add_rllib_example_script_args( + default_reward=450.0, + default_timesteps=300000, +) +parser.set_defaults( + num_agents=2, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + register_env("multi_cart", lambda cfg: MultiAgentCartPole(cfg)) + dummy_env = gym.make("CartPole-v1") + + rllib_dir = Path(__file__).parent.parent.parent + print(f"rllib dir={rllib_dir}") + offline_file = os.path.join(rllib_dir, "tests/data/cartpole/large.json") + + base_config = ( + BCConfig() + # For offline RL, we do not specify an env here (b/c we don't want any env + # instances created on the EnvRunners). Instead, we'll provide observation- + # and action-spaces here for the RLModule to know its input- and output types. + .environment( + observation_space=dummy_env.observation_space, + action_space=dummy_env.action_space, + ) + .offline_data( + input_=offline_file, + # The number of iterations to be run per learner when in multi-learner + # mode in a single RLlib training iteration. Leave this to `None` to + # run an entire epoch on the dataset during a single RLlib training + # iteration. For single-learner mode, 1 is the only option. + dataset_num_iters_per_learner=1 if not args.num_learners else None, + ) + .multi_agent( + policies={"main"}, + policy_mapping_fn=lambda *a, **kw: "main", + ) + .evaluation( + evaluation_interval=1, + evaluation_num_env_runners=0, + evaluation_config=BCConfig.overrides( + # Evaluate on an actual env -> switch input back to "sampler". + input_="sampler", + # Do not explore during evaluation, but act greedily. + explore=False, + # Use a multi-agent setup for evaluation. + env="multi_cart", + env_config={"num_agents": args.num_agents}, + policies={ + "main": PolicySpec(), + "random": PolicySpec(policy_class=RandomPolicy), + }, + # Only control agent 0 with the main (trained) policy. + policy_mapping_fn=( + lambda aid, *a, **kw: "main" if aid == 0 else "random" + ), + # Note that we do NOT have to specify the `policies_to_train` here, + # b/c we are inside the evaluation config (no policy is trained during + # evaluation). The fact that the BCConfig above is "only" setup + # as single-agent makes it automatically only train the policy found in + # the BCConfig's `policies` field (which is "main"). + # policies_to_train=["main"], + ), + ) + ) + + policy_eval_returns = ( + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/policy_reward_mean/" + ) + + stop = { + # Check for the "main" policy's episode return, not the combined one. + # The combined one is the sum of the "main" policy + the "random" one. + policy_eval_returns + "main": args.stop_reward, + NUM_ENV_STEPS_TRAINED: args.stop_timesteps, + TRAINING_ITERATION: args.stop_iters, + } + + run_rllib_example_script_experiment( + base_config, + args, + stop=stop, + success_metric={policy_eval_returns + "main": args.stop_reward}, + # We use a special progress reporter here to show the evaluation results (of the + # "main" policy). + # In the following dict, the keys are the (possibly nested) keys that can be + # found in RLlib's (BC's) result dict, produced at every training iteration, and + # the values are the column names you would like to see in your console reports. + # Note that for nested result dict keys, you need to use slashes "/" to define + # the exact path. + progress_reporter=tune.CLIReporter( + metric_columns={ + TRAINING_ITERATION: "iter", + TIME_TOTAL_S: "total time (s)", + NUM_ENV_STEPS_TRAINED: "ts", + policy_eval_returns + "main": "eps. return (main)", + policy_eval_returns + "random": "eps. return (random)", + } + ), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/saving_experiences.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/saving_experiences.py new file mode 100644 index 0000000000000000000000000000000000000000..3018d93f9d2ab7c7661ed181d5b6008670ac61e6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/saving_experiences.py @@ -0,0 +1,60 @@ +# @OldAPIStack + +"""Simple example of writing experiences to a file using JsonWriter.""" + +# __sphinx_doc_begin__ +import gymnasium as gym +import numpy as np +import os + +from ray._common.utils import get_user_temp_dir + +from ray.rllib.models.preprocessors import get_preprocessor +from ray.rllib.evaluation.sample_batch_builder import SampleBatchBuilder +from ray.rllib.offline.json_writer import JsonWriter + +if __name__ == "__main__": + batch_builder = SampleBatchBuilder() # or MultiAgentSampleBatchBuilder + writer = JsonWriter(os.path.join(get_user_temp_dir(), "demo-out")) + + # You normally wouldn't want to manually create sample batches if a + # simulator is available, but let's do it anyways for example purposes: + env = gym.make("CartPole-v1") + + # RLlib uses preprocessors to implement transforms such as one-hot encoding + # and flattening of tuple and dict observations. For CartPole a no-op + # preprocessor is used, but this may be relevant for more complex envs. + prep = get_preprocessor(env.observation_space)(env.observation_space) + print("The preprocessor is", prep) + + for eps_id in range(100): + obs, info = env.reset() + prev_action = np.zeros_like(env.action_space.sample()) + prev_reward = 0 + terminated = truncated = False + t = 0 + while not terminated and not truncated: + action = env.action_space.sample() + new_obs, rew, terminated, truncated, info = env.step(action) + batch_builder.add_values( + t=t, + eps_id=eps_id, + agent_index=0, + obs=prep.transform(obs), + actions=action, + action_prob=1.0, # put the true action probability here + action_logp=0.0, + rewards=rew, + prev_actions=prev_action, + prev_rewards=prev_reward, + terminateds=terminated, + truncateds=truncated, + infos=info, + new_obs=prep.transform(new_obs), + ) + obs = new_obs + prev_action = action + prev_reward = rew + t += 1 + writer.write(batch_builder.build_and_reset()) +# __sphinx_doc_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/train_w_bc_finetune_w_ppo.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/train_w_bc_finetune_w_ppo.py new file mode 100644 index 0000000000000000000000000000000000000000..97dbf0c9f598ae3a09223e17e8a62d2fdbae4801 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/offline_rl/train_w_bc_finetune_w_ppo.py @@ -0,0 +1,300 @@ +"""Example of training a custom RLModule with BC first, then finetuning it with PPO. + +This example: + - demonstrates how to write a very simple custom BC RLModule. + - run a quick BC training experiment with the custom module and learn CartPole + until some episode return A, while checkpointing each iteration. + - shows how subclass the custom BC RLModule, add the ValueFunctionAPI to the + new class, and add a value-function branch and an implementation of + `compute_values` to the original model to make it work with a value-based algo + like PPO. + - shows how to plug this new PPO-capable RLModule (including its checkpointed state + from the BC run) into your algorithm's config. + - confirms that even after 1-2 training iterations with PPO, no catastrophic + forgetting occurs (due to the additional value function branch and the switched + optimizer). + - uses Tune and RLlib to continue training the model until a higher return of B + is reached. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can first see BC's performance until return A is reached: ++----------------------------+------------+----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|----------------------------+------------+----------------+--------+ +| BC_CartPole-v1_95ba0_00000 | TERMINATED | 127.0.0.1:1515 | 51 | ++----------------------------+------------+----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_env_steps_traine | +| | | d_lifetime | +|------------------+------------------------|------------------------| +| 11.4828 | 250.5 | 42394 | ++------------------+------------------------+------------------------+ + +The script should confirm that no catastrophic forgetting has taken place: + +PPO return after initialization: 292.3 +PPO return after 2x training: 276.85 + +Then, after PPO training, you should see something like this (higher return): ++-----------------------------+------------+----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+----------------+--------+ +| PPO_CartPole-v1_e07ac_00000 | TERMINATED | 127.0.0.1:6032 | 37 | ++-----------------------------+------------+----------------+--------+ + ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_episodes_lifetime | +| | | | ++------------------+------------------------+------------------------+ +| 32.7647 | 450.76 | 406 | ++------------------+------------------------+------------------------+ +""" +from pathlib import Path + +from torch import nn + +from ray.rllib.algorithms.bc import BCConfig +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core import ( + COMPONENT_LEARNER_GROUP, + COMPONENT_LEARNER, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.base import ENCODER_OUT +from ray.rllib.core.models.configs import MLPEncoderConfig, MLPHeadConfig +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.core.rl_module.rl_module import RLModule, RLModuleSpec +from ray.rllib.core.rl_module.torch import TorchRLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +parser = add_rllib_example_script_args() +parser.set_defaults( + env="CartPole-v1", + checkpoint_freq=1, +) + + +class MyBCModel(TorchRLModule): + """A very simple BC-usable model that only computes action logits.""" + + @override(TorchRLModule) + def setup(self): + # Create an encoder trunk. + # Observations are directly passed through it and feature vectors are output. + self._encoder = MLPEncoderConfig( + input_dims=[4], # CartPole + hidden_layer_dims=[256, 256], + hidden_layer_activation="relu", + output_layer_dim=None, + ).build(framework="torch") + + # The policy head sitting on top of the encoder. Feature vectors come in as + # input and action logits are output. + self._pi = MLPHeadConfig( + input_dims=[256], # from encoder + hidden_layer_dims=[256], # pi head + hidden_layer_activation="relu", + output_layer_dim=2, # CartPole + output_layer_activation="linear", + ).build(framework="torch") + + @override(TorchRLModule) + def _forward_inference(self, batch, **kwargs): + return {Columns.ACTION_DIST_INPUTS: self._pi(self._encoder(batch)[ENCODER_OUT])} + + @override(RLModule) + def _forward_exploration(self, batch, **kwargs): + return self._forward_inference(batch) + + @override(RLModule) + def _forward_train(self, batch, **kwargs): + return self._forward_inference(batch) + + +class MyPPOModel(MyBCModel, ValueFunctionAPI): + """Subclass of our simple BC model, but implementing the ValueFunctionAPI. + + Implementing the `compute_values` method makes this RLModule usable by algos + like PPO. + """ + + @override(MyBCModel) + def setup(self): + # Call super setup to create encoder trunk and policy head. + super().setup() + # Create the new value function head and zero-initialize it to not cause too + # much disruption. + self._vf = MLPHeadConfig( + input_dims=[256], # from encoder + hidden_layer_dims=[256], # pi head + hidden_layer_activation="relu", + hidden_layer_weights_initializer=nn.init.zeros_, + hidden_layer_bias_initializer=nn.init.zeros_, + output_layer_dim=1, # 1=value node + output_layer_activation="linear", + output_layer_weights_initializer=nn.init.zeros_, + output_layer_bias_initializer=nn.init.zeros_, + ).build(framework="torch") + + @override(MyBCModel) + def _forward_train(self, batch, **kwargs): + features = self._encoder(batch)[ENCODER_OUT] + logits = self._pi(features) + vf_out = self._vf(features).squeeze(-1) + return { + Columns.ACTION_DIST_INPUTS: logits, + Columns.VF_PREDS: vf_out, + } + + @override(ValueFunctionAPI) + def compute_values(self, batch, embeddings=None): + # Compute embeddings ... + if embeddings is None: + embeddings = self._encoder(batch)[ENCODER_OUT] + # then values using our value head. + return self._vf(embeddings).squeeze(-1) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.env == "CartPole-v1", "This example works only with --env=CartPole-v1!" + + # Define the data paths for our CartPole large dataset. + base_path = Path(__file__).parents[2] + assert base_path.is_dir(), base_path + data_path = base_path / "tests/data/cartpole/cartpole-v1_large" + assert data_path.is_dir(), data_path + print(f"data_path={data_path}") + + # Define the BC config. + base_config = ( + BCConfig() + # Note, the `input_` argument is the major argument for the + # new offline API. Via the `input_read_method_kwargs` the + # arguments for the `ray.data.Dataset` read method can be + # configured. The read method needs at least as many blocks + # as remote learners. + .offline_data( + input_=[data_path.as_posix()], + # Define the number of reading blocks, these should be larger than 1 + # and aligned with the data size. + input_read_method_kwargs={ + "override_num_blocks": max((args.num_learners or 1) * 2, 2) + }, + # Concurrency defines the number of processes that run the + # `map_batches` transformations. This should be aligned with the + # 'prefetch_batches' argument in 'iter_batches_kwargs'. + map_batches_kwargs={"concurrency": 2, "num_cpus": 2}, + # This data set is small so do not prefetch too many batches and use no + # local shuffle. + iter_batches_kwargs={ + "prefetch_batches": 1, + "local_shuffle_buffer_size": None, + }, + # The number of iterations to be run per learner when in multi-learner + # mode in a single RLlib training iteration. Leave this to `None` to + # run an entire epoch on the dataset during a single RLlib training + # iteration. For single-learner mode, 1 is the only option. + dataset_num_iters_per_learner=1 if not args.num_learners else None, + ).training( + train_batch_size_per_learner=1024, + # To increase learning speed with multiple learners, + # increase the learning rate correspondingly. + lr=0.0008 * (args.num_learners or 1) ** 0.5, + ) + # Plug in our simple custom BC model from above. + .rl_module(rl_module_spec=RLModuleSpec(module_class=MyBCModel)) + # Run evaluation to observe how good our BC policy already is. + .evaluation( + evaluation_interval=3, + evaluation_num_env_runners=1, + evaluation_duration=5, + evaluation_parallel_to_training=True, + ) + ) + + # Run the BC experiment and stop at R=250.0 + metric_key = f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + stop = {metric_key: 250.0} + results = run_rllib_example_script_experiment(base_config, args, stop=stop) + + # Extract the RLModule checkpoint. + best_result = results.get_best_result(metric_key) + rl_module_checkpoint = ( + Path(best_result.checkpoint.path) + / COMPONENT_LEARNER_GROUP + / COMPONENT_LEARNER + / COMPONENT_RL_MODULE + / "default_policy" + ) + + # Create a new PPO config. + base_config = ( + PPOConfig() + .environment(args.env) + .env_runners(create_env_on_local_worker=True) + .training( + # Keep lr relatively low at the beginning to avoid catastrophic forgetting. + lr=0.00002, + num_epochs=6, + vf_loss_coeff=0.01, + ) + # Plug in our simple custom PPO model from above. Note that the checkpoint + # for the BC model is loadable into the PPO model, b/c the BC model is a subset + # of the PPO model (all weights/biases in the BC model are also found in the PPO + # model; the PPO model only has an additional value function branch). + .rl_module( + rl_module_spec=RLModuleSpec( + module_class=MyPPOModel, + load_state_path=rl_module_checkpoint, + ) + ) + ) + + # Quick test, whether initial performance in the loaded (now PPO) model is ok. + ppo = base_config.build() + eval_results = ppo.evaluate() + R = eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + assert R >= 200.0, f"Initial PPO performance bad! R={R} (expected 200.0+)." + print(f"PPO return after initialization: {R}") + # Check, whether training 2 times causes catastrophic forgetting. + ppo.train() + train_results = ppo.train() + R = train_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + assert R >= 250.0, f"PPO performance (training) bad! R={R} (expected 250.0+)." + print(f"PPO return after 2x training: {R}") + + # Perform actual PPO training run (this time until 450.0 return). + stop = { + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": 450.0, + } + run_rllib_example_script_experiment(base_config, args, stop=stop) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8b5f3d01c34d3293c4aa7000b14b4a55276b4a2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/__pycache__/ray_serve_with_rllib.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/__pycache__/ray_serve_with_rllib.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c5558131ae17d74cfb85ee45c163e68d93e2170 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/__pycache__/ray_serve_with_rllib.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8911b90ee5f6cccfc49c089112652abb951421fd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/__pycache__/cartpole_deployment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/__pycache__/cartpole_deployment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03957003e381b761a3e40d67a717098bce0031b6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/__pycache__/cartpole_deployment.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/cartpole_deployment.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/cartpole_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..41686306c09577bb1f41f1205e0f96cde6f8100c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/classes/cartpole_deployment.py @@ -0,0 +1,50 @@ +import json +from typing import Dict + +import numpy as np +from starlette.requests import Request +import torch + +from ray import serve +from ray.rllib.core import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.serve.schema import LoggingConfig + + +@serve.deployment(logging_config=LoggingConfig(log_level="WARN")) +class ServeRLlibRLModule: + """Callable class used by Ray Serve to handle async requests. + + All the necessary serving logic is implemented in here: + - Creation and restoring of the (already trained) RLlib Algorithm. + - Calls to algo.compute_action upon receiving an action request + (with a current observation). + """ + + def __init__(self, rl_module_checkpoint): + self.rl_module = RLModule.from_checkpoint(rl_module_checkpoint) + + async def __call__(self, starlette_request: Request) -> Dict: + request = await starlette_request.body() + request = request.decode("utf-8") + request = json.loads(request) + obs = request["observation"] + + # Compute and return the action for the given observation (create a batch + # with B=1 and convert to torch). + output = self.rl_module.forward_inference( + batch={"obs": torch.from_numpy(np.array([obs], np.float32))} + ) + # Extract action logits and unbatch. + logits = output[Columns.ACTION_DIST_INPUTS][0] + # Act greedily (argmax). + action = int(np.argmax(logits)) + + return {"action": action} + + +# Defining the builder function. This is so we can start our deployment via: +# `serve run [this py module]:rl_module checkpoint=[some algo checkpoint path]` +def rl_module(args: Dict[str, str]): + serve.start(http_options={"host": "0.0.0.0", "port": args.get("port", 12345)}) + return ServeRLlibRLModule.bind(args["rl_module_checkpoint"]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/ray_serve_with_rllib.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/ray_serve_with_rllib.py new file mode 100644 index 0000000000000000000000000000000000000000..2d46105a93d8710c046430bf5364609368171d62 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_serve/ray_serve_with_rllib.py @@ -0,0 +1,190 @@ +"""Example on how to run RLlib in combination with Ray Serve. + +This example trains an agent with PPO on the CartPole environment, then creates +an RLModule checkpoint and returns its location. After that, it sends the checkpoint +to the Serve deployment for serving the trained RLModule (policy). + +This example: + - shows how to set up a Ray Serve deployment for serving an already trained + RLModule (policy network). + - shows how to request new actions from the Ray Serve deployment while actually + running through episodes in an environment (on which the RLModule that's served + was trained). + + +How to run this script +---------------------- +`python [script file name].py --stop-reward=200.0` + +Use the `--stop-iters`, `--stop-reward`, and/or `--stop-timesteps` options to +determine how long to train the policy for. Use the `--serve-episodes` option to +set the number of episodes to serve (after training) and the `--no-render` option +to NOT render the environment during the serving phase. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- + +You should see something similar to the following on the command line when using the +options: `--stop-reward=250.0`, `--num-episodes-served=2`, and `--port=12345`: + +[First, the RLModule is trained through PPO] + ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_84778_00000 | TERMINATED | 127.0.0.1:40411 | 1 | ++-----------------------------+------------+-----------------+--------+ ++------------------+---------------------+------------------------+ +| total time (s) | episode_return_mean | num_env_steps_sample | +| | | d_lifetime | +|------------------+---------------------|------------------------| +| 2.87052 | 253.2 | 12000 | ++------------------+---------------------+------------------------+ + +[The RLModule is deployed through Ray Serve on port 12345] + +Started Ray Serve with PID: 40458 + +[A few episodes are played through using the policy service (w/ greedy, non-exploratory +actions)] + +Episode R=500.0 +Episode R=500.0 +""" + +import atexit +import os + +import requests +import subprocess +import time + +import gymnasium as gym +from pathlib import Path + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core import ( + COMPONENT_LEARNER_GROUP, + COMPONENT_LEARNER, + COMPONENT_RL_MODULE, + DEFAULT_MODULE_ID, +) +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray._common.network_utils import build_address + +parser = add_rllib_example_script_args() +parser.set_defaults( + checkpoint_freq=1, + checkpoint_at_and=True, +) +parser.add_argument("--num-episodes-served", type=int, default=2) +parser.add_argument("--no-render", action="store_true") +parser.add_argument("--port", type=int, default=12345) + + +def kill_proc(proc): + try: + proc.terminate() # Send SIGTERM + proc.wait(timeout=5) # Wait for process to terminate + except subprocess.TimeoutExpired: + proc.kill() # Send SIGKILL + proc.wait() # Ensure process is dead + + +if __name__ == "__main__": + args = parser.parse_args() + + # Config for the served RLlib RLModule/Algorithm. + base_config = PPOConfig().environment("CartPole-v1") + + results = run_rllib_example_script_experiment(base_config, args) + algo_checkpoint = results.get_best_result( + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + ).checkpoint.path + # We only need the RLModule component from the algorithm checkpoint. It's located + # under "[algo checkpoint dir]/learner_group/learner/rl_module/[default policy ID] + rl_module_checkpoint = ( + Path(algo_checkpoint) + / COMPONENT_LEARNER_GROUP + / COMPONENT_LEARNER + / COMPONENT_RL_MODULE + / DEFAULT_MODULE_ID + ) + + path_of_this_file = Path(__file__).parent + os.chdir(path_of_this_file) + # Start the serve app with the trained checkpoint. + serve_proc = subprocess.Popen( + [ + "serve", + "run", + "classes.cartpole_deployment:rl_module", + f"rl_module_checkpoint={rl_module_checkpoint}", + f"port={args.port}", + "route_prefix=/rllib-rlmodule", + ] + ) + # Register our `kill_proc` function to be called on exit to stop Ray Serve again. + atexit.register(kill_proc, serve_proc) + # Wait a while to make sure the app is ready to serve. + time.sleep(20) + print(f"Started Ray Serve with PID: {serve_proc.pid}") + + try: + # Create the environment that we would like to receive + # served actions for. + env = gym.make("CartPole-v1", render_mode="human") + obs, _ = env.reset() + + num_episodes = 0 + episode_return = 0.0 + + while num_episodes < args.num_episodes_served: + # Render env if necessary. + if not args.no_render: + env.render() + + # print(f"-> Requesting action for obs={obs} ...", end="") + # Send a request to serve. + resp = requests.get( + f"http://{build_address('localhost', args.port)}/rllib-rlmodule", + json={"observation": obs.tolist()}, + ) + response = resp.json() + # print(f" received: action={response['action']}") + + # Apply the action in the env. + action = response["action"] + obs, reward, terminated, truncated, _ = env.step(action) + episode_return += reward + + # If episode done -> reset to get initial observation of new episode. + if terminated or truncated: + print(f"Episode R={episode_return}") + obs, _ = env.reset() + num_episodes += 1 + episode_return = 0.0 + + finally: + # Make sure to kill the process on script termination + kill_proc(serve_proc) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..305b80fba1f8627f9cb26cef93ca69ac53588ec8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_experiment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_experiment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b9d0a2a0369dd37cf321e72e244fbc0293f0122 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_experiment.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_logger.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c99082d9b71b1167eb39673534a49b7d3fda1249 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_logger.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_progress_reporter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_progress_reporter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff2bc912544a33fc32a863c773bc412441b4c9d9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/__pycache__/custom_progress_reporter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_experiment.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..54628f3103aa121881b83c3f275e68d372965b2a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_experiment.py @@ -0,0 +1,183 @@ +"""Example of a custom Ray Tune experiment wrapping an RLlib Algorithm. + +You should only use such a customized workflow if the following conditions apply: +- You know exactly what you are doing :) +- Configuring an existing RLlib Algorithm (e.g. PPO) via its AlgorithmConfig +is not sufficient and doesn't allow you to shape the Algorithm into behaving the way +you'd like. Note that for complex, custom evaluation procedures there are many +AlgorithmConfig options one can use (for more details, see: +https://github.com/ray-project/ray/blob/master/rllib/examples/evaluation/custom_evaluation.py). # noqa +- Subclassing an RLlib Algorithm class and overriding the new class' `training_step` +method is not sufficient and doesn't allow you to define the algorithm's execution +logic the way you'd like. See an example here on how to customize the algorithm's +`training_step()` method: +https://github.com/ray-project/ray/blob/master/rllib/examples/algorithm/custom_training_step_on_and_off_policy_combined.py # noqa + + +How to run this script +---------------------- +`python [script file name].py` + + +Results to expect +----------------- +You should see the following output (at the end of the experiment) in your console: + +╭─────────────────────────────────────────────────────────────────────────────────────── +│ Trial name status iter total time (s) ts +├─────────────────────────────────────────────────────────────────────────────────────── +│ my_experiment_CartPole-v1_77083_00000 TERMINATED 10 36.7799 60000 +╰─────────────────────────────────────────────────────────────────────────────────────── +╭───────────────────────────────────────────────────────╮ +│ reward episode_len_mean episodes_this_iter │ +├───────────────────────────────────────────────────────┤ +│ 254.821 254.821 12 │ +╰───────────────────────────────────────────────────────╯ +evaluation episode returns=[500.0, 500.0, 500.0] + +Note that evaluation results (on the CartPole-v1 env) should be close to perfect +(episode return of ~500.0) as we are acting greedily inside the evaluation procedure. +""" +from typing import Dict + +import numpy as np +from ray import tune +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import NUM_ENV_STEPS_SAMPLED_LIFETIME + +torch, _ = try_import_torch() + + +def my_experiment(config: Dict): + + # Extract the number of iterations to run from the config. + train_iterations = config.pop("train-iterations", 2) + eval_episodes_to_do = config.pop("eval-episodes", 1) + + config = ( + PPOConfig() + .update_from_dict(config) + .api_stack(enable_rl_module_and_learner=True) + .environment("CartPole-v1") + ) + + # Train for n iterations with high LR. + config.training(lr=0.001) + algo_high_lr = config.build() + for _ in range(train_iterations): + train_results = algo_high_lr.train() + # Add the phase to the result dict. + train_results["phase"] = 1 + tune.report(train_results) + phase_high_lr_time = train_results[NUM_ENV_STEPS_SAMPLED_LIFETIME] + checkpoint_training_high_lr = algo_high_lr.save() + algo_high_lr.stop() + + # Train for n iterations with low LR. + config.training(lr=0.00001) + algo_low_lr = config.build() + # Load state from the high-lr algo into this one. + algo_low_lr.restore(checkpoint_training_high_lr) + for _ in range(train_iterations): + train_results = algo_low_lr.train() + # Add the phase to the result dict. + train_results["phase"] = 2 + # keep time moving forward + train_results[NUM_ENV_STEPS_SAMPLED_LIFETIME] += phase_high_lr_time + tune.report(train_results) + + checkpoint_training_low_lr = algo_low_lr.save() + algo_low_lr.stop() + + # After training, run a manual evaluation procedure. + + # Set the number of EnvRunners for collecting training data to 0 (local + # worker only). + config.env_runners(num_env_runners=0) + + eval_algo = config.build() + # Load state from the low-lr algo into this one. + eval_algo.restore(checkpoint_training_low_lr) + # The algo's local worker (SingleAgentEnvRunner) that holds a + # gym.vector.Env object and an RLModule for computing actions. + local_env_runner = eval_algo.env_runner + # Extract the gymnasium env object from the created algo (its local + # SingleAgentEnvRunner worker). Note that the env in this single-agent + # case is a gymnasium vector env and that we get its first sub-env here. + env = local_env_runner.env.unwrapped.envs[0] + + # The local worker (SingleAgentEnvRunner) + rl_module = local_env_runner.module + + # Run a very simple env loop and add up rewards over a single episode. + obs, infos = env.reset() + episode_returns = [] + episode_lengths = [] + sum_rewards = length = 0 + num_episodes = 0 + while num_episodes < eval_episodes_to_do: + # Call the RLModule's `forward_inference()` method to compute an + # action. + rl_module_out = rl_module.forward_inference( + { + "obs": torch.from_numpy(np.expand_dims(obs, 0)), # <- add B=1 + } + ) + action_logits = rl_module_out["action_dist_inputs"][0] # <- remove B=1 + action = np.argmax(action_logits.detach().cpu().numpy()) # act greedily + + # Step the env. + obs, reward, terminated, truncated, info = env.step(action) + + # Acculumate stats and reset the env, if necessary. + sum_rewards += reward + length += 1 + if terminated or truncated: + num_episodes += 1 + episode_returns.append(sum_rewards) + episode_lengths.append(length) + sum_rewards = length = 0 + obs, infos = env.reset() + + # Compile evaluation results. + eval_results = { + "eval_returns": episode_returns, + "eval_episode_lengths": episode_lengths, + } + # Combine the most recent training results with the just collected + # evaluation results. + results = {**train_results, **eval_results} + # Report everything. + tune.report(results) + + +if __name__ == "__main__": + base_config = PPOConfig().environment("CartPole-v1").env_runners(num_env_runners=0) + # Convert to a plain dict for Tune. Note that this is usually not needed, you can + # pass into the below Tune Tuner any instantiated RLlib AlgorithmConfig object. + # However, for demonstration purposes, we show here how you can add other, arbitrary + # keys to the plain config dict and then pass these keys to your custom experiment + # function. + config_dict = base_config.to_dict() + + # Set a Special flag signalling `my_experiment` how many training steps to + # perform on each: the high learning rate and low learning rate. + config_dict["train-iterations"] = 5 + # Set a Special flag signalling `my_experiment` how many episodes to evaluate for. + config_dict["eval-episodes"] = 3 + + training_function = tune.with_resources( + my_experiment, + resources=base_config.algo_class.default_resource_request(base_config), + ) + + tuner = tune.Tuner( + training_function, + # Pass in your config dict. + param_space=config_dict, + ) + results = tuner.fit() + best_results = results.get_best_result() + + print(f"evaluation episode returns={best_results.metrics['eval_returns']}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_logger.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..12e09ba636afbb0f68a4e703cf0dfd21dc917b4a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_logger.py @@ -0,0 +1,137 @@ +"""Example showing how to define a custom Logger class for an RLlib Algorithm. + +The script uses the AlgorithmConfig's `debugging` API to setup the custom Logger: + +``` +config.debugging(logger_config={ + "type": [some Logger subclass], + "ctor_arg1", ..., + "ctor_arg2", ..., +}) +``` + +All keys other than "type" in the logger_config dict will be passed into the Logger +class's constructor. +By default (logger_config=None), RLlib will construct a Ray Tune UnifiedLogger object, +which logs results to JSON, CSV, and TBX. + +NOTE that a custom Logger is different from a custom `ProgressReporter`, which defines, +how the (frequent) outputs to your console will be formatted. To see an example on how +to write your own Progress reporter, see: +https://github.com/ray-project/ray/tree/master/rllib/examples/ray_tune/custom_progress_reporter.py # noqa + +Below examples include: +- Disable logging entirely. +- Using only one of tune's Json, CSV, or TBX loggers. +- Defining a custom logger (by sub-classing tune.logger.py::Logger). + + +How to run this script +---------------------- +`python [script file name].py` + + +Results to expect +----------------- +You should see log lines similar to the following in your console output. Note that +these logged lines will mix with the ones produced by Tune's default ProgressReporter. +See above link on how to setup a custom one. + +ABC Avg-return: 20.609375; pi-loss: -0.02921550187703246 +ABC Avg-return: 32.28688524590164; pi-loss: -0.023369029412534572 +ABC Avg-return: 51.92; pi-loss: -0.017113141975661456 +ABC Avg-return: 76.16; pi-loss: -0.01305474770361625 +ABC Avg-return: 100.54; pi-loss: -0.007665307738129169 +ABC Avg-return: 132.33; pi-loss: -0.005010405003325517 +ABC Avg-return: 169.65; pi-loss: -0.008397869592997183 +ABC Avg-return: 203.17; pi-loss: -0.005611495616764371 +Flushing +Closing + +""" + +from ray import tune +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + LEARNER_RESULTS, +) +from ray.tune.logger import Logger, LegacyLoggerCallback + + +class MyPrintLogger(Logger): + """Logs results by simply printing out everything.""" + + def _init(self): + # Custom init function. + print("Initializing ...") + # Setting up our log-line prefix. + self.prefix = self.config.get("logger_config").get("prefix") + + def on_result(self, result: dict): + # Define, what should happen on receiving a `result` (dict). + mean_return = result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + pi_loss = result[LEARNER_RESULTS][DEFAULT_MODULE_ID]["policy_loss"] + print(f"{self.prefix} " f"Avg-return: {mean_return} " f"pi-loss: {pi_loss}") + + def close(self): + # Releases all resources used by this logger. + print("Closing") + + def flush(self): + # Flushing all possible disk writes to permanent storage. + print("Flushing", flush=True) + + +if __name__ == "__main__": + config = ( + PPOConfig().environment("CartPole-v1") + # Setting up a custom logger config. + # ---------------------------------- + # The following are different examples of custom logging setups: + # 1) Disable logging entirely. + # "logger_config": { + # # Use the tune.logger.NoopLogger class for no logging. + # "type": "ray.tune.logger.NoopLogger", + # }, + # 2) Use tune's JsonLogger only. + # Alternatively, use `CSVLogger` or `TBXLogger` instead of + # `JsonLogger` in the "type" key below. + # "logger_config": { + # "type": "ray.tune.logger.JsonLogger", + # # Optional: Custom logdir (do not define this here + # # for using ~/ray_results/...). + # "logdir": "/tmp", + # }, + # 3) Custom logger (see `MyPrintLogger` class above). + .debugging( + logger_config={ + # Provide the class directly or via fully qualified class + # path. + "type": MyPrintLogger, + # `config` keys: + "prefix": "ABC", + # Optional: Custom logdir (do not define this here + # for using ~/ray_results/...). + # "logdir": "/somewhere/on/my/file/system/" + } + ) + ) + + stop = {f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": 200.0} + + # Run the actual experiment (using Tune). + results = tune.Tuner( + config.algo_class, + param_space=config, + run_config=tune.RunConfig( + stop=stop, + verbose=2, + # Plugin our own logger. + callbacks=[ + LegacyLoggerCallback([MyPrintLogger]), + ], + ), + ).fit() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_progress_reporter.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_progress_reporter.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f7c010aad1c630b3f2a67e3f452c54accde056 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/ray_tune/custom_progress_reporter.py @@ -0,0 +1,119 @@ +"""Example showing how to set up a custom progress reporter for an RLlib Algorithm. + +The script sets the `progress_reporter` arg in the tune.RunConfig and passes that to +Tune's Tuner: + +``` +tune.Tuner( + param_space=..., # <- your RLlib config + run_config=tune.RunConfig( + progress_reporter=[some already instantiated TuneReporterBase object], + ), +) +``` + +By default (progress_reporter=None), Tune will construct a default `CLIReporter` object, +which reports the episode mean return, number of env steps sampled and -trained, and +the total number of episodes run thus far. + +NOTE that a custom progress reporter is different from a custom `Logger`, which defines, +how the (frequent) results are being formatted and written to e.g. a logfile. +To see an example on how to write your own Logger, see: +https://github.com/ray-project/ray/tree/master/rllib/examples/ray_tune/custom_logger.py + + +How to run this script +---------------------- +`python [script file name].py + + +Results to expect +----------------- +You should see something similar to the following in your console output: + ++---------------------+------------+-----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +|---------------------+------------+-----------------+--------+------------------+ +| PPO_env_bb503_00000 | TERMINATED | 127.0.0.1:26303 | 5 | 30.3823 | ++---------------------+------------+-----------------+--------+------------------+ ++-------+-------------------+------------------+------------------+------------------+ +| ts | combined return | return policy1 | return policy2 | return policy3 | +|-------+-------------------+------------------+------------------+------------------| +| 20000 | 258.7 | 103.4 | 88.84 | 87.86 | ++-------+-------------------+------------------+------------------+------------------+ + +""" +from ray import tune +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) + + +my_multi_agent_progress_reporter = tune.CLIReporter( + # In the following dict, the keys are the (possibly nested) keys that can be found + # in RLlib's (PPO's) result dict, produced at every training iteration, and the + # values are the column names you would like to see in your console reports. + # Note that for nested result dict keys, you need to use slashes "/" to define the + # exact path. + metric_columns={ + **{ + TRAINING_ITERATION: "iter", + "time_total_s": "total time (s)", + NUM_ENV_STEPS_SAMPLED_LIFETIME: "ts", + # RLlib always sums up all agents' rewards and reports it under: + # result_dict[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]. + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": "combined return", + }, + # Because RLlib sums up all returns of all agents, we would like to also + # see the individual agents' returns. We can find these under the result dict's + # 'env_runners/module_episode_returns_mean/' key (then the policy ID): + **{ + f"{ENV_RUNNER_RESULTS}/module_episode_returns_mean/{pid}": f"return {pid}" + for pid in ["policy1", "policy2", "policy3"] + }, + }, +) + + +if __name__ == "__main__": + # Force Tuner to use old progress output as the new one silently ignores our custom + # `CLIReporter`. + # TODO (sven): Find out why we require this hack. + import os + + os.environ["RAY_AIR_NEW_OUTPUT"] = "0" + + # Register our multi-agent env with a fixed number of agents. + # The agents' IDs are 0, 1, and 2. + tune.register_env("env", lambda _: MultiAgentCartPole({"num_agents": 3})) + + config = ( + PPOConfig() + .environment("env") + .multi_agent( + # Define 3 policies. Note that in our simple setup, they are all configured + # the exact same way (with a PPO default RLModule/NN). + policies={"policy1", "policy2", "policy3"}, + # Map agent 0 to "policy1", etc.. + policy_mapping_fn=lambda agent_id, episode: f"policy{agent_id + 1}", + ) + ) + + stop = {f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": 200.0} + + # Run the actual experiment (using Tune). + results = tune.Tuner( + config.algo_class, + param_space=config, + run_config=tune.RunConfig( + stop=stop, + verbose=2, + # Plugin our own progress reporter. + progress_reporter=my_multi_agent_progress_reporter, + ), + ).fit() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7806a5fd3e22d19c429148f3bee54f935688393 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/action_masking_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/action_masking_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c478a7bafd4f134188b8730e28cf402e7f795e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/action_masking_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/custom_cnn_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/custom_cnn_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f621003e493d14854cf366d2a225acc340b9d7d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/custom_cnn_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/custom_lstm_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/custom_lstm_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..548568e8d5fa162e00d0dbe4322f0cfee18d7117 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/custom_lstm_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e87bcb29662f1f7613bb7e5d8e6491e113e48e10 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..747cc104f92c92e8ef00a9688c48756929c4e47a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/pretraining_single_agent_training_multi_agent.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/pretraining_single_agent_training_multi_agent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3831927452fe6ed6df5f503484ba76339c1040c4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/__pycache__/pretraining_single_agent_training_multi_agent.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/action_masking_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/action_masking_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..02d54742e7a9aaa50cef2477916c9e9d036235b0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/action_masking_rl_module.py @@ -0,0 +1,127 @@ +"""An example script showing how to define and load an `RLModule` that applies +action masking + +This example: + - Defines an `RLModule` that applies action masking. + - It does so by using a `gymnasium.spaces.dict.Dict` observation space + with two keys, namely `"observations"`, holding the original observations + and `"action_mask"` defining the action mask for the current environment + state. Note, by this definition you can wrap any `gymnasium` environment + and use it for this module. + - Furthermore, it derives its `TorchRLModule` from the `PPOTorchRLModule` and + can therefore be easily plugged into our `PPO` algorithm. + - It overrides the `forward` methods of the `PPOTorchRLModule` to apply the + action masking and it overrides the `_compute_values` method for GAE + computation to extract the `"observations"` from the batch `Columns.OBS` + key. + - It uses the custom `ActionMaskEnv` that defines for each step a new action + mask that defines actions that are allowed (1.0) and others that are not + (0.0). + - It runs 10 iterations with PPO and finishes. + +How to run this script +---------------------- +`python [script file name].py --num-env-runners 2` + +Control the number of `EnvRunner`s with the `--num-env-runners` flag. This +will increase the sampling speed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect a mean episode reward of around 0.35. The environment is a random +environment paying out random rewards - so the agent cannot learn, but it can obey the +action mask and should do so (no `AssertionError` should happen). +After 40,000 environment steps and 10 training iterations the run should stop +successfully: + ++-------------------------------+------------+----------------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-------------------------------+------------+----------------------+--------+ +| PPO_ActionMaskEnv_dedc8_00000 | TERMINATED | 192.168.1.178:103298 | 10 | ++-------------------------------+------------+----------------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | num_env_steps_sample | num_env_steps_traine | +| | d_lifetime | d_lifetime | ++------------------+------------------------+------------------------+ +| 57.9207 | 40000 | 40000 | ++------------------+------------------------+------------------------+ +*------------------------+ +| num_episodes_lifetim | +| e | ++------------------------| +| 3898 | ++------------------------+ +""" +from gymnasium.spaces import Box, Discrete + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.envs.classes.action_mask_env import ActionMaskEnv +from ray.rllib.examples.rl_modules.classes.action_masking_rlm import ( + ActionMaskingTorchRLModule, +) + +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + + +parser = add_rllib_example_script_args( + default_iters=10, + default_timesteps=100000, + default_reward=150.0, +) + +if __name__ == "__main__": + args = parser.parse_args() + + if args.algo != "PPO": + raise ValueError("This example only supports PPO. Please use --algo=PPO.") + + base_config = ( + PPOConfig() + .environment( + env=ActionMaskEnv, + env_config={ + "action_space": Discrete(100), + # This defines the 'original' observation space that is used in the + # `RLModule`. The environment will wrap this space into a + # `gym.spaces.Dict` together with an 'action_mask' that signals the + # `RLModule` to adapt the action distribution inputs for the underlying + # `DefaultPPORLModule`. + "observation_space": Box(-1.0, 1.0, (5,)), + }, + ) + .rl_module( + # We need to explicitly specify here RLModule to use and + # the catalog needed to build it. + rl_module_spec=RLModuleSpec( + module_class=ActionMaskingTorchRLModule, + model_config={ + "head_fcnet_hiddens": [64, 64], + "head_fcnet_activation": "relu", + }, + ), + ) + .evaluation( + evaluation_num_env_runners=1, + evaluation_interval=1, + # Run evaluation parallel to training to speed up the example. + evaluation_parallel_to_training=True, + ) + ) + + # Run the example (with Tune). + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b6525851c1ac8cecc0a4491a2bf04f21969ac921 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__init__.py @@ -0,0 +1,10 @@ +from ray.rllib.examples.rl_modules.classes.rock_paper_scissors_heuristic_rlm import ( + AlwaysSameHeuristicRLM, + BeatLastHeuristicRLM, +) + + +__all__ = [ + "AlwaysSameHeuristicRLM", + "BeatLastHeuristicRLM", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b6fedbbd1ee229faa1d11a2b6224405ef9efd86 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/action_masking_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/action_masking_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..892b11cd12750e3e1387c63b847d014a3c1b6ee3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/action_masking_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/autoregressive_actions_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/autoregressive_actions_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..218d1b2f97ca8f81b90eb92bef3d3cbbfd3f8f5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/autoregressive_actions_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/custom_action_distribution_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/custom_action_distribution_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df9f722e9b8898a588e73443a238550ed80af040 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/custom_action_distribution_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/intrinsic_curiosity_model_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/intrinsic_curiosity_model_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..913bfb8c5623f0e4a9ef1ee95c030536ad38d975 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/intrinsic_curiosity_model_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/lstm_containing_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/lstm_containing_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e35f14fc53048834f510bd6928707fce2637f670 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/lstm_containing_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/mobilenet_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/mobilenet_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86709a6b8901e0c04aa3b7c055e4bf4dccc8d078 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/mobilenet_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/modelv2_to_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/modelv2_to_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5a23dcfaad7652844bf80d82faa12911938afb5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/modelv2_to_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/random_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/random_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7fdfb0d932a8b66edfd22afa24715dcad50cf09 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/random_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/rock_paper_scissors_heuristic_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/rock_paper_scissors_heuristic_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba4317fed8a5144ebeb26b36ab735210fb42427c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/rock_paper_scissors_heuristic_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/tiny_atari_cnn_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/tiny_atari_cnn_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..041b77186382ea3bf856feed2605f8a115849459 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/tiny_atari_cnn_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/vpg_torch_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/vpg_torch_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07fa76b31153120aa7883aba644300cdc42eb3ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/vpg_torch_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/vpg_using_shared_encoder_rlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/vpg_using_shared_encoder_rlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c9e2c0ffb4b80dac7dc184fa0ef308f2cf50f09 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/vpg_using_shared_encoder_rlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/action_masking_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/action_masking_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..aee91f203c8790f7688094f79bec5eeeb4fadf33 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/action_masking_rlm.py @@ -0,0 +1,210 @@ +import gymnasium as gym +from typing import Dict, Optional, Tuple, Union + +from ray.rllib.algorithms.ppo.torch.ppo_torch_rl_module import PPOTorchRLModule +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import FLOAT_MIN +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +class ActionMaskingRLModule(RLModule): + """An RLModule that implements an action masking for safe RL. + + This RLModule implements action masking to avoid unsafe/unwanted actions + dependent on the current state (observations). It does so by using an + environment generated action mask defining which actions are allowed and + which should be avoided. The action mask is extracted from the + environment's `gymnasium.spaces.dict.Dict` observation and applied after + the module's `forward`-pass to the action logits. The resulting action + logits prevent unsafe/unwanted actions to be sampled from the corresponding + action distribution. + + Note, this RLModule is implemented for the `PPO` algorithm only. It is not + guaranteed to work with other algorithms. Furthermore, not that for this + module to work it requires an environment with a `gymnasium.spaces.dict.Dict` + observation space containing tow key, `"action_mask"` and `"observations"`. + """ + + @override(RLModule) + def __init__( + self, + *, + observation_space: Optional[gym.Space] = None, + action_space: Optional[gym.Space] = None, + inference_only: Optional[bool] = None, + learner_only: bool = False, + model_config: Optional[Union[dict, DefaultModelConfig]] = None, + catalog_class=None, + **kwargs, + ): + # If observation space is not of type `Dict` raise an error. + if not isinstance(observation_space, gym.spaces.dict.Dict): + raise ValueError( + "This RLModule requires the environment to provide a " + "`gym.spaces.Dict` observation space of the form: \n" + " {'action_mask': Box(0.0, 1.0, shape=(self.action_space.n,))," + " 'observation_space': self.observation_space}" + ) + + # While the environment holds an observation space that contains, both, + # the action mask and the original observation space, the 'RLModule' + # receives only the `"observation"` element of the space, but not the + # action mask. + self.observation_space_with_mask = observation_space + self.observation_space = observation_space["observations"] + + # Keeps track if observation specs have been checked already. + self._checked_observations = False + + # The DefaultPPORLModule, in its constructor will build networks for the + # original observation space (i.e. without the action mask). + super().__init__( + observation_space=self.observation_space, + action_space=action_space, + inference_only=inference_only, + learner_only=learner_only, + model_config=model_config, + catalog_class=catalog_class, + **kwargs, + ) + + +class ActionMaskingTorchRLModule(ActionMaskingRLModule, PPOTorchRLModule): + @override(PPOTorchRLModule) + def setup(self): + super().setup() + # We need to reset here the observation space such that the + # super`s (`PPOTorchRLModule`) observation space is the + # original space (i.e. without the action mask) and `self`'s + # observation space contains the action mask. + self.observation_space = self.observation_space_with_mask + + @override(PPOTorchRLModule) + def _forward_inference( + self, batch: Dict[str, TensorType], **kwargs + ) -> Dict[str, TensorType]: + # Preprocess the original batch to extract the action mask. + action_mask, batch = self._preprocess_batch(batch) + # Run the forward pass. + outs = super()._forward_inference(batch, **kwargs) + # Mask the action logits and return. + return self._mask_action_logits(outs, action_mask) + + @override(PPOTorchRLModule) + def _forward_exploration( + self, batch: Dict[str, TensorType], **kwargs + ) -> Dict[str, TensorType]: + # Preprocess the original batch to extract the action mask. + action_mask, batch = self._preprocess_batch(batch) + # Run the forward pass. + outs = super()._forward_exploration(batch, **kwargs) + # Mask the action logits and return. + return self._mask_action_logits(outs, action_mask) + + @override(PPOTorchRLModule) + def _forward_train( + self, batch: Dict[str, TensorType], **kwargs + ) -> Dict[str, TensorType]: + # Run the forward pass. + outs = super()._forward_train(batch, **kwargs) + # Mask the action logits and return. + return self._mask_action_logits(outs, batch["action_mask"]) + + @override(ValueFunctionAPI) + def compute_values(self, batch: Dict[str, TensorType], embeddings=None): + # Check, if the observations are still in `dict` form. + if isinstance(batch[Columns.OBS], dict): + # Preprocess the batch to extract the `observations` to `Columns.OBS`. + action_mask, batch = self._preprocess_batch(batch) + # NOTE: Because we manipulate the batch we need to add the `action_mask` + # to the batch to access them in `_forward_train`. + batch["action_mask"] = action_mask + # Call the super's method to compute values for GAE. + return super().compute_values(batch, embeddings) + + def _preprocess_batch( + self, batch: Dict[str, TensorType], **kwargs + ) -> Tuple[TensorType, Dict[str, TensorType]]: + """Extracts observations and action mask from the batch + + Args: + batch: A dictionary containing tensors (at least `Columns.OBS`) + + Returns: + A tuple with the action mask tensor and the modified batch containing + the original observations. + """ + # Check observation specs for action mask and observation keys. + self._check_batch(batch) + + # Extract the available actions tensor from the observation. + action_mask = batch[Columns.OBS].pop("action_mask") + + # Modify the batch for the `DefaultPPORLModule`'s `forward` method, i.e. + # pass only `"obs"` into the `forward` method. + batch[Columns.OBS] = batch[Columns.OBS].pop("observations") + + # Return the extracted action mask and the modified batch. + return action_mask, batch + + def _mask_action_logits( + self, batch: Dict[str, TensorType], action_mask: TensorType + ) -> Dict[str, TensorType]: + """Masks the action logits for the output of `forward` methods + + Args: + batch: A dictionary containing tensors (at least action logits). + action_mask: A tensor containing the action mask for the current + observations. + + Returns: + A modified batch with masked action logits for the action distribution + inputs. + """ + # Convert action mask into an `[0.0][-inf]`-type mask. + inf_mask = torch.clamp(torch.log(action_mask), min=FLOAT_MIN) + + # Mask the logits. + batch[Columns.ACTION_DIST_INPUTS] += inf_mask + + # Return the batch with the masked action logits. + return batch + + def _check_batch(self, batch: Dict[str, TensorType]) -> Optional[ValueError]: + """Assert that the batch includes action mask and observations. + + Args: + batch: A dicitonary containing tensors (at least `Columns.OBS`) to be + checked. + + Raises: + `ValueError` if the column `Columns.OBS` does not contain observations + and action mask. + """ + if not self._checked_observations: + if "action_mask" not in batch[Columns.OBS]: + raise ValueError( + "No action mask found in observation. This `RLModule` requires " + "the environment to provide observations that include an " + "action mask (i.e. an observation space of the Dict space " + "type that looks as follows: \n" + "{'action_mask': Box(0.0, 1.0, shape=(self.action_space.n,))," + "'observations': self.observation_space}" + ) + if "observations" not in batch[Columns.OBS]: + raise ValueError( + "No observations found in observation. This 'RLModule` requires " + "the environment to provide observations that include the original " + "observations under a key `'observations'` in a dict (i.e. an " + "observation space of the Dict space type that looks as follows: \n" + "{'action_mask': Box(0.0, 1.0, shape=(self.action_space.n,))," + "'observations': }" + ) + self._checked_observations = True diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/autoregressive_actions_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/autoregressive_actions_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..e9449d61b9b39a847cf660791ca2e93394020716 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/autoregressive_actions_rlm.py @@ -0,0 +1,129 @@ +from typing import Dict + +import gymnasium as gym + +from ray.rllib.core import Columns +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.core.rl_module.torch.torch_rl_module import TorchRLModule +from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchCategorical, + TorchDiagGaussian, + TorchMultiDistribution, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import one_hot +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +class AutoregressiveActionsRLM(TorchRLModule, ValueFunctionAPI): + """An RLModule that uses an autoregressive action distribution. + + Actions are sampled in two steps. The first (prior) action component is sampled from + a categorical distribution. Then, the second (posterior) action component is sampled + from a posterior distribution that depends on the first action component and the + other input data (observations). + + Note, this RLModule works in combination with any algorithm, whose Learners require + the `ValueFunctionAPI`. + """ + + @override(RLModule) + def setup(self): + super().setup() + + # Assert the action space is correct. + assert isinstance(self.action_space, gym.spaces.Tuple) + assert isinstance(self.action_space[0], gym.spaces.Discrete) + assert self.action_space[0].n == 3 + assert isinstance(self.action_space[1], gym.spaces.Box) + + self._prior_net = nn.Sequential( + nn.Linear( + in_features=self.observation_space.shape[0], + out_features=256, + ), + nn.Tanh(), + nn.Linear(in_features=256, out_features=self.action_space[0].n), + ) + + self._posterior_net = nn.Sequential( + nn.Linear( + in_features=self.observation_space.shape[0] + self.action_space[0].n, + out_features=256, + ), + nn.Tanh(), + nn.Linear(in_features=256, out_features=self.action_space[1].shape[0] * 2), + ) + + # Build the value function head. + self._value_net = nn.Sequential( + nn.Linear( + in_features=self.observation_space.shape[0], + out_features=256, + ), + nn.Tanh(), + nn.Linear(in_features=256, out_features=1), + ) + + @override(TorchRLModule) + def _forward_inference(self, batch: Dict[str, TensorType]) -> Dict[str, TensorType]: + return self._pi(batch[Columns.OBS], inference=True) + + @override(TorchRLModule) + def _forward_exploration( + self, batch: Dict[str, TensorType], **kwargs + ) -> Dict[str, TensorType]: + return self._pi(batch[Columns.OBS], inference=False) + + @override(TorchRLModule) + def _forward_train(self, batch: Dict[str, TensorType]) -> Dict[str, TensorType]: + return self._forward_exploration(batch) + + @override(ValueFunctionAPI) + def compute_values(self, batch: Dict[str, TensorType], embeddings=None): + # Value function forward pass. + vf_out = self._value_net(batch[Columns.OBS]) + # Squeeze out last dimension (single node value head). + return vf_out.squeeze(-1) + + # __sphinx_begin__ + def _pi(self, obs, inference: bool): + # Prior forward pass and sample a1. + prior_out = self._prior_net(obs) + dist_a1 = TorchCategorical.from_logits(prior_out) + if inference: + dist_a1 = dist_a1.to_deterministic() + a1 = dist_a1.sample() + + # Posterior forward pass and sample a2. + posterior_batch = torch.cat( + [obs, one_hot(a1, self.action_space[0])], + dim=-1, + ) + posterior_out = self._posterior_net(posterior_batch) + dist_a2 = TorchDiagGaussian.from_logits(posterior_out) + if inference: + dist_a2 = dist_a2.to_deterministic() + a2 = dist_a2.sample() + actions = (a1, a2) + + # We need logp and distribution parameters for the loss. + return { + Columns.ACTION_LOGP: ( + TorchMultiDistribution((dist_a1, dist_a2)).logp(actions) + ), + Columns.ACTION_DIST_INPUTS: torch.cat([prior_out, posterior_out], dim=-1), + Columns.ACTIONS: actions, + } + # __sphinx_end__ + + @override(TorchRLModule) + def get_inference_action_dist_cls(self): + return TorchMultiDistribution.get_partial_dist_cls( + child_distribution_cls_struct=(TorchCategorical, TorchDiagGaussian), + input_lens=(3, 2), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/custom_action_distribution_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/custom_action_distribution_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c6e26d94c0c9ea53ae97c4b4142fe2c2f556f1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/custom_action_distribution_rlm.py @@ -0,0 +1,153 @@ +from typing import Any, Dict, Optional + +from ray.rllib.core.columns import Columns +from ray.rllib.core.distribution.torch.torch_distribution import TorchCategorical +from ray.rllib.core.rl_module.apis import ValueFunctionAPI +from ray.rllib.core.rl_module.torch import TorchRLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +def _make_categorical_with_temperature(temp): + """Helper function to create a new action distribution class. + + The returned class takes a temperature parameter in its constructor with the default + value `temp`. + + Args: + temp: The default temperature to use for the generated distribution class. + """ + + class TorchCategoricalWithTemp(TorchCategorical): + def __init__(self, logits=None, probs=None, temperature: float = temp): + """Initializes a TorchCategoricalWithTemp instance. + + Args: + logits: Event log probabilities (non-normalized). + probs: The probabilities of each event. + temperature: In case of using logits, this parameter can be used to + determine the sharpness of the distribution. i.e. + ``probs = softmax(logits / temperature)``. The temperature must be + strictly positive. A low value (e.g. 1e-10) will result in argmax + sampling while a larger value will result in uniform sampling. + """ + # Either divide logits or probs by the temperature. + assert ( + temperature > 0.0 + ), f"Temperature ({temperature}) must be strictly positive!" + if logits is not None: + logits /= temperature + else: + probs = torch.nn.functional.softmax(probs / temperature) + super().__init__(logits, probs) + + return TorchCategoricalWithTemp + + +class CustomActionDistributionRLModule(TorchRLModule, ValueFunctionAPI): + """A simple TorchRLModule with its own custom action distribution. + + The distribution differs from the default one by an additional temperature + parameter applied on top of the Categorical base distribution. See the above + `TorchCategoricalWithTemp` class for details. + + .. testcode:: + + import numpy as np + import gymnasium as gym + + my_net = CustomActionDistributionRLModule( + observation_space=gym.spaces.Box(-1.0, 1.0, (4,), np.float32), + action_space=gym.spaces.Discrete(4), + model_config={"action_dist_temperature": 5.0}, + ) + + B = 10 + data = torch.from_numpy( + np.random.random_sample(size=(B, 4)).astype(np.float32) + ) + # Expect a relatively high-temperature distribution. + # Set "action_dist_temperature" to small values << 1.0 to approximate greedy + # behavior (even when stochastically sampling from the distribution). + print(my_net.forward_exploration({"obs": data})) + """ + + @override(TorchRLModule) + def setup(self): + """Use this method to create all the model components that you require. + + Feel free to access the following useful properties in this class: + - `self.model_config`: The config dict for this RLModule class, + which should contain flexible settings, for example: {"hiddens": [256, 256]}. + - `self.observation|action_space`: The observation and action space that + this RLModule is subject to. Note that the observation space might not be the + exact space from your env, but that it might have already gone through + preprocessing through a connector pipeline (for example, flattening, + frame-stacking, mean/std-filtering, etc..). + - `self.inference_only`: If True, this model should be built only for inference + purposes, in which case you may want to exclude any components that are not used + for computing actions, for example a value function branch. + """ + input_dim = self.observation_space.shape[0] + hidden_dim = self.model_config.get("hidden_dim", 256) + output_dim = self.action_space.n + + # Define simple encoder, and policy- and vf heads. + self._encoder = torch.nn.Sequential( + torch.nn.Linear(input_dim, hidden_dim), + torch.nn.ReLU(), + ) + self._policy_net = torch.nn.Linear(hidden_dim, output_dim) + self._vf = nn.Linear(hidden_dim, 1) + + # Plug in a custom action dist class. + # NOTE: If you need more granularity as to which distribution class is used by + # which forward method (`forward_inference`, `forward_exploration`, + # `forward_train`), override the RLModule methods + # `get_inference_action_dist_cls`, `get_exploration_action_dist_cls`, and + # `get_train_action_dist_cls`, and return + # your custom class(es) from these. In this case, leave `self.action_dist_cls` + # set to None, its default value. + self.action_dist_cls = _make_categorical_with_temperature( + self.model_config["action_dist_temperature"] + ) + + @override(TorchRLModule) + def _forward(self, batch, **kwargs): + # Compute the basic 1D feature tensor (inputs to policy- and value-heads). + _, logits = self._compute_embeddings_and_logits(batch) + # Return features and logits as ACTION_DIST_INPUTS (categorical distribution). + return { + Columns.ACTION_DIST_INPUTS: logits, + } + + @override(TorchRLModule) + def _forward_train(self, batch, **kwargs): + # Compute the basic 1D feature tensor (inputs to policy- and value-heads). + embeddings, logits = self._compute_embeddings_and_logits(batch) + # Return features and logits as ACTION_DIST_INPUTS (categorical distribution). + return { + Columns.ACTION_DIST_INPUTS: logits, + Columns.EMBEDDINGS: embeddings, + } + + # We implement this RLModule as a ValueFunctionAPI RLModule, so it can be used + # by value-based methods like PPO or IMPALA. + @override(ValueFunctionAPI) + def compute_values( + self, + batch: Dict[str, Any], + embeddings: Optional[Any] = None, + ) -> TensorType: + # Features not provided -> We need to compute them first. + if embeddings is None: + embeddings = self._encoder(batch[Columns.OBS]) + return self._vf(embeddings).squeeze(-1) + + def _compute_embeddings_and_logits(self, batch): + embeddings = self._encoder(batch[Columns.OBS]) + logits = self._policy_net(embeddings) + return embeddings, logits diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/intrinsic_curiosity_model_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/intrinsic_curiosity_model_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..efa3fcdb1d6ba36c07039c466489acce5c731cea --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/intrinsic_curiosity_model_rlm.py @@ -0,0 +1,240 @@ +from typing import Any, Dict, TYPE_CHECKING + +import tree # pip install dm_tree + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.apis import SelfSupervisedLossAPI +from ray.rllib.core.rl_module.torch import TorchRLModule +from ray.rllib.models.utils import get_activation_fn +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import one_hot +from ray.rllib.utils.typing import ModuleID + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.core.learner.torch.torch_learner import TorchLearner + +torch, nn = try_import_torch() + + +class IntrinsicCuriosityModel(TorchRLModule, SelfSupervisedLossAPI): + """An intrinsic curiosity model (ICM) as TorchRLModule for better exploration. + + For more details, see: + [1] Curiosity-driven Exploration by Self-supervised Prediction + Pathak, Agrawal, Efros, and Darrell - UC Berkeley - ICML 2017. + https://arxiv.org/pdf/1705.05363.pdf + + Learns a simplified model of the environment based on three networks: + 1) Embedding observations into latent space ("feature" network). + 2) Predicting the action, given two consecutive embedded observations + ("inverse" network). + 3) Predicting the next embedded obs, given an obs and action + ("forward" network). + + The less the agent is able to predict the actually observed next feature + vector, given obs and action (through the forwards network), the larger the + "intrinsic reward", which will be added to the extrinsic reward. + Therefore, if a state transition was unexpected, the agent becomes + "curious" and will further explore this transition leading to better + exploration in sparse rewards environments. + + .. testcode:: + + import numpy as np + import gymnasium as gym + import torch + + from ray.rllib.core import Columns + from ray.rllib.examples.rl_modules.classes.intrinsic_curiosity_model_rlm import ( # noqa + IntrinsicCuriosityModel + ) + + B = 10 # batch size + O = 4 # obs (1D) dim + A = 2 # num actions + f = 25 # feature dim + + # Construct the RLModule. + icm_net = IntrinsicCuriosityModel( + observation_space=gym.spaces.Box(-1.0, 1.0, (O,), np.float32), + action_space=gym.spaces.Discrete(A), + ) + + # Create some dummy input. + obs = torch.from_numpy( + np.random.random_sample(size=(B, O)).astype(np.float32) + ) + next_obs = torch.from_numpy( + np.random.random_sample(size=(B, O)).astype(np.float32) + ) + actions = torch.from_numpy( + np.random.random_integers(0, A - 1, size=(B,)) + ) + input_dict = { + Columns.OBS: obs, + Columns.NEXT_OBS: next_obs, + Columns.ACTIONS: actions, + } + + # Call `forward_train()` to get phi (feature vector from obs), next-phi + # (feature vector from next obs), and the intrinsic rewards (individual, per + # batch-item forward loss values). + print(icm_net.forward_train(input_dict)) + + # Print out the number of parameters. + num_all_params = sum(int(np.prod(p.size())) for p in icm_net.parameters()) + print(f"num params = {num_all_params}") + """ + + @override(TorchRLModule) + def setup(self): + # Get the ICM achitecture settings from the `model_config` attribute: + cfg = self.model_config + + feature_dim = cfg.get("feature_dim", 288) + + # Build the feature model (encoder of observations to feature space). + layers = [] + dense_layers = cfg.get("feature_net_hiddens", (256, 256)) + # `in_size` is the observation space (assume a simple Box(1D)). + in_size = self.observation_space.shape[0] + for out_size in dense_layers: + layers.append(nn.Linear(in_size, out_size)) + if cfg.get("feature_net_activation") not in [None, "linear"]: + layers.append( + get_activation_fn(cfg["feature_net_activation"], "torch")() + ) + in_size = out_size + # Last feature layer of n nodes (feature dimension). + layers.append(nn.Linear(in_size, feature_dim)) + self._feature_net = nn.Sequential(*layers) + + # Build the inverse model (predicting the action between two observations). + layers = [] + dense_layers = cfg.get("inverse_net_hiddens", (256,)) + # `in_size` is 2x the feature dim. + in_size = feature_dim * 2 + for out_size in dense_layers: + layers.append(nn.Linear(in_size, out_size)) + if cfg.get("inverse_net_activation") not in [None, "linear"]: + layers.append( + get_activation_fn(cfg["inverse_net_activation"], "torch")() + ) + in_size = out_size + # Last feature layer of n nodes (action space). + layers.append(nn.Linear(in_size, self.action_space.n)) + self._inverse_net = nn.Sequential(*layers) + + # Build the forward model (predicting the next observation from current one and + # action). + layers = [] + dense_layers = cfg.get("forward_net_hiddens", (256,)) + # `in_size` is the feature dim + action space (one-hot). + in_size = feature_dim + self.action_space.n + for out_size in dense_layers: + layers.append(nn.Linear(in_size, out_size)) + if cfg.get("forward_net_activation") not in [None, "linear"]: + layers.append( + get_activation_fn(cfg["forward_net_activation"], "torch")() + ) + in_size = out_size + # Last feature layer of n nodes (feature dimension). + layers.append(nn.Linear(in_size, feature_dim)) + self._forward_net = nn.Sequential(*layers) + + @override(TorchRLModule) + def _forward_train(self, batch, **kwargs): + # Push both observations through feature net to get feature vectors (phis). + # We cat/batch them here for efficiency reasons (save one forward pass). + obs = tree.map_structure( + lambda obs, next_obs: torch.cat([obs, next_obs], dim=0), + batch[Columns.OBS], + batch[Columns.NEXT_OBS], + ) + phis = self._feature_net(obs) + # Split again to yield 2 individual phi tensors. + phi, next_phi = torch.chunk(phis, 2) + + # Predict next feature vector (next_phi) with forward model (using obs and + # actions). + predicted_next_phi = self._forward_net( + torch.cat( + [ + phi, + one_hot(batch[Columns.ACTIONS].long(), self.action_space).float(), + ], + dim=-1, + ) + ) + + # Forward loss term: Predicted phi - given phi and action - vs actually observed + # phi (square-root of L2 norm). Note that this is the intrinsic reward that + # will be used and the mean of this is the forward net loss. + forward_l2_norm_sqrt = 0.5 * torch.sum( + torch.pow(predicted_next_phi - next_phi, 2.0), dim=-1 + ) + + output = { + Columns.INTRINSIC_REWARDS: forward_l2_norm_sqrt, + # Computed feature vectors (used to compute the losses later). + "phi": phi, + "next_phi": next_phi, + } + + return output + + @override(SelfSupervisedLossAPI) + def compute_self_supervised_loss( + self, + *, + learner: "TorchLearner", + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, Any], + ) -> Dict[str, Any]: + module = learner.module[module_id].unwrapped() + + # Forward net loss. + forward_loss = torch.mean(fwd_out[Columns.INTRINSIC_REWARDS]) + + # Inverse loss term (predicted action that led from phi to phi' vs + # actual action taken). + dist_inputs = module._inverse_net( + torch.cat([fwd_out["phi"], fwd_out["next_phi"]], dim=-1) + ) + action_dist = module.get_train_action_dist_cls().from_logits(dist_inputs) + + # Neg log(p); p=probability of observed action given the inverse-NN + # predicted action distribution. + inverse_loss = -action_dist.logp(batch[Columns.ACTIONS]) + inverse_loss = torch.mean(inverse_loss) + + # Calculate the ICM loss. + total_loss = ( + config.learner_config_dict["forward_loss_weight"] * forward_loss + + (1.0 - config.learner_config_dict["forward_loss_weight"]) * inverse_loss + ) + + learner.metrics.log_dict( + { + "mean_intrinsic_rewards": forward_loss, + "forward_loss": forward_loss, + "inverse_loss": inverse_loss, + }, + key=module_id, + window=1, + ) + + return total_loss + + # Inference and exploration not supported (this is a world-model that should only + # be used for training). + @override(TorchRLModule) + def _forward(self, batch, **kwargs): + raise NotImplementedError( + "`IntrinsicCuriosityModel` should only be used for training! " + "Only calls to `forward_train()` supported." + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/lstm_containing_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/lstm_containing_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..0e05bd2c4c7f2aaf2e02eb4df834a85f2ec661f1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/lstm_containing_rlm.py @@ -0,0 +1,152 @@ +from typing import Any, Dict, Optional + +import numpy as np + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.core.rl_module.torch import TorchRLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +class LSTMContainingRLModule(TorchRLModule, ValueFunctionAPI): + """An example TorchRLModule that contains an LSTM layer. + + .. testcode:: + + import numpy as np + import gymnasium as gym + + B = 10 # batch size + T = 5 # seq len + e = 25 # embedding dim + CELL = 32 # LSTM cell size + + # Construct the RLModule. + my_net = LSTMContainingRLModule( + observation_space=gym.spaces.Box(-1.0, 1.0, (e,), np.float32), + action_space=gym.spaces.Discrete(4), + model_config={"lstm_cell_size": CELL} + ) + + # Create some dummy input. + obs = torch.from_numpy( + np.random.random_sample(size=(B, T, e) + ).astype(np.float32)) + state_in = my_net.get_initial_state() + # Repeat state_in across batch. + state_in = tree.map_structure( + lambda s: torch.from_numpy(s).unsqueeze(0).repeat(B, 1), state_in + ) + input_dict = { + Columns.OBS: obs, + Columns.STATE_IN: state_in, + } + + # Run through all 3 forward passes. + print(my_net.forward_inference(input_dict)) + print(my_net.forward_exploration(input_dict)) + print(my_net.forward_train(input_dict)) + + # Print out the number of parameters. + num_all_params = sum(int(np.prod(p.size())) for p in my_net.parameters()) + print(f"num params = {num_all_params}") + """ + + @override(TorchRLModule) + def setup(self): + """Use this method to create all the model components that you require. + + Feel free to access the following useful properties in this class: + - `self.model_config`: The config dict for this RLModule class, + which should contain flxeible settings, for example: {"hiddens": [256, 256]}. + - `self.observation|action_space`: The observation and action space that + this RLModule is subject to. Note that the observation space might not be the + exact space from your env, but that it might have already gone through + preprocessing through a connector pipeline (for example, flattening, + frame-stacking, mean/std-filtering, etc..). + """ + # Assume a simple Box(1D) tensor as input shape. + in_size = self.observation_space.shape[0] + + # Get the LSTM cell size from the `model_config` attribute: + self._lstm_cell_size = self.model_config.get("lstm_cell_size", 256) + self._lstm = nn.LSTM(in_size, self._lstm_cell_size, batch_first=True) + in_size = self._lstm_cell_size + + # Build a sequential stack. + layers = [] + # Get the dense layer pre-stack configuration from the same config dict. + dense_layers = self.model_config.get("dense_layers", [128, 128]) + for out_size in dense_layers: + # Dense layer. + layers.append(nn.Linear(in_size, out_size)) + # ReLU activation. + layers.append(nn.ReLU()) + in_size = out_size + + self._fc_net = nn.Sequential(*layers) + + # Logits layer (no bias, no activation). + self._pi_head = nn.Linear(in_size, self.action_space.n) + # Single-node value layer. + self._values = nn.Linear(in_size, 1) + + @override(TorchRLModule) + def get_initial_state(self) -> Any: + return { + "h": np.zeros(shape=(self._lstm_cell_size,), dtype=np.float32), + "c": np.zeros(shape=(self._lstm_cell_size,), dtype=np.float32), + } + + @override(TorchRLModule) + def _forward(self, batch, **kwargs): + # Compute the basic 1D embedding tensor (inputs to policy- and value-heads). + embeddings, state_outs = self._compute_embeddings_and_state_outs(batch) + logits = self._pi_head(embeddings) + + # Return logits as ACTION_DIST_INPUTS (categorical distribution). + # Note that the default `GetActions` connector piece (in the EnvRunner) will + # take care of argmax-"sampling" from the logits to yield the inference (greedy) + # action. + return { + Columns.ACTION_DIST_INPUTS: logits, + Columns.STATE_OUT: state_outs, + } + + @override(TorchRLModule) + def _forward_train(self, batch, **kwargs): + # Same logic as _forward, but also return embeddings to be used by value + # function branch during training. + embeddings, state_outs = self._compute_embeddings_and_state_outs(batch) + logits = self._pi_head(embeddings) + return { + Columns.ACTION_DIST_INPUTS: logits, + Columns.STATE_OUT: state_outs, + Columns.EMBEDDINGS: embeddings, + } + + # We implement this RLModule as a ValueFunctionAPI RLModule, so it can be used + # by value-based methods like PPO or IMPALA. + @override(ValueFunctionAPI) + def compute_values( + self, batch: Dict[str, Any], embeddings: Optional[Any] = None + ) -> TensorType: + if embeddings is None: + embeddings, _ = self._compute_embeddings_and_state_outs(batch) + values = self._values(embeddings).squeeze(-1) + return values + + def _compute_embeddings_and_state_outs(self, batch): + obs = batch[Columns.OBS] + state_in = batch[Columns.STATE_IN] + h, c = state_in["h"], state_in["c"] + # Unsqueeze the layer dim (we only have 1 LSTM layer). + embeddings, (h, c) = self._lstm(obs, (h.unsqueeze(0), c.unsqueeze(0))) + # Push through our FC net. + embeddings = self._fc_net(embeddings) + # Squeeze the layer dim (we only have 1 LSTM layer). + return embeddings, {"h": h.squeeze(0), "c": c.squeeze(0)} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/mobilenet_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/mobilenet_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..c945acfb583a83827d0f5cd255b7a17dc38628bb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/mobilenet_rlm.py @@ -0,0 +1,84 @@ +""" +This example shows how to take full control over what models and action distribution +are being built inside an RL Module. With this pattern, we can bypass a Catalog and +explicitly define our own models within a given RL Module. +""" +# __sphinx_doc_begin__ +import gymnasium as gym +import numpy as np + +from ray.rllib.algorithms.ppo.ppo import PPOConfig +from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( + DefaultPPOTorchRLModule, +) +from ray.rllib.core.models.configs import MLPHeadConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.envs.classes.random_env import RandomEnv +from ray.rllib.examples._old_api_stack.models.mobilenet_v2_encoder import ( + MobileNetV2EncoderConfig, + MOBILENET_INPUT_SHAPE, +) +from ray.rllib.core.models.configs import ActorCriticEncoderConfig + + +class MobileNetTorchPPORLModule(DefaultPPOTorchRLModule): + """A DefaultPPORLModule with mobilenet v2 as an encoder. + + The idea behind this model is to demonstrate how we can bypass catalog to + take full control over what models and action distribution are being built. + In this example, we do this to modify an existing RLModule with a custom encoder. + """ + + def setup(self): + mobilenet_v2_config = MobileNetV2EncoderConfig() + # Since we want to use PPO, which is an actor-critic algorithm, we need to + # use an ActorCriticEncoderConfig to wrap the base encoder config. + actor_critic_encoder_config = ActorCriticEncoderConfig( + base_encoder_config=mobilenet_v2_config + ) + + self.encoder = actor_critic_encoder_config.build(framework="torch") + mobilenet_v2_output_dims = mobilenet_v2_config.output_dims + + pi_config = MLPHeadConfig( + input_dims=mobilenet_v2_output_dims, + output_layer_dim=2, + ) + + vf_config = MLPHeadConfig( + input_dims=mobilenet_v2_output_dims, output_layer_dim=1 + ) + + self.pi = pi_config.build(framework="torch") + self.vf = vf_config.build(framework="torch") + + +config = ( + PPOConfig() + .environment( + RandomEnv, + env_config={ + "action_space": gym.spaces.Discrete(2), + # Test a simple Image observation space. + "observation_space": gym.spaces.Box( + 0.0, + 1.0, + shape=MOBILENET_INPUT_SHAPE, + dtype=np.float32, + ), + }, + ) + .env_runners(num_env_runners=0) + # The following training settings make it so that a training iteration is very + # quick. This is just for the sake of this example. PPO will not learn properly + # with these settings! + .training( + train_batch_size_per_learner=32, + minibatch_size=16, + num_epochs=1, + ) + .rl_module(rl_module_spec=RLModuleSpec(module_class=MobileNetTorchPPORLModule)) +) + +config.build().train() +# __sphinx_doc_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/modelv2_to_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/modelv2_to_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..10eaf2238d9a344d1e25a3dc3c378cf8717a6eaa --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/modelv2_to_rlm.py @@ -0,0 +1,206 @@ +import pathlib +from typing import Any, Dict, Optional + +import tree +from ray.rllib.core import Columns, DEFAULT_POLICY_ID +from ray.rllib.core.rl_module.apis import ValueFunctionAPI +from ray.rllib.core.rl_module.torch import TorchRLModule +from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchCategorical, + TorchDiagGaussian, + TorchMultiCategorical, + TorchMultiDistribution, + TorchSquashedGaussian, +) +from ray.rllib.models.torch.torch_action_dist import ( + TorchCategorical as OldTorchCategorical, + TorchDiagGaussian as OldTorchDiagGaussian, + TorchMultiActionDistribution as OldTorchMultiActionDistribution, + TorchMultiCategorical as OldTorchMultiCategorical, + TorchSquashedGaussian as OldTorchSquashedGaussian, +) +from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch + +torch, _ = try_import_torch() + + +class ModelV2ToRLModule(TorchRLModule, ValueFunctionAPI): + """An RLModule containing a (old stack) ModelV2. + + The `ModelV2` may be define either through + - an existing Policy checkpoint + - an existing Algorithm checkpoint (and a policy ID or "default_policy") + - or through an AlgorithmConfig object + + The ModelV2 is created in the `setup` and contines to live through the lifetime + of the RLModule. + """ + + @override(TorchRLModule) + def setup(self): + # Try extracting the policy ID from this RLModule's config dict. + policy_id = self.model_config.get("policy_id", DEFAULT_POLICY_ID) + + # Try getting the algorithm checkpoint from the `model_config`. + algo_checkpoint_dir = self.model_config.get("algo_checkpoint_dir") + if algo_checkpoint_dir: + algo_checkpoint_dir = pathlib.Path(algo_checkpoint_dir) + if not algo_checkpoint_dir.is_dir(): + raise ValueError( + "The `model_config` of your RLModule must contain a " + "`algo_checkpoint_dir` key pointing to the algo checkpoint " + "directory! You can find this dir inside the results dir of your " + "experiment. You can then add this path " + "through `config.rl_module(model_config={" + "'algo_checkpoint_dir': [your algo checkpoint dir]})`." + ) + policy_checkpoint_dir = algo_checkpoint_dir / "policies" / policy_id + # Try getting the policy checkpoint from the `model_config`. + else: + policy_checkpoint_dir = self.model_config.get("policy_checkpoint_dir") + + # Create the ModelV2 from the Policy. + if policy_checkpoint_dir: + policy_checkpoint_dir = pathlib.Path(policy_checkpoint_dir) + if not policy_checkpoint_dir.is_dir(): + raise ValueError( + "The `model_config` of your RLModule must contain a " + "`policy_checkpoint_dir` key pointing to the policy checkpoint " + "directory! You can find this dir under the Algorithm's checkpoint " + "dir in subdirectory: [algo checkpoint dir]/policies/[policy ID " + "ex. `default_policy`]. You can then add this path through `config" + ".rl_module(model_config={'policy_checkpoint_dir': " + "[your policy checkpoint dir]})`." + ) + # Create a temporary policy object. + policy = TorchPolicyV2.from_checkpoint(policy_checkpoint_dir) + # Create the ModelV2 from scratch using the config. + else: + config = self.model_config.get("old_api_stack_algo_config") + if not config: + raise ValueError( + "The `model_config` of your RLModule must contain a " + "`algo_config` key with a AlgorithmConfig object in it that " + "contains all the settings that would be necessary to construct a " + "old API stack Algorithm/Policy/ModelV2! You can add this setting " + "through `config.rl_module(model_config={'algo_config': " + "[your old config]})`." + ) + # Get the multi-agent policies dict. + policy_dict, _ = config.get_multi_agent_setup( + spaces={ + policy_id: (self.observation_space, self.action_space), + }, + default_policy_class=config.algo_class.get_default_policy_class(config), + ) + config = config.to_dict() + config["__policy_id"] = policy_id + policy = policy_dict[policy_id].policy_class( + self.observation_space, + self.action_space, + config, + ) + + self._model_v2 = policy.model + + # Translate the action dist classes from the old API stack to the new. + self.action_dist_class = self._translate_dist_class(policy.dist_class) + + # Erase the torch policy from memory, so it can be garbage collected. + del policy + + @override(TorchRLModule) + def _forward_inference(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + return self._forward_pass(batch, inference=True) + + @override(TorchRLModule) + def _forward_exploration(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + return self._forward_inference(batch, **kwargs) + + @override(TorchRLModule) + def _forward_train(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + out = self._forward_pass(batch, inference=False) + out[Columns.ACTION_LOGP] = self.get_train_action_dist_cls()( + out[Columns.ACTION_DIST_INPUTS] + ).logp(batch[Columns.ACTIONS]) + out[Columns.VF_PREDS] = self._model_v2.value_function() + if Columns.STATE_IN in batch and Columns.SEQ_LENS in batch: + out[Columns.VF_PREDS] = torch.reshape( + out[Columns.VF_PREDS], [len(batch[Columns.SEQ_LENS]), -1] + ) + return out + + def _forward_pass(self, batch, inference=True): + # Translate states and seq_lens into old API stack formats. + batch = batch.copy() + state_in = batch.pop(Columns.STATE_IN, {}) + state_in = [s for i, s in sorted(state_in.items())] + seq_lens = batch.pop(Columns.SEQ_LENS, None) + + if state_in: + if inference and seq_lens is None: + seq_lens = torch.tensor( + [1.0] * state_in[0].shape[0], device=state_in[0].device + ) + elif not inference: + assert seq_lens is not None + # Perform the actual ModelV2 forward pass. + # A recurrent ModelV2 adds and removes the time-rank itself (whereas in the + # new API stack, the connector pipelines are responsible for doing this) -> + # We have to remove, then re-add the time rank here to make ModelV2 work. + batch = tree.map_structure( + lambda s: torch.reshape(s, [-1] + list(s.shape[2:])), batch + ) + nn_output, state_out = self._model_v2(batch, state_in, seq_lens) + # Put back 1ts time rank into nn-output (inference). + if state_in: + if inference: + nn_output = tree.map_structure( + lambda s: torch.unsqueeze(s, axis=1), nn_output + ) + else: + nn_output = tree.map_structure( + lambda s: torch.reshape(s, [len(seq_lens), -1] + list(s.shape[1:])), + nn_output, + ) + # Interpret the NN output as action logits. + output = {Columns.ACTION_DIST_INPUTS: nn_output} + # Add the `state_out` to the `output`, new API stack style. + if state_out: + output[Columns.STATE_OUT] = {} + for i, o in enumerate(state_out): + output[Columns.STATE_OUT][i] = o + + return output + + @override(ValueFunctionAPI) + def compute_values(self, batch: Dict[str, Any], embeddings: Optional[Any] = None): + self._forward_pass(batch, inference=False) + v_preds = self._model_v2.value_function() + if Columns.STATE_IN in batch and Columns.SEQ_LENS in batch: + v_preds = torch.reshape(v_preds, [len(batch[Columns.SEQ_LENS]), -1]) + return v_preds + + @override(TorchRLModule) + def get_initial_state(self): + """Converts the initial state list of ModelV2 into a dict (new API stack).""" + init_state_list = self._model_v2.get_initial_state() + return dict(enumerate(init_state_list)) + + def _translate_dist_class(self, old_dist_class): + map_ = { + OldTorchCategorical: TorchCategorical, + OldTorchDiagGaussian: TorchDiagGaussian, + OldTorchMultiActionDistribution: TorchMultiDistribution, + OldTorchMultiCategorical: TorchMultiCategorical, + OldTorchSquashedGaussian: TorchSquashedGaussian, + } + if old_dist_class not in map_: + raise ValueError( + f"ModelV2ToRLModule does NOT support {old_dist_class} action " + f"distributions yet!" + ) + + return map_[old_dist_class] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/random_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/random_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c230ab7a4a1c1b2bb9fd04b56137cca25fffb1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/random_rlm.py @@ -0,0 +1,63 @@ +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module import RLModule +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.spaces.space_utils import batch as batch_func + + +class RandomRLModule(RLModule): + @override(RLModule) + def _forward(self, batch, **kwargs): + obs_batch_size = len(tree.flatten(batch[SampleBatch.OBS])[0]) + actions = batch_func( + [self.action_space.sample() for _ in range(obs_batch_size)] + ) + return {SampleBatch.ACTIONS: actions} + + @override(RLModule) + def _forward_train(self, *args, **kwargs): + # RandomRLModule should always be configured as non-trainable. + # To do so, set in your config: + # `config.multi_agent(policies_to_train=[list of ModuleIDs to be trained, + # NOT including the ModuleID of this RLModule])` + raise NotImplementedError("Random RLModule: Should not be trained!") + + def compile(self, *args, **kwargs): + """Dummy method for compatibility with TorchRLModule. + + This is hit when RolloutWorker tries to compile TorchRLModule.""" + pass + + +class StatefulRandomRLModule(RandomRLModule): + """A stateful RLModule that returns STATE_OUT from its forward methods. + + - Implements the `get_initial_state` method (returning a all-zeros dummy state). + - Returns a dummy state under the `Columns.STATE_OUT` from its forward methods. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._internal_state_space = gym.spaces.Box(-1.0, 1.0, (1,)) + + @override(RLModule) + def get_initial_state(self): + return { + "state": np.zeros_like([self._internal_state_space.sample()]), + } + + def _random_forward(self, batch, **kwargs): + batch = super()._random_forward(batch, **kwargs) + batch[Columns.STATE_OUT] = { + "state": batch_func( + [ + self._internal_state_space.sample() + for _ in range(len(batch[Columns.ACTIONS])) + ] + ), + } + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/rock_paper_scissors_heuristic_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/rock_paper_scissors_heuristic_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..644fe01c66536360c914f6c4dce704801bd586e0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/rock_paper_scissors_heuristic_rlm.py @@ -0,0 +1,92 @@ +from collections import defaultdict + +import numpy as np + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override + + +class AlwaysSameHeuristicRLM(RLModule): + """In rock-paper-scissors, always chooses the same action within an episode. + + The first move is random, all the following moves are the same as the first one. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._actions_per_vector_idx = defaultdict(int) + + @override(RLModule) + def _forward_inference(self, batch, **kwargs): + ret = [] + # Note that the obs is the previous move of the opponens (0-2). If it's 3, it + # means that there was no previous move and thus, the episode just started. + for i, obs in enumerate(batch[Columns.OBS]): + if obs == 3: + self._actions_per_vector_idx[i] = np.random.choice([0, 1, 2]) + ret.append(self._actions_per_vector_idx[i]) + return {Columns.ACTIONS: np.array(ret)} + + @override(RLModule) + def _forward_exploration(self, batch, **kwargs): + return self._forward_inference(batch, **kwargs) + + @override(RLModule) + def _forward_train(self, batch, **kwargs): + raise NotImplementedError( + "AlwaysSameHeuristicRLM is not trainable! Make sure you do NOT include it " + "in your `config.multi_agent(policies_to_train={...})` set." + ) + + +class BeatLastHeuristicRLM(RLModule): + """In rock-paper-scissors, always acts such that it beats prev. move of opponent. + + The first move is random. + + For example, after opponent played `rock` (and this policy made a random + move), the next move would be `paper`(to beat `rock`). + """ + + @override(RLModule) + def _forward_inference(self, batch, **kwargs): + """Returns the exact action that would beat the previous action of the opponent. + + The opponent's previous action is the current observation for this agent. + + Both action- and observation spaces are discrete. There are 3 actions available. + (0-2) and 4 observations (0-2 plus 3, where 3 is the observation after the env + reset, when no action has been taken yet). Thereby: + 0=Rock + 1=Paper + 2=Scissors + 3=[after reset] (observation space only) + """ + return { + Columns.ACTIONS: np.array( + [self._pick_single_action(obs) for obs in batch[Columns.OBS]] + ), + } + + @override(RLModule) + def _forward_exploration(self, batch, **kwargs): + return self._forward_inference(batch, **kwargs) + + @override(RLModule) + def _forward_train(self, batch, **kwargs): + raise NotImplementedError( + "BeatLastHeuristicRLM is not trainable! Make sure you do NOT include it in " + "your `config.multi_agent(policies_to_train={...})` set." + ) + + @staticmethod + def _pick_single_action(prev_opponent_obs): + if prev_opponent_obs == 0: + return 1 + elif prev_opponent_obs == 1: + return 2 + elif prev_opponent_obs == 2: + return 0 + else: + return np.random.choice([0, 1, 2]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/tiny_atari_cnn_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/tiny_atari_cnn_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..eb2e4e39b56a6f3963a247cf1969f92309970269 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/tiny_atari_cnn_rlm.py @@ -0,0 +1,194 @@ +from typing import Any, Dict, Optional + +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.utils import make_target_network +from ray.rllib.core.rl_module.apis import ( + TargetNetworkAPI, + ValueFunctionAPI, + TARGET_NETWORK_ACTION_DIST_INPUTS, +) +from ray.rllib.core.rl_module.torch import TorchRLModule +from ray.rllib.models.torch.misc import ( + normc_initializer, + same_padding, + valid_padding, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +class TinyAtariCNN(TorchRLModule, ValueFunctionAPI, TargetNetworkAPI): + """A tiny CNN stack for fast-learning of Atari envs. + + The architecture here is the exact same as the one used by the old API stack as + CNN default ModelV2. + + We stack 3 CNN layers based on the config, then a 4th one with linear activation + and n 1x1 filters, where n is the number of actions in the (discrete) action space. + Simple reshaping (no flattening or extra linear layers necessary) lead to the + action logits, which can directly be used inside a distribution or loss. + + .. testcode:: + + import numpy as np + import gymnasium as gym + + my_net = TinyAtariCNN( + observation_space=gym.spaces.Box(-1.0, 1.0, (42, 42, 4), np.float32), + action_space=gym.spaces.Discrete(4), + ) + + B = 10 + w = 42 + h = 42 + c = 4 + data = torch.from_numpy( + np.random.random_sample(size=(B, w, h, c)).astype(np.float32) + ) + print(my_net.forward_inference({"obs": data})) + print(my_net.forward_exploration({"obs": data})) + print(my_net.forward_train({"obs": data})) + + num_all_params = sum(int(np.prod(p.size())) for p in my_net.parameters()) + print(f"num params = {num_all_params}") + """ + + @override(TorchRLModule) + def setup(self): + """Use this method to create all the model components that you require. + + Feel free to access the following useful properties in this class: + - `self.model_config`: The config dict for this RLModule class, + which should contain flxeible settings, for example: {"hiddens": [256, 256]}. + - `self.observation|action_space`: The observation and action space that + this RLModule is subject to. Note that the observation space might not be the + exact space from your env, but that it might have already gone through + preprocessing through a connector pipeline (for example, flattening, + frame-stacking, mean/std-filtering, etc..). + """ + # Get the CNN stack config from our RLModuleConfig's (self.config) + # `model_config` property: + conv_filters = self.model_config.get("conv_filters") + # Default CNN stack with 3 layers: + if conv_filters is None: + conv_filters = [ + [16, 4, 2, "same"], # num filters, kernel wxh, stride wxh, padding type + [32, 4, 2, "same"], + [256, 11, 1, "valid"], + ] + + # Build the CNN layers. + layers = [] + + # Add user-specified hidden convolutional layers first + width, height, in_depth = self.observation_space.shape + in_size = [width, height] + for filter_specs in conv_filters: + if len(filter_specs) == 4: + out_depth, kernel_size, strides, padding = filter_specs + else: + out_depth, kernel_size, strides = filter_specs + padding = "same" + + # Pad like in tensorflow's SAME mode. + if padding == "same": + padding_size, out_size = same_padding(in_size, kernel_size, strides) + layers.append(nn.ZeroPad2d(padding_size)) + # No actual padding is performed for "valid" mode, but we will still + # compute the output size (input for the next layer). + else: + out_size = valid_padding(in_size, kernel_size, strides) + + layer = nn.Conv2d(in_depth, out_depth, kernel_size, strides, bias=True) + # Initialize CNN layer kernel and bias. + nn.init.xavier_uniform_(layer.weight) + nn.init.zeros_(layer.bias) + layers.append(layer) + # Activation. + layers.append(nn.ReLU()) + + in_size = out_size + in_depth = out_depth + + self._base_cnn_stack = nn.Sequential(*layers) + + # Add the final CNN 1x1 layer with num_filters == num_actions to be reshaped to + # yield the logits (no flattening, no additional linear layers required). + _final_conv = nn.Conv2d(in_depth, self.action_space.n, 1, 1, bias=True) + nn.init.xavier_uniform_(_final_conv.weight) + nn.init.zeros_(_final_conv.bias) + self._logits = nn.Sequential( + nn.ZeroPad2d(same_padding(in_size, 1, 1)[0]), _final_conv + ) + + self._values = nn.Linear(in_depth, 1) + # Mimick old API stack behavior of initializing the value function with `normc` + # std=0.01. + normc_initializer(0.01)(self._values.weight) + + @override(TorchRLModule) + def _forward(self, batch, **kwargs): + # Compute the basic 1D feature tensor (inputs to policy- and value-heads). + _, logits = self._compute_embeddings_and_logits(batch) + # Return features and logits as ACTION_DIST_INPUTS (categorical distribution). + return { + Columns.ACTION_DIST_INPUTS: logits, + } + + @override(TorchRLModule) + def _forward_train(self, batch, **kwargs): + # Compute the basic 1D feature tensor (inputs to policy- and value-heads). + embeddings, logits = self._compute_embeddings_and_logits(batch) + # Return features and logits as ACTION_DIST_INPUTS (categorical distribution). + return { + Columns.ACTION_DIST_INPUTS: logits, + Columns.EMBEDDINGS: embeddings, + } + + # We implement this RLModule as a TargetNetworkAPI RLModule, so it can be used + # by the APPO algorithm. + @override(TargetNetworkAPI) + def make_target_networks(self) -> None: + self._target_base_cnn_stack = make_target_network(self._base_cnn_stack) + self._target_logits = make_target_network(self._logits) + + @override(TargetNetworkAPI) + def get_target_network_pairs(self): + return [ + (self._base_cnn_stack, self._target_base_cnn_stack), + (self._logits, self._target_logits), + ] + + @override(TargetNetworkAPI) + def forward_target(self, batch, **kw): + obs = batch[Columns.OBS].permute(0, 3, 1, 2) + embeddings = self._target_base_cnn_stack(obs) + logits = self._target_logits(embeddings) + return {TARGET_NETWORK_ACTION_DIST_INPUTS: torch.squeeze(logits, dim=[-1, -2])} + + # We implement this RLModule as a ValueFunctionAPI RLModule, so it can be used + # by value-based methods like PPO or IMPALA. + @override(ValueFunctionAPI) + def compute_values( + self, + batch: Dict[str, Any], + embeddings: Optional[Any] = None, + ) -> TensorType: + # Features not provided -> We need to compute them first. + if embeddings is None: + obs = batch[Columns.OBS] + embeddings = self._base_cnn_stack(obs.permute(0, 3, 1, 2)) + embeddings = torch.squeeze(embeddings, dim=[-1, -2]) + return self._values(embeddings).squeeze(-1) + + def _compute_embeddings_and_logits(self, batch): + obs = batch[Columns.OBS].permute(0, 3, 1, 2) + embeddings = self._base_cnn_stack(obs) + logits = self._logits(embeddings) + return ( + torch.squeeze(embeddings, dim=[-1, -2]), + torch.squeeze(logits, dim=[-1, -2]), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/vpg_torch_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/vpg_torch_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3216c9d73a14cd08840e51c1d68b3f01739e6f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/vpg_torch_rlm.py @@ -0,0 +1,59 @@ +import torch + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.torch import TorchRLModule + + +class VPGTorchRLModule(TorchRLModule): + """A simple VPG (vanilla policy gradient)-style RLModule for testing purposes. + + Use this as a minimum, bare-bones example implementation of a custom TorchRLModule. + """ + + def setup(self): + """Use this method to create all the model components that you require. + + Feel free to access the following useful properties in this class: + - `self.model_config`: The config dict for this RLModule class, + which should contain flexible settings, for example: {"hiddens": [256, 256]}. + - `self.observation|action_space`: The observation and action space that + this RLModule is subject to. Note that the observation space might not be the + exact space from your env, but that it might have already gone through + preprocessing through a connector pipeline (for example, flattening, + frame-stacking, mean/std-filtering, etc..). + - `self.inference_only`: If True, this model should be built only for inference + purposes, in which case you may want to exclude any components that are not used + for computing actions, for example a value function branch. + """ + input_dim = self.observation_space.shape[0] + hidden_dim = self.model_config["hidden_dim"] + output_dim = self.action_space.n + + self._policy_net = torch.nn.Sequential( + torch.nn.Linear(input_dim, hidden_dim), + torch.nn.ReLU(), + torch.nn.Linear(hidden_dim, output_dim), + ) + + def _forward(self, batch, **kwargs): + # Push the observations from the batch through our `self._policy_net`. + action_logits = self._policy_net(batch[Columns.OBS]) + # Return parameters for the (default) action distribution, which is + # `TorchCategorical` (due to our action space being `gym.spaces.Discrete`). + return {Columns.ACTION_DIST_INPUTS: action_logits} + + # If you need more granularity between the different forward behaviors during + # the different phases of the module's lifecycle, implement three different + # forward methods. Thereby, it is recommended to put the inference and + # exploration versions inside a `with torch.no_grad()` context for better + # performance. + # def _forward_train(self, batch): + # ... + # + # def _forward_inference(self, batch): + # with torch.no_grad(): + # return self._forward_train(batch) + # + # def _forward_exploration(self, batch): + # with torch.no_grad(): + # return self._forward_train(batch) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/vpg_using_shared_encoder_rlm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/vpg_using_shared_encoder_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..05a350de5ff0c89a89b032214e941413c75e4f12 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/classes/vpg_using_shared_encoder_rlm.py @@ -0,0 +1,171 @@ +import torch + +from ray.rllib.core import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.core.rl_module.torch.torch_rl_module import TorchRLModule + + +SHARED_ENCODER_ID = "shared_encoder" + + +# __sphinx_doc_policy_begin__ +class VPGPolicyAfterSharedEncoder(TorchRLModule): + """A VPG (vanilla pol. gradient)-style RLModule using a shared encoder. + # __sphinx_doc_policy_end__ + + The shared encoder RLModule must be held by the same MultiRLModule, under which + this RLModule resides. The shared encoder's forward is called before this + RLModule's forward and returns the embeddings under the "encoder_embeddings" + key. + # __sphinx_doc_policy_2_begin__ + """ + + def setup(self): + super().setup() + + # Incoming feature dim from the shared encoder. + embedding_dim = self.model_config["embedding_dim"] + hidden_dim = self.model_config["hidden_dim"] + + self._pi_head = torch.nn.Sequential( + torch.nn.Linear(embedding_dim, hidden_dim), + torch.nn.ReLU(), + torch.nn.Linear(hidden_dim, self.action_space.n), + ) + + def _forward(self, batch, **kwargs): + # Embeddings can be found in the batch under the "encoder_embeddings" key. + embeddings = batch["encoder_embeddings"] + logits = self._pi_head(embeddings) + return {Columns.ACTION_DIST_INPUTS: logits} + + +# __sphinx_doc_policy_2_end__ + + +# __sphinx_doc_mrlm_begin__ +class VPGMultiRLModuleWithSharedEncoder(MultiRLModule): + """VPG (vanilla pol. gradient)-style MultiRLModule handling a shared encoder. + # __sphinx_doc_mrlm_end__ + + This MultiRLModule needs to be configured appropriately as follows: + + .. testcode:: + + # __sphinx_doc_how_to_run_begin__ + import gymnasium as gym + from ray.rllib.algorithms.ppo import PPOConfig + from ray.rllib.core import MultiRLModuleSpec, RLModuleSpec + from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole + + single_agent_env = gym.make("CartPole-v1") + + EMBEDDING_DIM = 64 # encoder output dim + + config = ( + PPOConfig() + .environment(MultiAgentCartPole, env_config={"num_agents": 2}) + .multi_agent( + # Declare the two policies trained. + policies={"p0", "p1"}, + # Agent IDs of `MultiAgentCartPole` are 0 and 1. They are mapped to + # the two policies with ModuleIDs "p0" and "p1", respectively. + policy_mapping_fn=lambda agent_id, episode, **kw: f"p{agent_id}" + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + # Shared encoder. + SHARED_ENCODER_ID: RLModuleSpec( + module_class=SharedEncoder, + model_config={"embedding_dim": EMBEDDING_DIM}, + observation_space=single_agent_env.observation_space, + action_space=single_agent_env.action_space, + ), + # Large policy net. + "p0": RLModuleSpec( + module_class=VPGPolicyAfterSharedEncoder, + model_config={ + "embedding_dim": EMBEDDING_DIM, + "hidden_dim": 1024, + }, + ), + # Small policy net. + "p1": RLModuleSpec( + module_class=VPGPolicyAfterSharedEncoder, + model_config={ + "embedding_dim": EMBEDDING_DIM, + "hidden_dim": 64, + }, + ), + }, + ), + ) + ) + algo = config.build() + print(algo.get_module("p0")) + # __sphinx_doc_how_to_run_end__ + + Also note that in order to learn properly, a special, multi-agent Learner + accounting for the shared encoder must be setup. This Learner should have only + one optimizer (used to train all submodules: encoder and the n policy nets) in + order to not destabilize learning. The latter would happen if more than one + optimizer would try to alternatingly optimize the same shared encoder submodule. + # __sphinx_doc_mrlm_2_begin__ + """ + + def setup(self): + # Call the super's setup(). + super().setup() + + # Assert, we have the shared encoder submodule. + assert ( + SHARED_ENCODER_ID in self._rl_modules + and isinstance(self._rl_modules[SHARED_ENCODER_ID], SharedEncoder) + and len(self._rl_modules) > 1 + ) + # Assign the encoder to a convenience attribute. + self.encoder = self._rl_modules[SHARED_ENCODER_ID] + + def _forward(self, batch, **kwargs): + # Collect our policies' outputs in this dict. + outputs = {} + + # Loop through the policy nets (through the given batch's keys). + for policy_id, policy_batch in batch.items(): + rl_module = self._rl_modules[policy_id] + + # Pass policy's observations through shared encoder to get the features for + # this policy. + policy_batch["encoder_embeddings"] = self.encoder._forward(batch[policy_id]) + + # Pass the policy's embeddings through the policy net. + outputs[policy_id] = rl_module._forward(batch[policy_id], **kwargs) + + return outputs + + +# __sphinx_doc_mrlm_2_end__ + + +# __sphinx_doc_encoder_begin__ +class SharedEncoder(TorchRLModule): + """A shared encoder that can be used with `VPGMultiRLModuleWithSharedEncoder`.""" + + def setup(self): + super().setup() + + input_dim = self.observation_space.shape[0] + embedding_dim = self.model_config["embedding_dim"] + + # A very simple encoder network. + self._net = torch.nn.Sequential( + torch.nn.Linear(input_dim, embedding_dim), + ) + + def _forward(self, batch, **kwargs): + # Pass observations through the net and return outputs. + return {"encoder_embeddings": self._net(batch[Columns.OBS])} + + +# __sphinx_doc_encoder_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/custom_cnn_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/custom_cnn_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..361938c0a16c0fdb9e4569ffc4a4f4cabfe97246 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/custom_cnn_rl_module.py @@ -0,0 +1,115 @@ +"""Example of implementing and configuring a custom (torch) CNN containing RLModule. + +This example: + - demonstrates how you can subclass the TorchRLModule base class and set up your + own CNN-stack architecture by overriding the `setup()` method. + - shows how to override the 3 forward methods: `_forward_inference()`, + `_forward_exploration()`, and `forward_train()` to implement your own custom forward + logic(s). You will also learn, when each of these 3 methods is called by RLlib or + the users of your RLModule. + - shows how you then configure an RLlib Algorithm such that it uses your custom + RLModule (instead of a default RLModule). + +We implement a tiny CNN stack here, the exact same one that is used by the old API +stack as default CNN net. It comprises 4 convolutional layers, the last of which +ends in a 1x1 filter size and the number of filters exactly matches the number of +discrete actions (logits). This way, the (non-activated) output of the last layer only +needs to be reshaped in order to receive the policy's logit outputs. No flattening +or additional dense layer required. + +The network is then used in a fast ALE/Pong-v5 experiment. + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see the following output (during the experiment) in your console: + +Number of trials: 1/1 (1 RUNNING) ++---------------------+----------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+----------+----------------+--------+------------------+ +| PPO_env_82b44_00000 | RUNNING | 127.0.0.1:9718 | 1 | 98.3585 | ++---------------------+----------+----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| num_env_steps_sample | num_env_steps_traine | num_episodes_lifetim | +| d_lifetime | d_lifetime | e | +|------------------------+------------------------+------------------------| +| 4000 | 4000 | 4 | ++------------------------+------------------------+------------------------+ +""" +import gymnasium as gym + +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.wrappers.atari_wrappers import wrap_atari_for_new_api_stack +from ray.rllib.examples.rl_modules.classes.tiny_atari_cnn_rlm import TinyAtariCNN +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +parser = add_rllib_example_script_args(default_iters=100, default_timesteps=600000) +parser.set_defaults( + env="ale_py:ALE/Pong-v5", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + register_env( + "env", + lambda cfg: wrap_atari_for_new_api_stack( + gym.make(args.env, **cfg), + dim=42, # <- need images to be "tiny" for our custom model + framestack=4, + ), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + env="env", + env_config=dict( + frameskip=1, + full_action_space=False, + repeat_action_probability=0.0, + ), + ) + .rl_module( + # Plug-in our custom RLModule class. + rl_module_spec=RLModuleSpec( + module_class=TinyAtariCNN, + # Feel free to specify your own `model_config` settings below. + # The `model_config` defined here will be available inside your + # custom RLModule class through the `self.model_config` + # property. + model_config={ + "conv_filters": [ + # num filters, kernel wxh, stride wxh, padding type + [16, 4, 2, "same"], + [32, 4, 2, "same"], + [256, 11, 1, "valid"], + ], + }, + ), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/custom_lstm_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/custom_lstm_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..9d7975cd473266dc6d9755543911b97ca68f1020 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/custom_lstm_rl_module.py @@ -0,0 +1,101 @@ +"""Example of implementing and configuring a custom (torch) LSTM containing RLModule. + +This example: + - demonstrates how you can subclass the TorchRLModule base class and set up your + own LSTM-containing NN architecture by overriding the `setup()` method. + - shows how to override the 3 forward methods: `_forward_inference()`, + `_forward_exploration()`, and `forward_train()` to implement your own custom forward + logic(s), including how to handle STATE in- and outputs to and from these calls. + - explains when each of these 3 methods is called by RLlib or the users of your + RLModule. + - shows how you then configure an RLlib Algorithm such that it uses your custom + RLModule (instead of a default RLModule). + +We implement a simple LSTM layer here, followed by a series of Linear layers. +After the last Linear layer, we add fork of 2 Linear (non-activated) layers, one for the +action logits and one for the value function output. + +We test the LSTM containing RLModule on the StatelessCartPole environment, a variant +of CartPole that is non-Markovian (partially observable). Only an RNN-network can learn +a decent policy in this environment due to the lack of any velocity information. By +looking at one observation, one cannot know whether the cart is currently moving left or +right and whether the pole is currently moving up or down). + + +How to run this script +---------------------- +`python [script file name].py` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should see the following output (during the experiment) in your console: + +""" +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.envs.classes.stateless_cartpole import StatelessCartPole +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentStatelessCartPole +from ray.rllib.examples.rl_modules.classes.lstm_containing_rlm import ( + LSTMContainingRLModule, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +parser = add_rllib_example_script_args( + default_reward=300.0, + default_timesteps=2000000, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + if args.num_agents == 0: + register_env("env", lambda cfg: StatelessCartPole()) + else: + register_env("env", lambda cfg: MultiAgentStatelessCartPole(cfg)) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + env="env", + env_config={"num_agents": args.num_agents}, + ) + .training( + train_batch_size_per_learner=1024, + num_epochs=6, + lr=0.0009, + vf_loss_coeff=0.001, + entropy_coeff=0.0, + ) + .rl_module( + # Plug-in our custom RLModule class. + rl_module_spec=RLModuleSpec( + module_class=LSTMContainingRLModule, + # Feel free to specify your own `model_config` settings below. + # The `model_config` defined here will be available inside your + # custom RLModule class through the `self.model_config` + # property. + model_config={ + "lstm_cell_size": 256, + "dense_layers": [256, 256], + "max_seq_len": 20, + }, + ), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/migrate_modelv2_to_new_api_stack_by_config.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/migrate_modelv2_to_new_api_stack_by_config.py new file mode 100644 index 0000000000000000000000000000000000000000..21b68184051f7be95d5ea06ca80ec1032cbd998c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/migrate_modelv2_to_new_api_stack_by_config.py @@ -0,0 +1,77 @@ +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core import DEFAULT_POLICY_ID +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.rl_modules.classes.modelv2_to_rlm import ModelV2ToRLModule +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, +) + + +if __name__ == "__main__": + # Configure an old stack default ModelV2. + config_old_stack = ( + PPOConfig() + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .environment("CartPole-v1") + .training( + lr=0.0003, + num_sgd_iter=6, + vf_loss_coeff=0.01, + # Change the ModelV2 settings a bit. + model={ + "fcnet_hiddens": [32], + "fcnet_activation": "linear", + "use_lstm": True, + "vf_share_layers": True, + }, + ) + ) + + # Training with the (configured and wrapped) ModelV2. + + # We change the original (old API stack) `config` into a new API stack one: + config_new_stack = ( + config_old_stack.copy(copy_frozen=False) + .api_stack( + enable_rl_module_and_learner=True, + enable_env_runner_and_connector_v2=True, + ) + .rl_module( + rl_module_spec=RLModuleSpec( + module_class=ModelV2ToRLModule, + model_config={ + "policy_id": DEFAULT_POLICY_ID, + "old_api_stack_algo_config": config_old_stack, + "max_seq_len": 20, + }, + ), + ) + ) + + # Build the new stack algo. + algo_new_stack = config_new_stack.build() + + # Train until a higher return. + min_return_new_stack = 350.0 + results = None + passed = False + for i in range(100): + results = algo_new_stack.train() + print(results) + if results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= min_return_new_stack: + print( + f"Reached episode return of {min_return_new_stack} -> stopping " + "new API stack training." + ) + passed = True + break + + if not passed: + raise ValueError( + "Continuing training on the new stack did not succeed! Last return: " + f"{results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]}" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6ef471cb9552e6e1307c60c73db65060f759af --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.py @@ -0,0 +1,118 @@ +import pathlib + +import gymnasium as gym +import numpy as np +import torch + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.rl_modules.classes.modelv2_to_rlm import ModelV2ToRLModule +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, +) +from ray.rllib.utils.spaces.space_utils import batch + + +if __name__ == "__main__": + # Configure and train an old stack default ModelV2. + config = ( + PPOConfig() + # Old API stack. + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .environment("CartPole-v1") + .training( + lr=0.0003, + num_epochs=6, + vf_loss_coeff=0.01, + ) + ) + algo_old_stack = config.build() + + min_return_old_stack = 100.0 + while True: + results = algo_old_stack.train() + print(results) + if results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= min_return_old_stack: + print( + f"Reached episode return of {min_return_old_stack} -> stopping " + "old API stack training." + ) + break + + checkpoint = algo_old_stack.save() + policy_path = ( + pathlib.Path(checkpoint.checkpoint.path) / "policies" / "default_policy" + ) + assert policy_path.is_dir() + algo_old_stack.stop() + + print("done") + + # Move the old API stack (trained) ModelV2 into the new API stack's RLModule. + # Run a simple CartPole inference experiment. + env = gym.make("CartPole-v1", render_mode="human") + rl_module = ModelV2ToRLModule( + observation_space=env.observation_space, + action_space=env.action_space, + model_config={"policy_checkpoint_dir": policy_path}, + ) + + obs, _ = env.reset() + env.render() + done = False + episode_return = 0.0 + while not done: + output = rl_module.forward_inference({"obs": torch.from_numpy(batch([obs]))}) + action_logits = output["action_dist_inputs"].detach().numpy()[0] + action = np.argmax(action_logits) + obs, reward, terminated, truncated, _ = env.step(action) + done = terminated or truncated + episode_return += reward + env.render() + + print(f"Ran episode with trained ModelV2: return={episode_return}") + + # Continue training with the (checkpointed) ModelV2. + + # We change the original (old API stack) `config` into a new API stack one: + config = config.api_stack( + enable_rl_module_and_learner=True, + enable_env_runner_and_connector_v2=True, + ).rl_module( + rl_module_spec=RLModuleSpec( + module_class=ModelV2ToRLModule, + model_config={"policy_checkpoint_dir": policy_path}, + ), + ) + + # Build the new stack algo. + algo_new_stack = config.build() + + # Train until a higher return. + min_return_new_stack = 450.0 + passed = False + for i in range(50): + results = algo_new_stack.train() + print(results) + # Make sure that the model's weights from the old API stack training + # were properly transferred to the new API RLModule wrapper. Thus, even + # after only one iteration of new stack training, we already expect the + # return to be higher than it was at the end of the old stack training. + assert results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= min_return_old_stack + if results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= min_return_new_stack: + print( + f"Reached episode return of {min_return_new_stack} -> stopping " + "new API stack training." + ) + passed = True + break + + if not passed: + raise ValueError( + "Continuing training on the new stack did not succeed! Last return: " + f"{results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]}" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/pretraining_single_agent_training_multi_agent.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/pretraining_single_agent_training_multi_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..9c009926a9f8f9d8ce95b0ee946c64447500728f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/rl_modules/pretraining_single_agent_training_multi_agent.py @@ -0,0 +1,194 @@ +"""Example of running a single-agent pre-training followed with a multi-agent training. + +This examples `num_agents` agents each of them with its own `RLModule` that defines its +policy. The first agent is pre-trained using a single-agent PPO algorithm. All agents +are trained together in the main training run using a multi-agent PPO algorithm where +the pre-trained module is used for the first agent. + +The environment is MultiAgentCartPole, in which there are n agents both policies. + +How to run this script +---------------------- +`python [script file name].py --num-agents=2` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that the single-agent policy is first trained until +the specified `--stop-reward-pretraining` value. For example, with the command line: +`--num-agents=2 --stop-reward-pretraining=250.0 --stop-reward=250.0 +--stop-iters=3 --as-test`, you should get something like: ++-----------------------+------------+------+----------------+---------------------+ +| Trial name | status | iter | total time (s) | episode_return_mean | +| | | | | | +|-----------------------+------------+------+----------------+---------------------+ +| PPO_CartPole-v1_00000 | TERMINATED | 16 | 25.6009 | 256.2 | ++-----------------------+------------+------+----------------+---------------------+ + +Then, in the second experiment, where we run in a multi-agent setup with two policies +("p0" from the single-agent checkpoint and "p1" randomly initialized), you can see that +only "p0" immediately (after 1 iteration) reaches the same episode return as at the end +of pretraining: ++----------------------------+------------+--------+------------------+------+ +| Trial name | status | iter | total time (s) | ts | +|----------------------------+------------+--------+------------------+------+ +| PPO_multi-cart_6274d_00000 | TERMINATED | 1 | 2.71681 | 4000 | ++----------------------------+------------+--------+------------------+------+ ++-------------------+-------------+-------------+ +| combined return | return p0 | return p1 | +|-------------------+-------------|-------------+ +| 451.625 | 433.125 | 18.5 | ++-------------------+-------------+-------------+ +""" +from pathlib import Path + +import gymnasium as gym + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.algorithms.ppo.ppo_catalog import PPOCatalog +from ray.rllib.algorithms.ppo.torch.ppo_torch_rl_module import PPOTorchRLModule +from ray.rllib.core import ( + COMPONENT_LEARNER, + COMPONENT_LEARNER_GROUP, + COMPONENT_RL_MODULE, + DEFAULT_MODULE_ID, +) +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune import register_env + +# Read in common example script command line arguments. +parser = add_rllib_example_script_args( + # Use less training steps for the main training run. + default_timesteps=50000, + default_reward=200.0, + default_iters=20, +) +parser.set_defaults( + checkpoint_freq=1, + checkpoint_at_end=True, +) +parser.add_argument( + "--stop-reward-pretraining", + type=float, + default=250.0, + help="The min. episode return to reach during pre-training.", +) + + +if __name__ == "__main__": + + # Parse the command line arguments. + args = parser.parse_args() + + # Ensure that the user has set the number of agents. + if args.num_agents == 0: + raise ValueError( + "This pre-training example script requires at least 1 agent. " + "Try setting the command line argument `--num-agents` to the " + "number of agents you want to use." + ) + + # Store the user's stopping criteria for the later training run. + stop_iters = args.stop_iters + stop_timesteps = args.stop_timesteps + stop_reward = args.stop_reward + num_agents = args.num_agents + as_test = args.as_test + + # Override these criteria for the pre-training run. + args.stop_iters = 10000 + args.stop_timesteps = 100000000 + args.stop_reward = args.stop_reward_pretraining + args.num_agents = 0 + args.as_test = False + + # Define out pre-training single-agent algorithm. We will use the same module + # configuration for the pre-training and the training. + config = ( + PPOConfig() + .environment("CartPole-v1") + .rl_module( + # Use a different number of hidden units for the pre-trained module. + model_config=DefaultModelConfig(fcnet_hiddens=[64]), + ) + ) + + # Run the pre-training. + results = run_rllib_example_script_experiment(config, args, keep_ray_up=True) + # Get the checkpoint path. + module_chkpt_path = ( + Path(results.get_best_result().checkpoint.path) + / COMPONENT_LEARNER_GROUP + / COMPONENT_LEARNER + / COMPONENT_RL_MODULE + / DEFAULT_MODULE_ID + ) + assert module_chkpt_path.is_dir() + + # Restore the user's stopping criteria for the training run. + args.stop_iters = stop_iters + args.stop_timesteps = stop_timesteps + args.stop_reward = stop_reward + args.num_agents = num_agents + args.as_test = as_test + + # Create a new MultiRLModule using the pre-trained module for policy 0. + env = gym.make("CartPole-v1") + module_specs = {} + module_class = PPOTorchRLModule + for i in range(args.num_agents): + module_specs[f"p{i}"] = RLModuleSpec( + module_class=PPOTorchRLModule, + observation_space=env.observation_space, + action_space=env.action_space, + model_config=DefaultModelConfig(fcnet_hiddens=[32]), + catalog_class=PPOCatalog, + ) + + # Swap in the pre-trained module for policy 0. + module_specs["p0"] = RLModuleSpec( + module_class=PPOTorchRLModule, + observation_space=env.observation_space, + action_space=env.action_space, + model_config=DefaultModelConfig(fcnet_hiddens=[64]), + catalog_class=PPOCatalog, + # Note, we load here the module directly from the checkpoint. + load_state_path=module_chkpt_path, + ) + multi_rl_module_spec = MultiRLModuleSpec(rl_module_specs=module_specs) + + # Register our environment with tune if we use multiple agents. + register_env( + "multi-cart", + lambda _: MultiAgentCartPole(config={"num_agents": args.num_agents}), + ) + + # Configure the main (multi-agent) training run. + config = ( + PPOConfig() + .environment("multi-cart") + .multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, eps, **kw: f"p{aid}", + ) + .rl_module(rl_module_spec=multi_rl_module_spec) + ) + + # Run the main training run. + run_rllib_example_script_experiment(config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00f405a38105d61c2a78c46f65c6b5242f07922c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/learner_thread.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/learner_thread.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5b91dc2d837e57cf2787121c6d149bc31af6dd8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/learner_thread.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/minibatch_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/minibatch_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a35b7ab2319b146ce80ffde42d92b58b2e127e40 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/minibatch_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/multi_gpu_learner_thread.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/multi_gpu_learner_thread.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f91ab486ea2caf4925c50c314f2b18e188c1a4b6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/multi_gpu_learner_thread.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/replay_ops.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/replay_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..027c7613bd2d318698ae3a264c11d41d96d12086 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/replay_ops.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/rollout_ops.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/rollout_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b0785457c52c9dc9321b4b9aba625ba13d70d8b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/rollout_ops.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/segment_tree.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/segment_tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..899372ed7e6ad0c891694eb2ee77844742a75093 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/segment_tree.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/train_ops.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/train_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fb37282fcac6eec9e51936b21140706314d7cd3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__pycache__/train_ops.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ada9f7acbab10c3c6a9b2af82cf3bc96cdbf1df9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/__pycache__/mixin_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/__pycache__/mixin_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cacdefba008a74624229ed3d7b9ac89fc7568340 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/__pycache__/mixin_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/mixin_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/mixin_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..6f897ac06f553d813d844b890914550ff08e0fc1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/buffers/mixin_replay_buffer.py @@ -0,0 +1,173 @@ +import collections +import platform +import random +from typing import Optional + +from ray.util.timer import _Timer +from ray.rllib.execution.replay_ops import SimpleReplayBuffer +from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID, concat_samples +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.replay_buffers.multi_agent_replay_buffer import ReplayMode +from ray.rllib.utils.replay_buffers.replay_buffer import _ALL_POLICIES +from ray.rllib.utils.typing import PolicyID, SampleBatchType + + +@OldAPIStack +class MixInMultiAgentReplayBuffer: + """This buffer adds replayed samples to a stream of new experiences. + + - Any newly added batch (`add()`) is immediately returned upon + the next `replay` call (close to on-policy) as well as being moved + into the buffer. + - Additionally, a certain number of old samples is mixed into the + returned sample according to a given "replay ratio". + - If >1 calls to `add()` are made without any `replay()` calls + in between, all newly added batches are returned (plus some older samples + according to the "replay ratio"). + + .. testcode:: + + from ray.rllib.execution.buffers.mixin_replay_buffer import ( + MixInMultiAgentReplayBuffer) + from ray.rllib.policy.sample_batch import SampleBatch + # replay ratio 0.66 (2/3 replayed, 1/3 new samples): + buffer = MixInMultiAgentReplayBuffer(capacity=100, + replay_ratio=0.66) + A, B, C = (SampleBatch({"obs": [1]}), SampleBatch({"obs": [2]}), + SampleBatch({"obs": [3]})) + buffer.add(A) + buffer.add(B) + buffer.add(B) + print(buffer.replay()["obs"]) + + .. testoutput:: + :hide: + + ... + """ + + def __init__( + self, + capacity: int, + replay_ratio: float, + replay_mode: ReplayMode = ReplayMode.INDEPENDENT, + ): + """Initializes MixInReplay instance. + + Args: + capacity: Number of batches to store in total. + replay_ratio: Ratio of replayed samples in the returned + batches. E.g. a ratio of 0.0 means only return new samples + (no replay), a ratio of 0.5 means always return newest sample + plus one old one (1:1), a ratio of 0.66 means always return + the newest sample plus 2 old (replayed) ones (1:2), etc... + """ + self.capacity = capacity + self.replay_ratio = replay_ratio + self.replay_proportion = None + if self.replay_ratio != 1.0: + self.replay_proportion = self.replay_ratio / (1.0 - self.replay_ratio) + + if replay_mode in ["lockstep", ReplayMode.LOCKSTEP]: + self.replay_mode = ReplayMode.LOCKSTEP + elif replay_mode in ["independent", ReplayMode.INDEPENDENT]: + self.replay_mode = ReplayMode.INDEPENDENT + else: + raise ValueError("Unsupported replay mode: {}".format(replay_mode)) + + def new_buffer(): + return SimpleReplayBuffer(num_slots=capacity) + + self.replay_buffers = collections.defaultdict(new_buffer) + + # Metrics. + self.add_batch_timer = _Timer() + self.replay_timer = _Timer() + self.update_priorities_timer = _Timer() + + # Added timesteps over lifetime. + self.num_added = 0 + + # Last added batch(es). + self.last_added_batches = collections.defaultdict(list) + + def add(self, batch: SampleBatchType) -> None: + """Adds a batch to the appropriate policy's replay buffer. + + Turns the batch into a MultiAgentBatch of the DEFAULT_POLICY_ID if + it is not a MultiAgentBatch. Subsequently adds the individual policy + batches to the storage. + + Args: + batch: The batch to be added. + """ + # Make a copy so the replay buffer doesn't pin plasma memory. + batch = batch.copy() + batch = batch.as_multi_agent() + + with self.add_batch_timer: + if self.replay_mode == ReplayMode.LOCKSTEP: + # Lockstep mode: Store under _ALL_POLICIES key (we will always + # only sample from all policies at the same time). + # This means storing a MultiAgentBatch to the underlying buffer + self.replay_buffers[_ALL_POLICIES].add_batch(batch) + self.last_added_batches[_ALL_POLICIES].append(batch) + else: + # Store independent SampleBatches + for policy_id, sample_batch in batch.policy_batches.items(): + self.replay_buffers[policy_id].add_batch(sample_batch) + self.last_added_batches[policy_id].append(sample_batch) + + self.num_added += batch.count + + def replay( + self, policy_id: PolicyID = DEFAULT_POLICY_ID + ) -> Optional[SampleBatchType]: + if self.replay_mode == ReplayMode.LOCKSTEP and policy_id != _ALL_POLICIES: + raise ValueError( + "Trying to sample from single policy's buffer in lockstep " + "mode. In lockstep mode, all policies' experiences are " + "sampled from a single replay buffer which is accessed " + "with the policy id `{}`".format(_ALL_POLICIES) + ) + + buffer = self.replay_buffers[policy_id] + # Return None, if: + # - Buffer empty or + # - `replay_ratio` < 1.0 (new samples required in returned batch) + # and no new samples to mix with replayed ones. + if len(buffer) == 0 or ( + len(self.last_added_batches[policy_id]) == 0 and self.replay_ratio < 1.0 + ): + return None + + # Mix buffer's last added batches with older replayed batches. + with self.replay_timer: + output_batches = self.last_added_batches[policy_id] + self.last_added_batches[policy_id] = [] + + # No replay desired -> Return here. + if self.replay_ratio == 0.0: + return concat_samples(output_batches) + # Only replay desired -> Return a (replayed) sample from the + # buffer. + elif self.replay_ratio == 1.0: + return buffer.replay() + + # Replay ratio = old / [old + new] + # Replay proportion: old / new + num_new = len(output_batches) + replay_proportion = self.replay_proportion + while random.random() < num_new * replay_proportion: + replay_proportion -= 1 + output_batches.append(buffer.replay()) + return concat_samples(output_batches) + + def get_host(self) -> str: + """Returns the computer's network name. + + Returns: + The computer's networks name or an empty string, if the network + name could not be determined. + """ + return platform.node() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb37582d54cd31fec5b86d69395e736e9a437dec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/action_dist.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/action_dist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7c0b70cf790d1c4a9a4d065ba3f8530adf62ff4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/action_dist.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/catalog.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/catalog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58b8a0249778923b44f19afc25df7d8b9b54a00d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/catalog.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/distributions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/distributions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81d0015428abd47993ff5f7e7a55ab641a11994c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/distributions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/modelv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/modelv2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5faf4b58e9a8a3a413ea2e0f11e98a95a79c8e80 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/modelv2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/preprocessors.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/preprocessors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f482b5cb59321b697917711b402ad1b0f85a9e84 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/preprocessors.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/repeated_values.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/repeated_values.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aef294534a79951f52a27a9c5eb95f82b13bcd4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/repeated_values.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0757e667d380aeab408eba0e031b038e6342aed Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..86d33b39d455bcd6f43da151586444df41711b1c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__init__.py @@ -0,0 +1,11 @@ +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.tf.fcnet import FullyConnectedNetwork +from ray.rllib.models.tf.recurrent_net import RecurrentNetwork +from ray.rllib.models.tf.visionnet import VisionNetwork + +__all__ = [ + "FullyConnectedNetwork", + "RecurrentNetwork", + "TFModelV2", + "VisionNetwork", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98cba61962b8646416ee72c5f4d77401767e263e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/attention_net.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/attention_net.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0406f1d00a398f00142500ea62e1887e2223c3b5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/attention_net.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/complex_input_net.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/complex_input_net.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ef4f27aae73c26007f3887a11782025b7c4a8ce Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/complex_input_net.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/fcnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/fcnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b31770aca48ddfeff5fc15095aabf3e00f8aa3c5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/fcnet.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/misc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..506cd9afb3e450e28d703774c3365b5ba40a0a45 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/misc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/recurrent_net.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/recurrent_net.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74006c0c3d91036e72b656a080456fe8b7c46508 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/recurrent_net.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/tf_action_dist.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/tf_action_dist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15cffab549a258c34db0053a4109c5adcf5d2293 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/tf_action_dist.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/tf_modelv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/tf_modelv2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61bb81e21348f75093175e84d6cb798d710cf232 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/tf_modelv2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/visionnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/visionnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3cb65ded704577a2cec9b8c806e0d0df43cf2cb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/__pycache__/visionnet.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/attention_net.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/attention_net.py new file mode 100644 index 0000000000000000000000000000000000000000..886580fce177a0e075eb2d252ef869e181f5ae1b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/attention_net.py @@ -0,0 +1,573 @@ +""" +[1] - Attention Is All You Need - Vaswani, Jones, Shazeer, Parmar, + Uszkoreit, Gomez, Kaiser - Google Brain/Research, U Toronto - 2017. + https://arxiv.org/pdf/1706.03762.pdf +[2] - Stabilizing Transformers for Reinforcement Learning - E. Parisotto + et al. - DeepMind - 2019. https://arxiv.org/pdf/1910.06764.pdf +[3] - Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. + Z. Dai, Z. Yang, et al. - Carnegie Mellon U - 2019. + https://www.aclweb.org/anthology/P19-1285.pdf +""" +import gymnasium as gym +from gymnasium.spaces import Box, Discrete, MultiDiscrete +import numpy as np +import tree # pip install dm_tree +from typing import Any, Dict, Optional, Union + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.layers import ( + GRUGate, + RelativeMultiHeadAttention, + SkipConnection, +) +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.tf.recurrent_net import RecurrentNetwork +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.tf_utils import flatten_inputs_to_1d_tensor, one_hot +from ray.rllib.utils.typing import ModelConfigDict, TensorType, List +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util import log_once + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class PositionwiseFeedforward(tf.keras.layers.Layer if tf else object): + """A 2x linear layer with ReLU activation in between described in [1]. + + Each timestep coming from the attention head will be passed through this + layer separately. + """ + + def __init__( + self, + out_dim: int, + hidden_dim: int, + output_activation: Optional[Any] = None, + **kwargs, + ): + super().__init__(**kwargs) + + self._hidden_layer = tf.keras.layers.Dense( + hidden_dim, + activation=tf.nn.relu, + ) + + self._output_layer = tf.keras.layers.Dense( + out_dim, activation=output_activation + ) + if log_once("positionwise_feedforward_tf"): + deprecation_warning( + old="rllib.models.tf.attention_net.PositionwiseFeedforward", + ) + + def call(self, inputs: TensorType, **kwargs) -> TensorType: + del kwargs + output = self._hidden_layer(inputs) + return self._output_layer(output) + + +@OldAPIStack +class TrXLNet(RecurrentNetwork): + """A TrXL net Model described in [1].""" + + def __init__( + self, + observation_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + num_transformer_units: int, + attention_dim: int, + num_heads: int, + head_dim: int, + position_wise_mlp_dim: int, + ): + """Initializes a TrXLNet object. + + Args: + num_transformer_units: The number of Transformer repeats to + use (denoted L in [2]). + attention_dim: The input and output dimensions of one + Transformer unit. + num_heads: The number of attention heads to use in parallel. + Denoted as `H` in [3]. + head_dim: The dimension of a single(!) attention head within + a multi-head attention unit. Denoted as `d` in [3]. + position_wise_mlp_dim: The dimension of the hidden layer + within the position-wise MLP (after the multi-head attention + block within one Transformer unit). This is the size of the + first of the two layers within the PositionwiseFeedforward. The + second layer always has size=`attention_dim`. + """ + if log_once("trxl_net_tf"): + deprecation_warning( + old="rllib.models.tf.attention_net.TrXLNet", + ) + super().__init__( + observation_space, action_space, num_outputs, model_config, name + ) + + self.num_transformer_units = num_transformer_units + self.attention_dim = attention_dim + self.num_heads = num_heads + self.head_dim = head_dim + self.max_seq_len = model_config["max_seq_len"] + self.obs_dim = observation_space.shape[0] + + inputs = tf.keras.layers.Input( + shape=(self.max_seq_len, self.obs_dim), name="inputs" + ) + E_out = tf.keras.layers.Dense(attention_dim)(inputs) + + for _ in range(self.num_transformer_units): + MHA_out = SkipConnection( + RelativeMultiHeadAttention( + out_dim=attention_dim, + num_heads=num_heads, + head_dim=head_dim, + input_layernorm=False, + output_activation=None, + ), + fan_in_layer=None, + )(E_out) + E_out = SkipConnection( + PositionwiseFeedforward(attention_dim, position_wise_mlp_dim) + )(MHA_out) + E_out = tf.keras.layers.LayerNormalization(axis=-1)(E_out) + + # Postprocess TrXL output with another hidden layer and compute values. + logits = tf.keras.layers.Dense( + self.num_outputs, activation=tf.keras.activations.linear, name="logits" + )(E_out) + + self.base_model = tf.keras.models.Model([inputs], [logits]) + + @override(RecurrentNetwork) + def forward_rnn( + self, inputs: TensorType, state: List[TensorType], seq_lens: TensorType + ) -> (TensorType, List[TensorType]): + # To make Attention work with current RLlib's ModelV2 API: + # We assume `state` is the history of L recent observations (all + # concatenated into one tensor) and append the current inputs to the + # end and only keep the most recent (up to `max_seq_len`). This allows + # us to deal with timestep-wise inference and full sequence training + # within the same logic. + observations = state[0] + observations = tf.concat((observations, inputs), axis=1)[:, -self.max_seq_len :] + logits = self.base_model([observations]) + T = tf.shape(inputs)[1] # Length of input segment (time). + logits = logits[:, -T:] + + return logits, [observations] + + @override(RecurrentNetwork) + def get_initial_state(self) -> List[np.ndarray]: + # State is the T last observations concat'd together into one Tensor. + # Plus all Transformer blocks' E(l) outputs concat'd together (up to + # tau timesteps). + return [np.zeros((self.max_seq_len, self.obs_dim), np.float32)] + + +class GTrXLNet(RecurrentNetwork): + """A GTrXL net Model described in [2]. + + This is still in an experimental phase. + Can be used as a drop-in replacement for LSTMs in PPO and IMPALA. + + To use this network as a replacement for an RNN, configure your Algorithm + as follows: + + Examples: + >> config["model"]["custom_model"] = GTrXLNet + >> config["model"]["max_seq_len"] = 10 + >> config["model"]["custom_model_config"] = { + >> num_transformer_units=1, + >> attention_dim=32, + >> num_heads=2, + >> memory_inference=100, + >> memory_training=50, + >> etc.. + >> } + """ + + def __init__( + self, + observation_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: Optional[int], + model_config: ModelConfigDict, + name: str, + *, + num_transformer_units: int = 1, + attention_dim: int = 64, + num_heads: int = 2, + memory_inference: int = 50, + memory_training: int = 50, + head_dim: int = 32, + position_wise_mlp_dim: int = 32, + init_gru_gate_bias: float = 2.0, + ): + """Initializes a GTrXLNet instance. + + Args: + num_transformer_units: The number of Transformer repeats to + use (denoted L in [2]). + attention_dim: The input and output dimensions of one + Transformer unit. + num_heads: The number of attention heads to use in parallel. + Denoted as `H` in [3]. + memory_inference: The number of timesteps to concat (time + axis) and feed into the next transformer unit as inference + input. The first transformer unit will receive this number of + past observations (plus the current one), instead. + memory_training: The number of timesteps to concat (time + axis) and feed into the next transformer unit as training + input (plus the actual input sequence of len=max_seq_len). + The first transformer unit will receive this number of + past observations (plus the input sequence), instead. + head_dim: The dimension of a single(!) attention head within + a multi-head attention unit. Denoted as `d` in [3]. + position_wise_mlp_dim: The dimension of the hidden layer + within the position-wise MLP (after the multi-head attention + block within one Transformer unit). This is the size of the + first of the two layers within the PositionwiseFeedforward. The + second layer always has size=`attention_dim`. + init_gru_gate_bias: Initial bias values for the GRU gates + (two GRUs per Transformer unit, one after the MHA, one after + the position-wise MLP). + """ + super().__init__( + observation_space, action_space, num_outputs, model_config, name + ) + + self.num_transformer_units = num_transformer_units + self.attention_dim = attention_dim + self.num_heads = num_heads + self.memory_inference = memory_inference + self.memory_training = memory_training + self.head_dim = head_dim + self.max_seq_len = model_config["max_seq_len"] + self.obs_dim = observation_space.shape[0] + + # Raw observation input (plus (None) time axis). + input_layer = tf.keras.layers.Input(shape=(None, self.obs_dim), name="inputs") + memory_ins = [ + tf.keras.layers.Input( + shape=(None, self.attention_dim), + dtype=tf.float32, + name="memory_in_{}".format(i), + ) + for i in range(self.num_transformer_units) + ] + + # Map observation dim to input/output transformer (attention) dim. + E_out = tf.keras.layers.Dense(self.attention_dim)(input_layer) + # Output, collected and concat'd to build the internal, tau-len + # Memory units used for additional contextual information. + memory_outs = [E_out] + + # 2) Create L Transformer blocks according to [2]. + for i in range(self.num_transformer_units): + # RelativeMultiHeadAttention part. + MHA_out = SkipConnection( + RelativeMultiHeadAttention( + out_dim=self.attention_dim, + num_heads=num_heads, + head_dim=head_dim, + input_layernorm=True, + output_activation=tf.nn.relu, + ), + fan_in_layer=GRUGate(init_gru_gate_bias), + name="mha_{}".format(i + 1), + )(E_out, memory=memory_ins[i]) + # Position-wise MLP part. + E_out = SkipConnection( + tf.keras.Sequential( + ( + tf.keras.layers.LayerNormalization(axis=-1), + PositionwiseFeedforward( + out_dim=self.attention_dim, + hidden_dim=position_wise_mlp_dim, + output_activation=tf.nn.relu, + ), + ) + ), + fan_in_layer=GRUGate(init_gru_gate_bias), + name="pos_wise_mlp_{}".format(i + 1), + )(MHA_out) + # Output of position-wise MLP == E(l-1), which is concat'd + # to the current Mem block (M(l-1)) to yield E~(l-1), which is then + # used by the next transformer block. + memory_outs.append(E_out) + + self._logits = None + self._value_out = None + + # Postprocess TrXL output with another hidden layer and compute values. + if num_outputs is not None: + self._logits = tf.keras.layers.Dense( + self.num_outputs, activation=None, name="logits" + )(E_out) + values_out = tf.keras.layers.Dense(1, activation=None, name="values")(E_out) + outs = [self._logits, values_out] + else: + outs = [E_out] + self.num_outputs = self.attention_dim + + self.trxl_model = tf.keras.Model( + inputs=[input_layer] + memory_ins, outputs=outs + memory_outs[:-1] + ) + + self.trxl_model.summary() + + # __sphinx_doc_begin__ + # Setup trajectory views (`memory-inference` x past memory outs). + for i in range(self.num_transformer_units): + space = Box(-1.0, 1.0, shape=(self.attention_dim,)) + self.view_requirements["state_in_{}".format(i)] = ViewRequirement( + "state_out_{}".format(i), + shift="-{}:-1".format(self.memory_inference), + # Repeat the incoming state every max-seq-len times. + batch_repeat_value=self.max_seq_len, + space=space, + ) + self.view_requirements["state_out_{}".format(i)] = ViewRequirement( + space=space, used_for_training=False + ) + # __sphinx_doc_end__ + + @override(ModelV2) + def forward( + self, input_dict, state: List[TensorType], seq_lens: TensorType + ) -> (TensorType, List[TensorType]): + assert seq_lens is not None + + # Add the time dim to observations. + B = tf.shape(seq_lens)[0] + observations = input_dict[SampleBatch.OBS] + + shape = tf.shape(observations) + T = shape[0] // B + observations = tf.reshape(observations, tf.concat([[-1, T], shape[1:]], axis=0)) + + all_out = self.trxl_model([observations] + state) + + if self._logits is not None: + out = tf.reshape(all_out[0], [-1, self.num_outputs]) + self._value_out = all_out[1] + memory_outs = all_out[2:] + else: + out = tf.reshape(all_out[0], [-1, self.attention_dim]) + memory_outs = all_out[1:] + + return out, [tf.reshape(m, [-1, self.attention_dim]) for m in memory_outs] + + @override(RecurrentNetwork) + def get_initial_state(self) -> List[np.ndarray]: + return [ + tf.zeros(self.view_requirements["state_in_{}".format(i)].space.shape) + for i in range(self.num_transformer_units) + ] + + @override(ModelV2) + def value_function(self) -> TensorType: + return tf.reshape(self._value_out, [-1]) + + +class AttentionWrapper(TFModelV2): + """GTrXL wrapper serving as interface for ModelV2s that set use_attention.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + if log_once("attention_wrapper_tf_deprecation"): + deprecation_warning( + old="ray.rllib.models.tf.attention_net.AttentionWrapper" + ) + super().__init__(obs_space, action_space, None, model_config, name) + + self.use_n_prev_actions = model_config["attention_use_n_prev_actions"] + self.use_n_prev_rewards = model_config["attention_use_n_prev_rewards"] + + self.action_space_struct = get_base_struct_from_space(self.action_space) + self.action_dim = 0 + + for space in tree.flatten(self.action_space_struct): + if isinstance(space, Discrete): + self.action_dim += space.n + elif isinstance(space, MultiDiscrete): + self.action_dim += np.sum(space.nvec) + elif space.shape is not None: + self.action_dim += int(np.prod(space.shape)) + else: + self.action_dim += int(len(space)) + + # Add prev-action/reward nodes to input to LSTM. + if self.use_n_prev_actions: + self.num_outputs += self.use_n_prev_actions * self.action_dim + if self.use_n_prev_rewards: + self.num_outputs += self.use_n_prev_rewards + + cfg = model_config + + self.attention_dim = cfg["attention_dim"] + + if self.num_outputs is not None: + in_space = gym.spaces.Box( + float("-inf"), float("inf"), shape=(self.num_outputs,), dtype=np.float32 + ) + else: + in_space = obs_space + + # Construct GTrXL sub-module w/ num_outputs=None (so it does not + # create a logits/value output; we'll do this ourselves in this wrapper + # here). + self.gtrxl = GTrXLNet( + in_space, + action_space, + None, + model_config, + "gtrxl", + num_transformer_units=cfg["attention_num_transformer_units"], + attention_dim=self.attention_dim, + num_heads=cfg["attention_num_heads"], + head_dim=cfg["attention_head_dim"], + memory_inference=cfg["attention_memory_inference"], + memory_training=cfg["attention_memory_training"], + position_wise_mlp_dim=cfg["attention_position_wise_mlp_dim"], + init_gru_gate_bias=cfg["attention_init_gru_gate_bias"], + ) + + # `self.num_outputs` right now is the number of nodes coming from the + # attention net. + input_ = tf.keras.layers.Input(shape=(self.gtrxl.num_outputs,)) + + # Set final num_outputs to correct value (depending on action space). + self.num_outputs = num_outputs + + # Postprocess GTrXL output with another hidden layer and compute + # values. + out = tf.keras.layers.Dense(self.num_outputs, activation=None)(input_) + self._logits_branch = tf.keras.models.Model([input_], [out]) + + out = tf.keras.layers.Dense(1, activation=None)(input_) + self._value_branch = tf.keras.models.Model([input_], [out]) + + self.view_requirements = self.gtrxl.view_requirements + self.view_requirements["obs"].space = self.obs_space + + # Add prev-a/r to this model's view, if required. + if self.use_n_prev_actions: + self.view_requirements[SampleBatch.PREV_ACTIONS] = ViewRequirement( + SampleBatch.ACTIONS, + space=self.action_space, + shift="-{}:-1".format(self.use_n_prev_actions), + ) + if self.use_n_prev_rewards: + self.view_requirements[SampleBatch.PREV_REWARDS] = ViewRequirement( + SampleBatch.REWARDS, shift="-{}:-1".format(self.use_n_prev_rewards) + ) + + @override(RecurrentNetwork) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + assert seq_lens is not None + # Push obs through "unwrapped" net's `forward()` first. + wrapped_out, _ = self._wrapped_forward(input_dict, [], None) + + # Concat. prev-action/reward if required. + prev_a_r = [] + + # Prev actions. + if self.use_n_prev_actions: + prev_n_actions = input_dict[SampleBatch.PREV_ACTIONS] + # If actions are not processed yet (in their original form as + # have been sent to environment): + # Flatten/one-hot into 1D array. + if self.model_config["_disable_action_flattening"]: + # Merge prev n actions into flat tensor. + flat = flatten_inputs_to_1d_tensor( + prev_n_actions, + spaces_struct=self.action_space_struct, + time_axis=True, + ) + # Fold time-axis into flattened data. + flat = tf.reshape(flat, [tf.shape(flat)[0], -1]) + prev_a_r.append(flat) + # If actions are already flattened (but not one-hot'd yet!), + # one-hot discrete/multi-discrete actions here and concatenate the + # n most recent actions together. + else: + if isinstance(self.action_space, Discrete): + for i in range(self.use_n_prev_actions): + prev_a_r.append( + one_hot(prev_n_actions[:, i], self.action_space) + ) + elif isinstance(self.action_space, MultiDiscrete): + for i in range( + 0, self.use_n_prev_actions, self.action_space.shape[0] + ): + prev_a_r.append( + one_hot( + tf.cast( + prev_n_actions[ + :, i : i + self.action_space.shape[0] + ], + tf.float32, + ), + space=self.action_space, + ) + ) + else: + prev_a_r.append( + tf.reshape( + tf.cast(prev_n_actions, tf.float32), + [-1, self.use_n_prev_actions * self.action_dim], + ) + ) + # Prev rewards. + if self.use_n_prev_rewards: + prev_a_r.append( + tf.reshape( + tf.cast(input_dict[SampleBatch.PREV_REWARDS], tf.float32), + [-1, self.use_n_prev_rewards], + ) + ) + + # Concat prev. actions + rewards to the "main" input. + if prev_a_r: + wrapped_out = tf.concat([wrapped_out] + prev_a_r, axis=1) + + # Then through our GTrXL. + input_dict["obs_flat"] = input_dict["obs"] = wrapped_out + + self._features, memory_outs = self.gtrxl(input_dict, state, seq_lens) + model_out = self._logits_branch(self._features) + return model_out, memory_outs + + @override(ModelV2) + def value_function(self) -> TensorType: + assert self._features is not None, "Must call forward() first!" + return tf.reshape(self._value_branch(self._features), [-1]) + + @override(ModelV2) + def get_initial_state(self) -> Union[List[np.ndarray], List[TensorType]]: + return [ + np.zeros(self.gtrxl.view_requirements["state_in_{}".format(i)].space.shape) + for i in range(self.gtrxl.num_transformer_units) + ] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/complex_input_net.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/complex_input_net.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c41be4067a1473107a39a1f4f7ec94d8a99f27 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/complex_input_net.py @@ -0,0 +1,214 @@ +from gymnasium.spaces import Box, Discrete, MultiDiscrete +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2, restore_original_dimensions +from ray.rllib.models.tf.misc import normc_initializer +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.utils import get_filter_config +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.spaces.space_utils import flatten_space +from ray.rllib.utils.tf_utils import one_hot + +tf1, tf, tfv = try_import_tf() + + +# __sphinx_doc_begin__ +@OldAPIStack +class ComplexInputNetwork(TFModelV2): + """TFModelV2 concat'ing CNN outputs to flat input(s), followed by FC(s). + + Note: This model should be used for complex (Dict or Tuple) observation + spaces that have one or more image components. + + The data flow is as follows: + + `obs` (e.g. Tuple[img0, img1, discrete0]) -> `CNN0 + CNN1 + ONE-HOT` + `CNN0 + CNN1 + ONE-HOT` -> concat all flat outputs -> `out` + `out` -> (optional) FC-stack -> `out2` + `out2` -> action (logits) and vaulue heads. + """ + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + + self.original_space = ( + obs_space.original_space + if hasattr(obs_space, "original_space") + else obs_space + ) + + self.processed_obs_space = ( + self.original_space + if model_config.get("_disable_preprocessor_api") + else obs_space + ) + super().__init__( + self.original_space, action_space, num_outputs, model_config, name + ) + + self.flattened_input_space = flatten_space(self.original_space) + + # Build the CNN(s) given obs_space's image components. + self.cnns = {} + self.one_hot = {} + self.flatten_dims = {} + self.flatten = {} + concat_size = 0 + for i, component in enumerate(self.flattened_input_space): + # Image space. + if len(component.shape) == 3 and isinstance(component, Box): + config = { + "conv_filters": model_config["conv_filters"] + if "conv_filters" in model_config + else get_filter_config(component.shape), + "conv_activation": model_config.get("conv_activation"), + "post_fcnet_hiddens": [], + } + self.cnns[i] = ModelCatalog.get_model_v2( + component, + action_space, + num_outputs=None, + model_config=config, + framework="tf", + name="cnn_{}".format(i), + ) + concat_size += int(self.cnns[i].num_outputs) + # Discrete|MultiDiscrete inputs -> One-hot encode. + elif isinstance(component, (Discrete, MultiDiscrete)): + if isinstance(component, Discrete): + size = component.n + else: + size = np.sum(component.nvec) + config = { + "fcnet_hiddens": model_config["fcnet_hiddens"], + "fcnet_activation": model_config.get("fcnet_activation"), + "post_fcnet_hiddens": [], + } + self.one_hot[i] = ModelCatalog.get_model_v2( + Box(-1.0, 1.0, (size,), np.float32), + action_space, + num_outputs=None, + model_config=config, + framework="tf", + name="one_hot_{}".format(i), + ) + concat_size += int(self.one_hot[i].num_outputs) + # Everything else (1D Box). + else: + size = int(np.prod(component.shape)) + config = { + "fcnet_hiddens": model_config["fcnet_hiddens"], + "fcnet_activation": model_config.get("fcnet_activation"), + "post_fcnet_hiddens": [], + } + self.flatten[i] = ModelCatalog.get_model_v2( + Box(-1.0, 1.0, (size,), np.float32), + action_space, + num_outputs=None, + model_config=config, + framework="tf", + name="flatten_{}".format(i), + ) + self.flatten_dims[i] = size + concat_size += int(self.flatten[i].num_outputs) + + # Optional post-concat FC-stack. + post_fc_stack_config = { + "fcnet_hiddens": model_config.get("post_fcnet_hiddens", []), + "fcnet_activation": model_config.get("post_fcnet_activation", "relu"), + } + self.post_fc_stack = ModelCatalog.get_model_v2( + Box(float("-inf"), float("inf"), shape=(concat_size,), dtype=np.float32), + self.action_space, + None, + post_fc_stack_config, + framework="tf", + name="post_fc_stack", + ) + + # Actions and value heads. + self.logits_and_value_model = None + self._value_out = None + if num_outputs: + # Action-distribution head. + concat_layer = tf.keras.layers.Input((self.post_fc_stack.num_outputs,)) + logits_layer = tf.keras.layers.Dense( + num_outputs, + activation=None, + kernel_initializer=normc_initializer(0.01), + name="logits", + )(concat_layer) + + # Create the value branch model. + value_layer = tf.keras.layers.Dense( + 1, + activation=None, + kernel_initializer=normc_initializer(0.01), + name="value_out", + )(concat_layer) + self.logits_and_value_model = tf.keras.models.Model( + concat_layer, [logits_layer, value_layer] + ) + else: + self.num_outputs = self.post_fc_stack.num_outputs + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + if SampleBatch.OBS in input_dict and "obs_flat" in input_dict: + orig_obs = input_dict[SampleBatch.OBS] + else: + orig_obs = restore_original_dimensions( + input_dict[SampleBatch.OBS], self.processed_obs_space, tensorlib="tf" + ) + # Push image observations through our CNNs. + outs = [] + for i, component in enumerate(tree.flatten(orig_obs)): + if i in self.cnns: + cnn_out, _ = self.cnns[i](SampleBatch({SampleBatch.OBS: component})) + outs.append(cnn_out) + elif i in self.one_hot: + if "int" in component.dtype.name: + one_hot_in = { + SampleBatch.OBS: one_hot( + component, self.flattened_input_space[i] + ) + } + else: + one_hot_in = {SampleBatch.OBS: component} + one_hot_out, _ = self.one_hot[i](SampleBatch(one_hot_in)) + outs.append(one_hot_out) + else: + nn_out, _ = self.flatten[i]( + SampleBatch( + { + SampleBatch.OBS: tf.cast( + tf.reshape(component, [-1, self.flatten_dims[i]]), + tf.float32, + ) + } + ) + ) + outs.append(nn_out) + # Concat all outputs and the non-image inputs. + out = tf.concat(outs, axis=1) + # Push through (optional) FC-stack (this may be an empty stack). + out, _ = self.post_fc_stack(SampleBatch({SampleBatch.OBS: out})) + + # No logits/value branches. + if not self.logits_and_value_model: + return out, [] + + # Logits- and value branches. + logits, values = self.logits_and_value_model(out) + self._value_out = tf.reshape(values, [-1]) + return logits, [] + + @override(ModelV2) + def value_function(self): + return self._value_out + + +# __sphinx_doc_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/fcnet.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/fcnet.py new file mode 100644 index 0000000000000000000000000000000000000000..56a09de0361acf371f5d6b8ab60fc7d2790565c7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/fcnet.py @@ -0,0 +1,148 @@ +import numpy as np +import gymnasium as gym +from typing import Dict + +from ray.rllib.models.tf.misc import normc_initializer +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.utils import get_activation_fn +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType, List, ModelConfigDict + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class FullyConnectedNetwork(TFModelV2): + """Generic fully connected network implemented in ModelV2 API.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + super(FullyConnectedNetwork, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + + hiddens = list(model_config.get("fcnet_hiddens", [])) + list( + model_config.get("post_fcnet_hiddens", []) + ) + activation = model_config.get("fcnet_activation") + if not model_config.get("fcnet_hiddens", []): + activation = model_config.get("post_fcnet_activation") + activation = get_activation_fn(activation) + no_final_linear = model_config.get("no_final_linear") + vf_share_layers = model_config.get("vf_share_layers") + free_log_std = model_config.get("free_log_std") + + # Generate free-floating bias variables for the second half of + # the outputs. + if free_log_std: + assert num_outputs % 2 == 0, ( + "num_outputs must be divisible by two", + num_outputs, + ) + num_outputs = num_outputs // 2 + self.log_std_var = tf.Variable( + [0.0] * num_outputs, dtype=tf.float32, name="log_std" + ) + + # We are using obs_flat, so take the flattened shape as input. + inputs = tf.keras.layers.Input( + shape=(int(np.prod(obs_space.shape)),), name="observations" + ) + # Last hidden layer output (before logits outputs). + last_layer = inputs + # The action distribution outputs. + logits_out = None + i = 1 + + # Create layers 0 to second-last. + for size in hiddens[:-1]: + last_layer = tf.keras.layers.Dense( + size, + name="fc_{}".format(i), + activation=activation, + kernel_initializer=normc_initializer(1.0), + )(last_layer) + i += 1 + + # The last layer is adjusted to be of size num_outputs, but it's a + # layer with activation. + if no_final_linear and num_outputs: + logits_out = tf.keras.layers.Dense( + num_outputs, + name="fc_out", + activation=activation, + kernel_initializer=normc_initializer(1.0), + )(last_layer) + # Finish the layers with the provided sizes (`hiddens`), plus - + # iff num_outputs > 0 - a last linear layer of size num_outputs. + else: + if len(hiddens) > 0: + last_layer = tf.keras.layers.Dense( + hiddens[-1], + name="fc_{}".format(i), + activation=activation, + kernel_initializer=normc_initializer(1.0), + )(last_layer) + if num_outputs: + logits_out = tf.keras.layers.Dense( + num_outputs, + name="fc_out", + activation=None, + kernel_initializer=normc_initializer(0.01), + )(last_layer) + # Adjust num_outputs to be the number of nodes in the last layer. + else: + self.num_outputs = ([int(np.prod(obs_space.shape))] + hiddens[-1:])[-1] + + # Concat the log std vars to the end of the state-dependent means. + if free_log_std and logits_out is not None: + + def tiled_log_std(x): + return tf.tile(tf.expand_dims(self.log_std_var, 0), [tf.shape(x)[0], 1]) + + log_std_out = tf.keras.layers.Lambda(tiled_log_std)(inputs) + logits_out = tf.keras.layers.Concatenate(axis=1)([logits_out, log_std_out]) + + last_vf_layer = None + if not vf_share_layers: + # Build a parallel set of hidden layers for the value net. + last_vf_layer = inputs + i = 1 + for size in hiddens: + last_vf_layer = tf.keras.layers.Dense( + size, + name="fc_value_{}".format(i), + activation=activation, + kernel_initializer=normc_initializer(1.0), + )(last_vf_layer) + i += 1 + + value_out = tf.keras.layers.Dense( + 1, + name="value_out", + activation=None, + kernel_initializer=normc_initializer(0.01), + )(last_vf_layer if last_vf_layer is not None else last_layer) + + self.base_model = tf.keras.Model( + inputs, [(logits_out if logits_out is not None else last_layer), value_out] + ) + + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + model_out, self._value_out = self.base_model(input_dict["obs_flat"]) + return model_out, state + + def value_function(self) -> TensorType: + return tf.reshape(self._value_out, [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6b840c42b17eff05c8e0c7d440a0f2963c9ed35a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__init__.py @@ -0,0 +1,17 @@ +from ray.rllib.models.tf.layers.gru_gate import GRUGate +from ray.rllib.models.tf.layers.noisy_layer import NoisyLayer +from ray.rllib.models.tf.layers.relative_multi_head_attention import ( + PositionalEmbedding, + RelativeMultiHeadAttention, +) +from ray.rllib.models.tf.layers.skip_connection import SkipConnection +from ray.rllib.models.tf.layers.multi_head_attention import MultiHeadAttention + +__all__ = [ + "GRUGate", + "MultiHeadAttention", + "NoisyLayer", + "PositionalEmbedding", + "RelativeMultiHeadAttention", + "SkipConnection", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..109b9218cf91478abd7d66eaaaffb7392e3af08d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/gru_gate.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/gru_gate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04c8a1be9b19a1a7ceafad21ed9d214ad867a72d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/gru_gate.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/multi_head_attention.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/multi_head_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6ef8a3d8f82e2b4418fce8d6b7bcad604ae980d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/multi_head_attention.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/noisy_layer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/noisy_layer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e2e3f447101cf04327d9d9b82a5bb0214773161 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/noisy_layer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/relative_multi_head_attention.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/relative_multi_head_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e93363e981b51a201feb632db99c23e2b28cd80 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/relative_multi_head_attention.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/skip_connection.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/skip_connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..854db92976509d04a0a5f230ec6c545ba1667945 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/__pycache__/skip_connection.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/gru_gate.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/gru_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..a41b23bbf534a15d0d3c71333bcba1bb0c0a6d3b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/gru_gate.py @@ -0,0 +1,58 @@ +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType, TensorShape +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util import log_once + +tf1, tf, tfv = try_import_tf() + + +class GRUGate(tf.keras.layers.Layer if tf else object): + def __init__(self, init_bias: float = 0.0, **kwargs): + super().__init__(**kwargs) + self._init_bias = init_bias + if log_once("gru_gate"): + deprecation_warning( + old="rllib.models.tf.layers.GRUGate", + ) + + def build(self, input_shape: TensorShape): + h_shape, x_shape = input_shape + if x_shape[-1] != h_shape[-1]: + raise ValueError( + "Both inputs to GRUGate must have equal size in last axis!" + ) + + dim = int(h_shape[-1]) + self._w_r = self.add_weight(shape=(dim, dim)) + self._w_z = self.add_weight(shape=(dim, dim)) + self._w_h = self.add_weight(shape=(dim, dim)) + + self._u_r = self.add_weight(shape=(dim, dim)) + self._u_z = self.add_weight(shape=(dim, dim)) + self._u_h = self.add_weight(shape=(dim, dim)) + + def bias_initializer(shape, dtype): + return tf.fill(shape, tf.cast(self._init_bias, dtype=dtype)) + + self._bias_z = self.add_weight(shape=(dim,), initializer=bias_initializer) + + def call(self, inputs: TensorType, **kwargs) -> TensorType: + # Pass in internal state first. + h, X = inputs + + r = tf.tensordot(X, self._w_r, axes=1) + tf.tensordot(h, self._u_r, axes=1) + r = tf.nn.sigmoid(r) + + z = ( + tf.tensordot(X, self._w_z, axes=1) + + tf.tensordot(h, self._u_z, axes=1) + - self._bias_z + ) + z = tf.nn.sigmoid(z) + + h_next = tf.tensordot(X, self._w_h, axes=1) + tf.tensordot( + (h * r), self._u_h, axes=1 + ) + h_next = tf.nn.tanh(h_next) + + return (1 - z) * h + z * h_next diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/multi_head_attention.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/multi_head_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..595608989f0b7da66e640a041289ae646cb36ae4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/multi_head_attention.py @@ -0,0 +1,61 @@ +""" +[1] - Attention Is All You Need - Vaswani, Jones, Shazeer, Parmar, + Uszkoreit, Gomez, Kaiser - Google Brain/Research, U Toronto - 2017. + https://arxiv.org/pdf/1706.03762.pdf +""" +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util import log_once + +tf1, tf, tfv = try_import_tf() + + +class MultiHeadAttention(tf.keras.layers.Layer if tf else object): + """A multi-head attention layer described in [1].""" + + def __init__(self, out_dim: int, num_heads: int, head_dim: int, **kwargs): + super().__init__(**kwargs) + + # No bias or non-linearity. + self._num_heads = num_heads + self._head_dim = head_dim + self._qkv_layer = tf.keras.layers.Dense( + 3 * num_heads * head_dim, use_bias=False + ) + self._linear_layer = tf.keras.layers.TimeDistributed( + tf.keras.layers.Dense(out_dim, use_bias=False) + ) + if log_once("multi_head_attention"): + deprecation_warning( + old="rllib.models.tf.layers.MultiHeadAttention", + ) + + def call(self, inputs: TensorType) -> TensorType: + L = tf.shape(inputs)[1] # length of segment + H = self._num_heads # number of attention heads + D = self._head_dim # attention head dimension + + qkv = self._qkv_layer(inputs) + + queries, keys, values = tf.split(qkv, 3, -1) + queries = queries[:, -L:] # only query based on the segment + + queries = tf.reshape(queries, [-1, L, H, D]) + keys = tf.reshape(keys, [-1, L, H, D]) + values = tf.reshape(values, [-1, L, H, D]) + + score = tf.einsum("bihd,bjhd->bijh", queries, keys) + score = score / D**0.5 + + # causal mask of the same length as the sequence + mask = tf.sequence_mask(tf.range(1, L + 1), dtype=score.dtype) + mask = mask[None, :, :, None] + + masked_score = score * mask + 1e30 * (mask - 1.0) + wmat = tf.nn.softmax(masked_score, axis=2) + + out = tf.einsum("bijh,bjhd->bihd", wmat, values) + shape = tf.concat([tf.shape(out)[:2], [H * D]], axis=0) + out = tf.reshape(out, shape) + return self._linear_layer(out) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/noisy_layer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/noisy_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..5bc149d5de13beee0e77fcda069e321850507633 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/noisy_layer.py @@ -0,0 +1,118 @@ +import numpy as np + +from ray.rllib.models.utils import get_activation_fn +from ray.rllib.utils.framework import ( + get_variable, + try_import_tf, + TensorType, + TensorShape, +) +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util import log_once + +tf1, tf, tfv = try_import_tf() + + +class NoisyLayer(tf.keras.layers.Layer if tf else object): + r"""A Layer that adds learnable Noise to some previous layer's outputs. + + Consists of: + - a common dense layer: y = w^{T}x + b + - a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + + (b+\epsilon_b*\sigma_b) + , where \epsilon are random variables sampled from factorized normal + distributions and \sigma are trainable variables which are expected to + vanish along the training procedure. + """ + + def __init__( + self, prefix: str, out_size: int, sigma0: float, activation: str = "relu" + ): + """Initializes a NoisyLayer object. + + Args: + prefix: + out_size: Output size for Noisy Layer + sigma0: Initialization value for sigma_b (bias noise) + non_linear: Non-linear activation for Noisy Layer + """ + super().__init__() + self.prefix = prefix + self.out_size = out_size + # TF noise generation can be unreliable on GPU + # If generating the noise on the CPU, + # lowering sigma0 to 0.1 may be helpful + self.sigma0 = sigma0 # 0.5~GPU, 0.1~CPU + self.activation = activation + # Variables. + self.w = None # Weight matrix. + self.b = None # Biases. + self.sigma_w = None # Noise for weight matrix + self.sigma_b = None # Noise for biases. + if log_once("noisy_layer"): + deprecation_warning( + old="rllib.models.tf.layers.NoisyLayer", + ) + + def build(self, input_shape: TensorShape): + in_size = int(input_shape[1]) + + self.sigma_w = get_variable( + value=tf.keras.initializers.RandomUniform( + minval=-1.0 / np.sqrt(float(in_size)), + maxval=1.0 / np.sqrt(float(in_size)), + ), + trainable=True, + tf_name=self.prefix + "_sigma_w", + shape=[in_size, self.out_size], + dtype=tf.float32, + ) + + self.sigma_b = get_variable( + value=tf.keras.initializers.Constant(self.sigma0 / np.sqrt(float(in_size))), + trainable=True, + tf_name=self.prefix + "_sigma_b", + shape=[self.out_size], + dtype=tf.float32, + ) + + self.w = get_variable( + value=tf.keras.initializers.GlorotUniform(), + tf_name=self.prefix + "_fc_w", + trainable=True, + shape=[in_size, self.out_size], + dtype=tf.float32, + ) + + self.b = get_variable( + value=tf.keras.initializers.Zeros(), + tf_name=self.prefix + "_fc_b", + trainable=True, + shape=[self.out_size], + dtype=tf.float32, + ) + + def call(self, inputs: TensorType) -> TensorType: + in_size = int(inputs.shape[1]) + epsilon_in = tf.random.normal(shape=[in_size]) + epsilon_out = tf.random.normal(shape=[self.out_size]) + epsilon_in = self._f_epsilon(epsilon_in) + epsilon_out = self._f_epsilon(epsilon_out) + epsilon_w = tf.matmul( + a=tf.expand_dims(epsilon_in, -1), b=tf.expand_dims(epsilon_out, 0) + ) + epsilon_b = epsilon_out + + action_activation = ( + tf.matmul(inputs, self.w + self.sigma_w * epsilon_w) + + self.b + + self.sigma_b * epsilon_b + ) + + fn = get_activation_fn(self.activation, framework="tf") + if fn is not None: + action_activation = fn(action_activation) + return action_activation + + def _f_epsilon(self, x: TensorType) -> TensorType: + return tf.math.sign(x) * tf.math.sqrt(tf.math.abs(x)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/relative_multi_head_attention.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/relative_multi_head_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..f88486ff20516c19fcebdab3718fc829591215fb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/relative_multi_head_attention.py @@ -0,0 +1,147 @@ +from typing import Optional + +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util import log_once + +tf1, tf, tfv = try_import_tf() + + +class RelativeMultiHeadAttention(tf.keras.layers.Layer if tf else object): + """A RelativeMultiHeadAttention layer as described in [3]. + + Uses segment level recurrence with state reuse. + """ + + def __init__( + self, + out_dim: int, + num_heads: int, + head_dim: int, + input_layernorm: bool = False, + output_activation: Optional["tf.nn.activation"] = None, + **kwargs + ): + """Initializes a RelativeMultiHeadAttention keras Layer object. + + Args: + out_dim: The output dimensions of the multi-head attention + unit. + num_heads: The number of attention heads to use. + Denoted `H` in [2]. + head_dim: The dimension of a single(!) attention head within + a multi-head attention unit. Denoted as `d` in [3]. + input_layernorm: Whether to prepend a LayerNorm before + everything else. Should be True for building a GTrXL. + output_activation (Optional[tf.nn.activation]): Optional tf.nn + activation function. Should be relu for GTrXL. + **kwargs: + """ + if log_once("relative_multi_head_attention"): + deprecation_warning( + old="rllib.models.tf.layers.RelativeMultiHeadAttention", + ) + super().__init__(**kwargs) + + # No bias or non-linearity. + self._num_heads = num_heads + self._head_dim = head_dim + # 3=Query, key, and value inputs. + self._qkv_layer = tf.keras.layers.Dense( + 3 * num_heads * head_dim, use_bias=False + ) + self._linear_layer = tf.keras.layers.TimeDistributed( + tf.keras.layers.Dense(out_dim, use_bias=False, activation=output_activation) + ) + + self._uvar = self.add_weight(shape=(num_heads, head_dim)) + self._vvar = self.add_weight(shape=(num_heads, head_dim)) + + # Constant (non-trainable) sinusoid rel pos encoding matrix, which + # depends on this incoming time dimension. + # For inference, we prepend the memory to the current timestep's + # input: Tau + 1. For training, we prepend the memory to the input + # sequence: Tau + T. + self._pos_embedding = PositionalEmbedding(out_dim) + self._pos_proj = tf.keras.layers.Dense(num_heads * head_dim, use_bias=False) + + self._input_layernorm = None + if input_layernorm: + self._input_layernorm = tf.keras.layers.LayerNormalization(axis=-1) + + def call( + self, inputs: TensorType, memory: Optional[TensorType] = None + ) -> TensorType: + T = tf.shape(inputs)[1] # length of segment (time) + H = self._num_heads # number of attention heads + d = self._head_dim # attention head dimension + + # Add previous memory chunk (as const, w/o gradient) to input. + # Tau (number of (prev) time slices in each memory chunk). + Tau = tf.shape(memory)[1] + inputs = tf.concat([tf.stop_gradient(memory), inputs], axis=1) + + # Apply the Layer-Norm. + if self._input_layernorm is not None: + inputs = self._input_layernorm(inputs) + + qkv = self._qkv_layer(inputs) + + queries, keys, values = tf.split(qkv, 3, -1) + # Cut out memory timesteps from query. + queries = queries[:, -T:] + + # Splitting up queries into per-head dims (d). + queries = tf.reshape(queries, [-1, T, H, d]) + keys = tf.reshape(keys, [-1, Tau + T, H, d]) + values = tf.reshape(values, [-1, Tau + T, H, d]) + + R = self._pos_embedding(Tau + T) + R = self._pos_proj(R) + R = tf.reshape(R, [Tau + T, H, d]) + + # b=batch + # i and j=time indices (i=max-timesteps (inputs); j=Tau memory space) + # h=head + # d=head-dim (over which we will reduce-sum) + score = tf.einsum("bihd,bjhd->bijh", queries + self._uvar, keys) + pos_score = tf.einsum("bihd,jhd->bijh", queries + self._vvar, R) + score = score + self.rel_shift(pos_score) + score = score / d**0.5 + + # Causal mask of the same length as the sequence. + mask = tf.sequence_mask(tf.range(Tau + 1, Tau + T + 1), dtype=score.dtype) + mask = mask[None, :, :, None] + + masked_score = score * mask + 1e30 * (mask - 1.0) + wmat = tf.nn.softmax(masked_score, axis=2) + + out = tf.einsum("bijh,bjhd->bihd", wmat, values) + out = tf.reshape(out, tf.concat((tf.shape(out)[:2], [H * d]), axis=0)) + return self._linear_layer(out) + + @staticmethod + def rel_shift(x: TensorType) -> TensorType: + # Transposed version of the shift approach described in [3]. + # https://github.com/kimiyoung/transformer-xl/blob/ + # 44781ed21dbaec88b280f74d9ae2877f52b492a5/tf/model.py#L31 + x_size = tf.shape(x) + + x = tf.pad(x, [[0, 0], [0, 0], [1, 0], [0, 0]]) + x = tf.reshape(x, [x_size[0], x_size[2] + 1, x_size[1], x_size[3]]) + x = x[:, 1:, :, :] + x = tf.reshape(x, x_size) + + return x + + +class PositionalEmbedding(tf.keras.layers.Layer if tf else object): + def __init__(self, out_dim, **kwargs): + super().__init__(**kwargs) + self.inverse_freq = 1 / (10000 ** (tf.range(0, out_dim, 2.0) / out_dim)) + + def call(self, seq_length): + pos_offsets = tf.cast(tf.range(seq_length - 1, -1, -1), tf.float32) + inputs = pos_offsets[:, None] * self.inverse_freq[None, :] + return tf.concat((tf.sin(inputs), tf.cos(inputs)), axis=-1) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/skip_connection.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/skip_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee1751caf36e4a760da3c60c08fe279400dcb12 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/layers/skip_connection.py @@ -0,0 +1,46 @@ +from typing import Optional, Any + +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util import log_once + +tf1, tf, tfv = try_import_tf() + + +class SkipConnection(tf.keras.layers.Layer if tf else object): + """Skip connection layer. + + Adds the original input to the output (regular residual layer) OR uses + input as hidden state input to a given fan_in_layer. + """ + + def __init__(self, layer: Any, fan_in_layer: Optional[Any] = None, **kwargs): + """Initializes a SkipConnection keras layer object. + + Args: + layer (tf.keras.layers.Layer): Any layer processing inputs. + fan_in_layer (Optional[tf.keras.layers.Layer]): An optional + layer taking two inputs: The original input and the output + of `layer`. + """ + if log_once("skip_connection"): + deprecation_warning( + old="rllib.models.tf.layers.SkipConnection", + ) + super().__init__(**kwargs) + self._layer = layer + self._fan_in_layer = fan_in_layer + + def call(self, inputs: TensorType, **kwargs) -> TensorType: + # del kwargs + outputs = self._layer(inputs, **kwargs) + # Residual case, just add inputs to outputs. + if self._fan_in_layer is None: + outputs = outputs + inputs + # Fan-in e.g. RNN: Call fan-in with `inputs` and `outputs`. + else: + # NOTE: In the GRU case, `inputs` is the state input. + outputs = self._fan_in_layer((inputs, outputs)) + + return outputs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/misc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea75e423c2d66756b9e899faa2c6487dd57cab4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/misc.py @@ -0,0 +1,90 @@ +import numpy as np +from typing import Tuple, Any, Optional + +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() + + +# TODO: (sven) obsolete this class. +@DeveloperAPI +def normc_initializer(std: float = 1.0) -> Any: + def _initializer(shape, dtype=None, partition_info=None): + out = np.random.randn(*shape).astype( + dtype.name if hasattr(dtype, "name") else dtype or np.float32 + ) + out *= std / np.sqrt(np.square(out).sum(axis=0, keepdims=True)) + return tf.constant(out) + + return _initializer + + +@DeveloperAPI +def conv2d( + x: TensorType, + num_filters: int, + name: str, + filter_size: Tuple[int, int] = (3, 3), + stride: Tuple[int, int] = (1, 1), + pad: str = "SAME", + dtype: Optional[Any] = None, + collections: Optional[Any] = None, +) -> TensorType: + + if dtype is None: + dtype = tf.float32 + + with tf1.variable_scope(name): + stride_shape = [1, stride[0], stride[1], 1] + filter_shape = [ + filter_size[0], + filter_size[1], + int(x.get_shape()[3]), + num_filters, + ] + + # There are "num input feature maps * filter height * filter width" + # inputs to each hidden unit. + fan_in = np.prod(filter_shape[:3]) + # Each unit in the lower layer receives a gradient from: "num output + # feature maps * filter height * filter width" / pooling size. + fan_out = np.prod(filter_shape[:2]) * num_filters + # Initialize weights with random weights. + w_bound = np.sqrt(6 / (fan_in + fan_out)) + + w = tf1.get_variable( + "W", + filter_shape, + dtype, + tf1.random_uniform_initializer(-w_bound, w_bound), + collections=collections, + ) + b = tf1.get_variable( + "b", + [1, 1, 1, num_filters], + initializer=tf1.constant_initializer(0.0), + collections=collections, + ) + return tf1.nn.conv2d(x, w, stride_shape, pad) + b + + +@DeveloperAPI +def linear( + x: TensorType, + size: int, + name: str, + initializer: Optional[Any] = None, + bias_init: float = 0.0, +) -> TensorType: + w = tf1.get_variable(name + "/w", [x.get_shape()[1], size], initializer=initializer) + b = tf1.get_variable( + name + "/b", [size], initializer=tf1.constant_initializer(bias_init) + ) + return tf.matmul(x, w) + b + + +@DeveloperAPI +def flatten(x: TensorType) -> TensorType: + return tf.reshape(x, [-1, np.prod(x.get_shape().as_list()[1:])]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/recurrent_net.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/recurrent_net.py new file mode 100644 index 0000000000000000000000000000000000000000..2010d4a901188a53cec5d2766e865392c1d7f9d0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/recurrent_net.py @@ -0,0 +1,292 @@ +import numpy as np +import gymnasium as gym +from gymnasium.spaces import Discrete, MultiDiscrete +import logging +import tree # pip install dm_tree +from typing import Dict, List, Tuple + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.policy.rnn_sequencing import add_time_dimension +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.tf_utils import flatten_inputs_to_1d_tensor, one_hot +from ray.rllib.utils.typing import ModelConfigDict, TensorType +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util.debug import log_once + +tf1, tf, tfv = try_import_tf() +logger = logging.getLogger(__name__) + + +@OldAPIStack +class RecurrentNetwork(TFModelV2): + """Helper class to simplify implementing RNN models with TFModelV2. + + Instead of implementing forward(), you can implement forward_rnn() which + takes batches with the time dimension added already. + + Here is an example implementation for a subclass + ``MyRNNClass(RecurrentNetwork)``:: + + def __init__(self, *args, **kwargs): + super(MyModelClass, self).__init__(*args, **kwargs) + cell_size = 256 + + # Define input layers + input_layer = tf.keras.layers.Input( + shape=(None, obs_space.shape[0])) + state_in_h = tf.keras.layers.Input(shape=(256, )) + state_in_c = tf.keras.layers.Input(shape=(256, )) + seq_in = tf.keras.layers.Input(shape=(), dtype=tf.int32) + + # Send to LSTM cell + lstm_out, state_h, state_c = tf.keras.layers.LSTM( + cell_size, return_sequences=True, return_state=True, + name="lstm")( + inputs=input_layer, + mask=tf.sequence_mask(seq_in), + initial_state=[state_in_h, state_in_c]) + output_layer = tf.keras.layers.Dense(...)(lstm_out) + + # Create the RNN model + self.rnn_model = tf.keras.Model( + inputs=[input_layer, seq_in, state_in_h, state_in_c], + outputs=[output_layer, state_h, state_c]) + self.rnn_model.summary() + """ + + @override(ModelV2) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> Tuple[TensorType, List[TensorType]]: + """Adds time dimension to batch before sending inputs to forward_rnn(). + + You should implement forward_rnn() in your subclass.""" + # Creating a __init__ function that acts as a passthrough and adding the warning + # there led to errors probably due to the multiple inheritance. We encountered + # the same error if we add the Deprecated decorator. We therefore add the + # deprecation warning here. + if log_once("recurrent_network_tf"): + deprecation_warning( + old="ray.rllib.models.tf.recurrent_net.RecurrentNetwork" + ) + assert seq_lens is not None + flat_inputs = input_dict["obs_flat"] + inputs = add_time_dimension( + padded_inputs=flat_inputs, seq_lens=seq_lens, framework="tf" + ) + output, new_state = self.forward_rnn( + inputs, + state, + seq_lens, + ) + return tf.reshape(output, [-1, self.num_outputs]), new_state + + def forward_rnn( + self, inputs: TensorType, state: List[TensorType], seq_lens: TensorType + ) -> Tuple[TensorType, List[TensorType]]: + """Call the model with the given input tensors and state. + + Args: + inputs: observation tensor with shape [B, T, obs_size]. + state: list of state tensors, each with shape [B, T, size]. + seq_lens: 1d tensor holding input sequence lengths. + + Returns: + (outputs, new_state): The model output tensor of shape + [B, T, num_outputs] and the list of new state tensors each with + shape [B, size]. + + Sample implementation for the ``MyRNNClass`` example:: + + def forward_rnn(self, inputs, state, seq_lens): + model_out, h, c = self.rnn_model([inputs, seq_lens] + state) + return model_out, [h, c] + """ + raise NotImplementedError("You must implement this for a RNN model") + + def get_initial_state(self) -> List[TensorType]: + """Get the initial recurrent state values for the model. + + Returns: + list of np.array objects, if any + + Sample implementation for the ``MyRNNClass`` example:: + + def get_initial_state(self): + return [ + np.zeros(self.cell_size, np.float32), + np.zeros(self.cell_size, np.float32), + ] + """ + raise NotImplementedError("You must implement this for a RNN model") + + +@OldAPIStack +class LSTMWrapper(RecurrentNetwork): + """An LSTM wrapper serving as an interface for ModelV2s that set use_lstm.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + super(LSTMWrapper, self).__init__( + obs_space, action_space, None, model_config, name + ) + # At this point, self.num_outputs is the number of nodes coming + # from the wrapped (underlying) model. In other words, self.num_outputs + # is the input size for the LSTM layer. + # If None, set it to the observation space. + if self.num_outputs is None: + self.num_outputs = int(np.prod(self.obs_space.shape)) + + self.cell_size = model_config["lstm_cell_size"] + self.use_prev_action = model_config["lstm_use_prev_action"] + self.use_prev_reward = model_config["lstm_use_prev_reward"] + + self.action_space_struct = get_base_struct_from_space(self.action_space) + self.action_dim = 0 + + for space in tree.flatten(self.action_space_struct): + if isinstance(space, Discrete): + self.action_dim += space.n + elif isinstance(space, MultiDiscrete): + self.action_dim += np.sum(space.nvec) + elif space.shape is not None: + self.action_dim += int(np.prod(space.shape)) + else: + self.action_dim += int(len(space)) + + # Add prev-action/reward nodes to input to LSTM. + if self.use_prev_action: + self.num_outputs += self.action_dim + if self.use_prev_reward: + self.num_outputs += 1 + + # Define input layers. + input_layer = tf.keras.layers.Input( + shape=(None, self.num_outputs), name="inputs" + ) + + # Set self.num_outputs to the number of output nodes desired by the + # caller of this constructor. + self.num_outputs = num_outputs + + state_in_h = tf.keras.layers.Input(shape=(self.cell_size,), name="h") + state_in_c = tf.keras.layers.Input(shape=(self.cell_size,), name="c") + seq_in = tf.keras.layers.Input(shape=(), name="seq_in", dtype=tf.int32) + + # Preprocess observation with a hidden layer and send to LSTM cell + lstm_out, state_h, state_c = tf.keras.layers.LSTM( + self.cell_size, return_sequences=True, return_state=True, name="lstm" + )( + inputs=input_layer, + mask=tf.sequence_mask(seq_in), + initial_state=[state_in_h, state_in_c], + ) + + # Postprocess LSTM output with another hidden layer and compute values + logits = tf.keras.layers.Dense( + self.num_outputs, activation=tf.keras.activations.linear, name="logits" + )(lstm_out) + values = tf.keras.layers.Dense(1, activation=None, name="values")(lstm_out) + + # Create the RNN model + self._rnn_model = tf.keras.Model( + inputs=[input_layer, seq_in, state_in_h, state_in_c], + outputs=[logits, values, state_h, state_c], + ) + # Print out model summary in INFO logging mode. + if logger.isEnabledFor(logging.INFO): + self._rnn_model.summary() + + # Add prev-a/r to this model's view, if required. + if model_config["lstm_use_prev_action"]: + self.view_requirements[SampleBatch.PREV_ACTIONS] = ViewRequirement( + SampleBatch.ACTIONS, space=self.action_space, shift=-1 + ) + if model_config["lstm_use_prev_reward"]: + self.view_requirements[SampleBatch.PREV_REWARDS] = ViewRequirement( + SampleBatch.REWARDS, shift=-1 + ) + + @override(RecurrentNetwork) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> Tuple[TensorType, List[TensorType]]: + assert seq_lens is not None + # Push obs through "unwrapped" net's `forward()` first. + wrapped_out, _ = self._wrapped_forward(input_dict, [], None) + + # Concat. prev-action/reward if required. + prev_a_r = [] + + # Prev actions. + if self.model_config["lstm_use_prev_action"]: + prev_a = input_dict[SampleBatch.PREV_ACTIONS] + # If actions are not processed yet (in their original form as + # have been sent to environment): + # Flatten/one-hot into 1D array. + if self.model_config["_disable_action_flattening"]: + prev_a_r.append( + flatten_inputs_to_1d_tensor( + prev_a, + spaces_struct=self.action_space_struct, + time_axis=False, + ) + ) + # If actions are already flattened (but not one-hot'd yet!), + # one-hot discrete/multi-discrete actions here. + else: + if isinstance(self.action_space, (Discrete, MultiDiscrete)): + prev_a = one_hot(prev_a, self.action_space) + prev_a_r.append( + tf.reshape(tf.cast(prev_a, tf.float32), [-1, self.action_dim]) + ) + # Prev rewards. + if self.model_config["lstm_use_prev_reward"]: + prev_a_r.append( + tf.reshape( + tf.cast(input_dict[SampleBatch.PREV_REWARDS], tf.float32), [-1, 1] + ) + ) + + # Concat prev. actions + rewards to the "main" input. + if prev_a_r: + wrapped_out = tf.concat([wrapped_out] + prev_a_r, axis=1) + + # Push everything through our LSTM. + input_dict["obs_flat"] = wrapped_out + return super().forward(input_dict, state, seq_lens) + + @override(RecurrentNetwork) + def forward_rnn( + self, inputs: TensorType, state: List[TensorType], seq_lens: TensorType + ) -> Tuple[TensorType, List[TensorType]]: + model_out, self._value_out, h, c = self._rnn_model([inputs, seq_lens] + state) + return model_out, [h, c] + + @override(ModelV2) + def get_initial_state(self) -> List[np.ndarray]: + return [ + np.zeros(self.cell_size, np.float32), + np.zeros(self.cell_size, np.float32), + ] + + @override(ModelV2) + def value_function(self) -> TensorType: + return tf.reshape(self._value_out, [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/tf_action_dist.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/tf_action_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..683d1939776d3f346ec5f52e97ca5b95e049cdb6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/tf_action_dist.py @@ -0,0 +1,735 @@ +import functools +import gymnasium as gym +from math import log +import numpy as np +import tree # pip install dm_tree +from typing import Optional + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils import MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT, SMALL_NUMBER +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf, try_import_tfp +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import TensorType, List, Union, Tuple, ModelConfigDict + +tf1, tf, tfv = try_import_tf() +tfp = try_import_tfp() + + +@OldAPIStack +class TFActionDistribution(ActionDistribution): + """TF-specific extensions for building action distributions.""" + + @override(ActionDistribution) + def __init__(self, inputs: List[TensorType], model: ModelV2): + super().__init__(inputs, model) + self.sample_op = self._build_sample_op() + self.sampled_action_logp_op = self.logp(self.sample_op) + + def _build_sample_op(self) -> TensorType: + """Implement this instead of sample(), to enable op reuse. + + This is needed since the sample op is non-deterministic and is shared + between sample() and sampled_action_logp(). + """ + raise NotImplementedError + + @override(ActionDistribution) + def sample(self) -> TensorType: + """Draw a sample from the action distribution.""" + return self.sample_op + + @override(ActionDistribution) + def sampled_action_logp(self) -> TensorType: + """Returns the log probability of the sampled action.""" + return self.sampled_action_logp_op + + +@OldAPIStack +class Categorical(TFActionDistribution): + """Categorical distribution for discrete action spaces.""" + + def __init__( + self, inputs: List[TensorType], model: ModelV2 = None, temperature: float = 1.0 + ): + assert temperature > 0.0, "Categorical `temperature` must be > 0.0!" + # Allow softmax formula w/ temperature != 1.0: + # Divide inputs by temperature. + super().__init__(inputs / temperature, model) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + return tf.math.argmax(self.inputs, axis=1) + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + return -tf.nn.sparse_softmax_cross_entropy_with_logits( + logits=self.inputs, labels=tf.cast(x, tf.int32) + ) + + @override(ActionDistribution) + def entropy(self) -> TensorType: + a0 = self.inputs - tf.reduce_max(self.inputs, axis=1, keepdims=True) + ea0 = tf.exp(a0) + z0 = tf.reduce_sum(ea0, axis=1, keepdims=True) + p0 = ea0 / z0 + return tf.reduce_sum(p0 * (tf.math.log(z0) - a0), axis=1) + + @override(ActionDistribution) + def kl(self, other: ActionDistribution) -> TensorType: + a0 = self.inputs - tf.reduce_max(self.inputs, axis=1, keepdims=True) + a1 = other.inputs - tf.reduce_max(other.inputs, axis=1, keepdims=True) + ea0 = tf.exp(a0) + ea1 = tf.exp(a1) + z0 = tf.reduce_sum(ea0, axis=1, keepdims=True) + z1 = tf.reduce_sum(ea1, axis=1, keepdims=True) + p0 = ea0 / z0 + return tf.reduce_sum(p0 * (a0 - tf.math.log(z0) - a1 + tf.math.log(z1)), axis=1) + + @override(TFActionDistribution) + def _build_sample_op(self) -> TensorType: + return tf.squeeze(tf.random.categorical(self.inputs, 1), axis=1) + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape(action_space, model_config): + return action_space.n + + +@OldAPIStack +def get_categorical_class_with_temperature(t: float): + """Categorical distribution class that has customized default temperature.""" + + class CategoricalWithTemperature(Categorical): + def __init__(self, inputs, model=None, temperature=t): + super().__init__(inputs, model, temperature) + + return CategoricalWithTemperature + + +@OldAPIStack +class MultiCategorical(TFActionDistribution): + """MultiCategorical distribution for MultiDiscrete action spaces.""" + + def __init__( + self, + inputs: List[TensorType], + model: ModelV2, + input_lens: Union[List[int], np.ndarray, Tuple[int, ...]], + action_space=None, + ): + # skip TFActionDistribution init + ActionDistribution.__init__(self, inputs, model) + self.cats = [ + Categorical(input_, model) + for input_ in tf.split(inputs, input_lens, axis=1) + ] + self.action_space = action_space + if self.action_space is None: + self.action_space = gym.spaces.MultiDiscrete( + [c.inputs.shape[1] for c in self.cats] + ) + self.sample_op = self._build_sample_op() + self.sampled_action_logp_op = self.logp(self.sample_op) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + sample_ = tf.stack([cat.deterministic_sample() for cat in self.cats], axis=1) + if isinstance(self.action_space, gym.spaces.Box): + return tf.cast( + tf.reshape(sample_, [-1] + list(self.action_space.shape)), + self.action_space.dtype, + ) + return sample_ + + @override(ActionDistribution) + def logp(self, actions: TensorType) -> TensorType: + # If tensor is provided, unstack it into list. + if isinstance(actions, tf.Tensor): + if isinstance(self.action_space, gym.spaces.Box): + actions = tf.reshape( + actions, [-1, int(np.prod(self.action_space.shape))] + ) + elif isinstance(self.action_space, gym.spaces.MultiDiscrete): + actions.set_shape((None, len(self.cats))) + actions = tf.unstack(tf.cast(actions, tf.int32), axis=1) + logps = tf.stack([cat.logp(act) for cat, act in zip(self.cats, actions)]) + return tf.reduce_sum(logps, axis=0) + + @override(ActionDistribution) + def multi_entropy(self) -> TensorType: + return tf.stack([cat.entropy() for cat in self.cats], axis=1) + + @override(ActionDistribution) + def entropy(self) -> TensorType: + return tf.reduce_sum(self.multi_entropy(), axis=1) + + @override(ActionDistribution) + def multi_kl(self, other: ActionDistribution) -> TensorType: + return tf.stack( + [cat.kl(oth_cat) for cat, oth_cat in zip(self.cats, other.cats)], axis=1 + ) + + @override(ActionDistribution) + def kl(self, other: ActionDistribution) -> TensorType: + return tf.reduce_sum(self.multi_kl(other), axis=1) + + @override(TFActionDistribution) + def _build_sample_op(self) -> TensorType: + sample_op = tf.stack([cat.sample() for cat in self.cats], axis=1) + if isinstance(self.action_space, gym.spaces.Box): + return tf.cast( + tf.reshape(sample_op, [-1] + list(self.action_space.shape)), + dtype=self.action_space.dtype, + ) + return sample_op + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + # Int Box. + if isinstance(action_space, gym.spaces.Box): + assert action_space.dtype.name.startswith("int") + low_ = np.min(action_space.low) + high_ = np.max(action_space.high) + assert np.all(action_space.low == low_) + assert np.all(action_space.high == high_) + return np.prod(action_space.shape, dtype=np.int32) * (high_ - low_ + 1) + # MultiDiscrete space. + else: + # nvec is already integer, so no casting needed. + return np.sum(action_space.nvec) + + +@OldAPIStack +class SlateMultiCategorical(Categorical): + """MultiCategorical distribution for MultiDiscrete action spaces. + + The action space must be uniform, meaning all nvec items have the same size, e.g. + MultiDiscrete([10, 10, 10]), where 10 is the number of candidates to pick from + and 3 is the slate size (pick 3 out of 10). When picking candidates, no candidate + must be picked more than once. + """ + + def __init__( + self, + inputs: List[TensorType], + model: ModelV2 = None, + temperature: float = 1.0, + action_space: Optional[gym.spaces.MultiDiscrete] = None, + all_slates=None, + ): + assert temperature > 0.0, "Categorical `temperature` must be > 0.0!" + # Allow softmax formula w/ temperature != 1.0: + # Divide inputs by temperature. + super().__init__(inputs / temperature, model) + self.action_space = action_space + # Assert uniformness of the action space (all discrete buckets have the same + # size). + assert isinstance(self.action_space, gym.spaces.MultiDiscrete) and all( + n == self.action_space.nvec[0] for n in self.action_space.nvec + ) + self.all_slates = all_slates + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + # Get a sample from the underlying Categorical (batch of ints). + sample = super().deterministic_sample() + # Use the sampled ints to pick the actual slates. + return tf.gather(self.all_slates, sample) + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + # TODO: Implement. + return tf.ones_like(self.inputs[:, 0]) + + +@OldAPIStack +class GumbelSoftmax(TFActionDistribution): + """GumbelSoftmax distr. (for differentiable sampling in discr. actions + + The Gumbel Softmax distribution [1] (also known as the Concrete [2] + distribution) is a close cousin of the relaxed one-hot categorical + distribution, whose tfp implementation we will use here plus + adjusted `sample_...` and `log_prob` methods. See discussion at [0]. + + [0] https://stackoverflow.com/questions/56226133/ + soft-actor-critic-with-discrete-action-space + + [1] Categorical Reparametrization with Gumbel-Softmax (Jang et al, 2017): + https://arxiv.org/abs/1611.01144 + [2] The Concrete Distribution: A Continuous Relaxation of Discrete Random + Variables (Maddison et al, 2017) https://arxiv.org/abs/1611.00712 + """ + + def __init__( + self, inputs: List[TensorType], model: ModelV2 = None, temperature: float = 1.0 + ): + """Initializes a GumbelSoftmax distribution. + + Args: + temperature: Temperature parameter. For low temperatures, + the expected value approaches a categorical random variable. + For high temperatures, the expected value approaches a uniform + distribution. + """ + assert temperature >= 0.0 + self.dist = tfp.distributions.RelaxedOneHotCategorical( + temperature=temperature, logits=inputs + ) + self.probs = tf.nn.softmax(self.dist._distribution.logits) + super().__init__(inputs, model) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + # Return the dist object's prob values. + return self.probs + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + # Override since the implementation of tfp.RelaxedOneHotCategorical + # yields positive values. + if x.shape != self.dist.logits.shape: + values = tf.one_hot( + x, self.dist.logits.shape.as_list()[-1], dtype=tf.float32 + ) + assert values.shape == self.dist.logits.shape, ( + values.shape, + self.dist.logits.shape, + ) + + # [0]'s implementation (see line below) seems to be an approximation + # to the actual Gumbel Softmax density. + return -tf.reduce_sum( + -x * tf.nn.log_softmax(self.dist.logits, axis=-1), axis=-1 + ) + + @override(TFActionDistribution) + def _build_sample_op(self) -> TensorType: + return self.dist.sample() + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return action_space.n + + +@OldAPIStack +class DiagGaussian(TFActionDistribution): + """Action distribution where each vector element is a gaussian. + + The first half of the input vector defines the gaussian means, and the + second half the gaussian standard deviations. + """ + + def __init__( + self, + inputs: List[TensorType], + model: ModelV2, + *, + action_space: Optional[gym.spaces.Space] = None + ): + mean, log_std = tf.split(inputs, 2, axis=1) + self.mean = mean + self.log_std = log_std + self.std = tf.exp(log_std) + # Remember to squeeze action samples in case action space is Box(shape) + self.zero_action_dim = action_space and action_space.shape == () + super().__init__(inputs, model) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + return self.mean + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + # Cover case where action space is Box(shape=()). + if int(tf.shape(x).shape[0]) == 1: + x = tf.expand_dims(x, axis=1) + return ( + -0.5 + * tf.reduce_sum( + tf.math.square((tf.cast(x, tf.float32) - self.mean) / self.std), axis=1 + ) + - 0.5 * np.log(2.0 * np.pi) * tf.cast(tf.shape(x)[1], tf.float32) + - tf.reduce_sum(self.log_std, axis=1) + ) + + @override(ActionDistribution) + def kl(self, other: ActionDistribution) -> TensorType: + assert isinstance(other, DiagGaussian) + return tf.reduce_sum( + other.log_std + - self.log_std + + (tf.math.square(self.std) + tf.math.square(self.mean - other.mean)) + / (2.0 * tf.math.square(other.std)) + - 0.5, + axis=1, + ) + + @override(ActionDistribution) + def entropy(self) -> TensorType: + return tf.reduce_sum(self.log_std + 0.5 * np.log(2.0 * np.pi * np.e), axis=1) + + @override(TFActionDistribution) + def _build_sample_op(self) -> TensorType: + sample = self.mean + self.std * tf.random.normal(tf.shape(self.mean)) + if self.zero_action_dim: + return tf.squeeze(sample, axis=-1) + return sample + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) * 2 + + +@OldAPIStack +class SquashedGaussian(TFActionDistribution): + """A tanh-squashed Gaussian distribution defined by: mean, std, low, high. + + The distribution will never return low or high exactly, but + `low`+SMALL_NUMBER or `high`-SMALL_NUMBER respectively. + """ + + def __init__( + self, + inputs: List[TensorType], + model: ModelV2, + low: float = -1.0, + high: float = 1.0, + ): + """Parameterizes the distribution via `inputs`. + + Args: + low: The lowest possible sampling value + (excluding this value). + high: The highest possible sampling value + (excluding this value). + """ + assert tfp is not None + mean, log_std = tf.split(inputs, 2, axis=-1) + # Clip `scale` values (coming from NN) to reasonable values. + log_std = tf.clip_by_value(log_std, MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT) + std = tf.exp(log_std) + self.distr = tfp.distributions.Normal(loc=mean, scale=std) + assert np.all(np.less(low, high)) + self.low = low + self.high = high + super().__init__(inputs, model) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + mean = self.distr.mean() + return self._squash(mean) + + @override(TFActionDistribution) + def _build_sample_op(self) -> TensorType: + return self._squash(self.distr.sample()) + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + # Unsquash values (from [low,high] to ]-inf,inf[) + unsquashed_values = tf.cast(self._unsquash(x), self.inputs.dtype) + # Get log prob of unsquashed values from our Normal. + log_prob_gaussian = self.distr.log_prob(unsquashed_values) + # For safety reasons, clamp somehow, only then sum up. + log_prob_gaussian = tf.clip_by_value(log_prob_gaussian, -100, 100) + log_prob_gaussian = tf.reduce_sum(log_prob_gaussian, axis=-1) + # Get log-prob for squashed Gaussian. + unsquashed_values_tanhd = tf.math.tanh(unsquashed_values) + log_prob = log_prob_gaussian - tf.reduce_sum( + tf.math.log(1 - unsquashed_values_tanhd**2 + SMALL_NUMBER), axis=-1 + ) + return log_prob + + def sample_logp(self): + z = self.distr.sample() + actions = self._squash(z) + return actions, tf.reduce_sum( + self.distr.log_prob(z) - tf.math.log(1 - actions * actions + SMALL_NUMBER), + axis=-1, + ) + + @override(ActionDistribution) + def entropy(self) -> TensorType: + raise ValueError("Entropy not defined for SquashedGaussian!") + + @override(ActionDistribution) + def kl(self, other: ActionDistribution) -> TensorType: + raise ValueError("KL not defined for SquashedGaussian!") + + def _squash(self, raw_values: TensorType) -> TensorType: + # Returned values are within [low, high] (including `low` and `high`). + squashed = ((tf.math.tanh(raw_values) + 1.0) / 2.0) * ( + self.high - self.low + ) + self.low + return tf.clip_by_value(squashed, self.low, self.high) + + def _unsquash(self, values: TensorType) -> TensorType: + normed_values = (values - self.low) / (self.high - self.low) * 2.0 - 1.0 + # Stabilize input to atanh. + save_normed_values = tf.clip_by_value( + normed_values, -1.0 + SMALL_NUMBER, 1.0 - SMALL_NUMBER + ) + unsquashed = tf.math.atanh(save_normed_values) + return unsquashed + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) * 2 + + +@OldAPIStack +class Beta(TFActionDistribution): + """ + A Beta distribution is defined on the interval [0, 1] and parameterized by + shape parameters alpha and beta (also called concentration parameters). + + PDF(x; alpha, beta) = x**(alpha - 1) (1 - x)**(beta - 1) / Z + with Z = Gamma(alpha) Gamma(beta) / Gamma(alpha + beta) + and Gamma(n) = (n - 1)! + """ + + def __init__( + self, + inputs: List[TensorType], + model: ModelV2, + low: float = 0.0, + high: float = 1.0, + ): + # Stabilize input parameters (possibly coming from a linear layer). + inputs = tf.clip_by_value(inputs, log(SMALL_NUMBER), -log(SMALL_NUMBER)) + inputs = tf.math.log(tf.math.exp(inputs) + 1.0) + 1.0 + self.low = low + self.high = high + alpha, beta = tf.split(inputs, 2, axis=-1) + # Note: concentration0==beta, concentration1=alpha (!) + self.dist = tfp.distributions.Beta(concentration1=alpha, concentration0=beta) + super().__init__(inputs, model) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + mean = self.dist.mean() + return self._squash(mean) + + @override(TFActionDistribution) + def _build_sample_op(self) -> TensorType: + return self._squash(self.dist.sample()) + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + unsquashed_values = self._unsquash(x) + return tf.math.reduce_sum(self.dist.log_prob(unsquashed_values), axis=-1) + + def _squash(self, raw_values: TensorType) -> TensorType: + return raw_values * (self.high - self.low) + self.low + + def _unsquash(self, values: TensorType) -> TensorType: + return (values - self.low) / (self.high - self.low) + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) * 2 + + +@OldAPIStack +class Deterministic(TFActionDistribution): + """Action distribution that returns the input values directly. + + This is similar to DiagGaussian with standard deviation zero (thus only + requiring the "mean" values as NN output). + """ + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + return self.inputs + + @override(TFActionDistribution) + def logp(self, x: TensorType) -> TensorType: + return tf.zeros_like(self.inputs) + + @override(TFActionDistribution) + def _build_sample_op(self) -> TensorType: + return self.inputs + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) + + +@OldAPIStack +class MultiActionDistribution(TFActionDistribution): + """Action distribution that operates on a set of actions. + + Args: + inputs (Tensor list): A list of tensors from which to compute samples. + """ + + def __init__( + self, inputs, model, *, child_distributions, input_lens, action_space, **kwargs + ): + ActionDistribution.__init__(self, inputs, model) + + self.action_space_struct = get_base_struct_from_space(action_space) + + self.input_lens = np.array(input_lens, dtype=np.int32) + split_inputs = tf.split(inputs, self.input_lens, axis=1) + self.flat_child_distributions = tree.map_structure( + lambda dist, input_: dist(input_, model, **kwargs), + child_distributions, + split_inputs, + ) + + @override(ActionDistribution) + def logp(self, x): + # Single tensor input (all merged). + if isinstance(x, (tf.Tensor, np.ndarray)): + split_indices = [] + for dist in self.flat_child_distributions: + if isinstance(dist, Categorical): + split_indices.append(1) + elif ( + isinstance(dist, MultiCategorical) and dist.action_space is not None + ): + split_indices.append(np.prod(dist.action_space.shape)) + else: + sample = dist.sample() + # Cover Box(shape=()) case. + if len(sample.shape) == 1: + split_indices.append(1) + else: + split_indices.append(tf.shape(sample)[1]) + split_x = tf.split(x, split_indices, axis=1) + # Structured or flattened (by single action component) input. + else: + split_x = tree.flatten(x) + + def map_(val, dist): + # Remove extra categorical dimension. + if isinstance(dist, Categorical): + val = tf.cast( + tf.squeeze(val, axis=-1) if len(val.shape) > 1 else val, tf.int32 + ) + return dist.logp(val) + + # Remove extra categorical dimension and take the logp of each + # component. + flat_logps = tree.map_structure(map_, split_x, self.flat_child_distributions) + + return functools.reduce(lambda a, b: a + b, flat_logps) + + @override(ActionDistribution) + def kl(self, other): + kl_list = [ + d.kl(o) + for d, o in zip( + self.flat_child_distributions, other.flat_child_distributions + ) + ] + return functools.reduce(lambda a, b: a + b, kl_list) + + @override(ActionDistribution) + def entropy(self): + entropy_list = [d.entropy() for d in self.flat_child_distributions] + return functools.reduce(lambda a, b: a + b, entropy_list) + + @override(ActionDistribution) + def sample(self): + child_distributions = tree.unflatten_as( + self.action_space_struct, self.flat_child_distributions + ) + return tree.map_structure(lambda s: s.sample(), child_distributions) + + @override(ActionDistribution) + def deterministic_sample(self): + child_distributions = tree.unflatten_as( + self.action_space_struct, self.flat_child_distributions + ) + return tree.map_structure( + lambda s: s.deterministic_sample(), child_distributions + ) + + @override(TFActionDistribution) + def sampled_action_logp(self): + p = self.flat_child_distributions[0].sampled_action_logp() + for c in self.flat_child_distributions[1:]: + p += c.sampled_action_logp() + return p + + @override(ActionDistribution) + def required_model_output_shape(self, action_space, model_config): + return np.sum(self.input_lens, dtype=np.int32) + + +@OldAPIStack +class Dirichlet(TFActionDistribution): + """Dirichlet distribution for continuous actions that are between + [0,1] and sum to 1. + + e.g. actions that represent resource allocation.""" + + def __init__(self, inputs: List[TensorType], model: ModelV2): + """Input is a tensor of logits. The exponential of logits is used to + parametrize the Dirichlet distribution as all parameters need to be + positive. An arbitrary small epsilon is added to the concentration + parameters to be zero due to numerical error. + + See issue #4440 for more details. + """ + self.epsilon = 1e-7 + concentration = tf.exp(inputs) + self.epsilon + self.dist = tf1.distributions.Dirichlet( + concentration=concentration, + validate_args=True, + allow_nan_stats=False, + ) + super().__init__(concentration, model) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + return tf.nn.softmax(self.dist.concentration) + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + # Support of Dirichlet are positive real numbers. x is already + # an array of positive numbers, but we clip to avoid zeros due to + # numerical errors. + x = tf.maximum(x, self.epsilon) + x = x / tf.reduce_sum(x, axis=-1, keepdims=True) + return self.dist.log_prob(x) + + @override(ActionDistribution) + def entropy(self) -> TensorType: + return self.dist.entropy() + + @override(ActionDistribution) + def kl(self, other: ActionDistribution) -> TensorType: + return self.dist.kl_divergence(other.dist) + + @override(TFActionDistribution) + def _build_sample_op(self) -> TensorType: + return self.dist.sample() + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/tf_modelv2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/tf_modelv2.py new file mode 100644 index 0000000000000000000000000000000000000000..7438796944248b443b0e3c91332275745a1ab467 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/tf_modelv2.py @@ -0,0 +1,142 @@ +import contextlib +import gymnasium as gym +import re +from typing import Dict, List, Union + +from ray.util import log_once +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import ModelConfigDict, TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class TFModelV2(ModelV2): + """TF version of ModelV2, which should contain a tf keras Model. + + Note that this class by itself is not a valid model unless you + implement forward() in a subclass.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + """Initializes a TFModelV2 instance. + + Here is an example implementation for a subclass + ``MyModelClass(TFModelV2)``:: + + def __init__(self, *args, **kwargs): + super(MyModelClass, self).__init__(*args, **kwargs) + input_layer = tf.keras.layers.Input(...) + hidden_layer = tf.keras.layers.Dense(...)(input_layer) + output_layer = tf.keras.layers.Dense(...)(hidden_layer) + value_layer = tf.keras.layers.Dense(...)(hidden_layer) + self.base_model = tf.keras.Model( + input_layer, [output_layer, value_layer]) + """ + super().__init__( + obs_space, action_space, num_outputs, model_config, name, framework="tf" + ) + + # Deprecated: TFModelV2 now automatically track their variables. + self.var_list = [] + + if tf1.executing_eagerly(): + self.graph = None + else: + self.graph = tf1.get_default_graph() + + def context(self) -> contextlib.AbstractContextManager: + """Returns a contextmanager for the current TF graph.""" + if self.graph: + return self.graph.as_default() + else: + return ModelV2.context(self) + + def update_ops(self) -> List[TensorType]: + """Return the list of update ops for this model. + + For example, this should include any BatchNorm update ops.""" + return [] + + def register_variables(self, variables: List[TensorType]) -> None: + """Register the given list of variables with this model.""" + if log_once("deprecated_tfmodelv2_register_variables"): + deprecation_warning(old="TFModelV2.register_variables", error=False) + self.var_list.extend(variables) + + @override(ModelV2) + def variables( + self, as_dict: bool = False + ) -> Union[List[TensorType], Dict[str, TensorType]]: + if as_dict: + # Old way using `register_variables`. + if self.var_list: + return {v.name: v for v in self.var_list} + # New way: Automatically determine the var tree. + else: + return self._find_sub_modules("", self.__dict__) + + # Old way using `register_variables`. + if self.var_list: + return list(self.var_list) + # New way: Automatically determine the var tree. + else: + return list(self.variables(as_dict=True).values()) + + @override(ModelV2) + def trainable_variables( + self, as_dict: bool = False + ) -> Union[List[TensorType], Dict[str, TensorType]]: + if as_dict: + return { + k: v for k, v in self.variables(as_dict=True).items() if v.trainable + } + return [v for v in self.variables() if v.trainable] + + @staticmethod + def _find_sub_modules(current_key, struct): + # Keras Model: key=k + "." + var-name (replace '/' by '.'). + if isinstance(struct, tf.keras.models.Model) or isinstance(struct, tf.Module): + ret = {} + for var in struct.variables: + name = re.sub("/", ".", var.name) + key = current_key + "." + name + ret[key] = var + return ret + # Other TFModelV2: Include its vars into ours. + elif isinstance(struct, TFModelV2): + return { + current_key + "." + key: var + for key, var in struct.variables(as_dict=True).items() + } + # tf.Variable + elif isinstance(struct, tf.Variable): + return {current_key: struct} + # List/Tuple. + elif isinstance(struct, (tuple, list)): + ret = {} + for i, value in enumerate(struct): + sub_vars = TFModelV2._find_sub_modules( + current_key + "_{}".format(i), value + ) + ret.update(sub_vars) + return ret + # Dict. + elif isinstance(struct, dict): + if current_key: + current_key += "_" + ret = {} + for key, value in struct.items(): + sub_vars = TFModelV2._find_sub_modules(current_key + str(key), value) + ret.update(sub_vars) + return ret + return {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/visionnet.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/visionnet.py new file mode 100644 index 0000000000000000000000000000000000000000..69124c9e2e61ef48272dfcbae99503db13a98b07 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/tf/visionnet.py @@ -0,0 +1,264 @@ +import gymnasium as gym +from typing import Dict, List + +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.models.tf.misc import normc_initializer +from ray.rllib.models.utils import get_activation_fn, get_filter_config +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import ModelConfigDict, TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class VisionNetwork(TFModelV2): + """Generic vision network implemented in ModelV2 API. + + An additional post-conv fully connected stack can be added and configured + via the config keys: + `post_fcnet_hiddens`: Dense layer sizes after the Conv2D stack. + `post_fcnet_activation`: Activation function to use for this FC stack. + """ + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + if not model_config.get("conv_filters"): + model_config["conv_filters"] = get_filter_config(obs_space.shape) + + super(VisionNetwork, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + + activation = get_activation_fn( + self.model_config.get("conv_activation"), framework="tf" + ) + filters = self.model_config["conv_filters"] + assert len(filters) > 0, "Must provide at least 1 entry in `conv_filters`!" + + # Post FC net config. + post_fcnet_hiddens = model_config.get("post_fcnet_hiddens", []) + post_fcnet_activation = get_activation_fn( + model_config.get("post_fcnet_activation"), framework="tf" + ) + + no_final_linear = self.model_config.get("no_final_linear") + vf_share_layers = self.model_config.get("vf_share_layers") + + input_shape = obs_space.shape + self.data_format = "channels_last" + + inputs = tf.keras.layers.Input(shape=input_shape, name="observations") + last_layer = inputs + # Whether the last layer is the output of a Flattened (rather than + # a n x (1,1) Conv2D). + self.last_layer_is_flattened = False + + # Build the action layers + for i, (out_size, kernel, stride) in enumerate(filters[:-1], 1): + last_layer = tf.keras.layers.Conv2D( + out_size, + kernel, + strides=stride + if isinstance(stride, (list, tuple)) + else (stride, stride), + activation=activation, + padding="same", + data_format="channels_last", + name="conv{}".format(i), + )(last_layer) + + out_size, kernel, stride = filters[-1] + + # No final linear: Last layer has activation function and exits with + # num_outputs nodes (this could be a 1x1 conv or a FC layer, depending + # on `post_fcnet_...` settings). + if no_final_linear and num_outputs: + last_layer = tf.keras.layers.Conv2D( + out_size if post_fcnet_hiddens else num_outputs, + kernel, + strides=stride + if isinstance(stride, (list, tuple)) + else (stride, stride), + activation=activation, + padding="valid", + data_format="channels_last", + name="conv_out", + )(last_layer) + # Add (optional) post-fc-stack after last Conv2D layer. + layer_sizes = post_fcnet_hiddens[:-1] + ( + [num_outputs] if post_fcnet_hiddens else [] + ) + feature_out = last_layer + + for i, out_size in enumerate(layer_sizes): + feature_out = last_layer + last_layer = tf.keras.layers.Dense( + out_size, + name="post_fcnet_{}".format(i), + activation=post_fcnet_activation, + kernel_initializer=normc_initializer(1.0), + )(last_layer) + + # Finish network normally (w/o overriding last layer size with + # `num_outputs`), then add another linear one of size `num_outputs`. + else: + last_layer = tf.keras.layers.Conv2D( + out_size, + kernel, + strides=stride + if isinstance(stride, (list, tuple)) + else (stride, stride), + activation=activation, + padding="valid", + data_format="channels_last", + name="conv{}".format(len(filters)), + )(last_layer) + + # num_outputs defined. Use that to create an exact + # `num_output`-sized (1,1)-Conv2D. + if num_outputs: + if post_fcnet_hiddens: + last_cnn = last_layer = tf.keras.layers.Conv2D( + post_fcnet_hiddens[0], + [1, 1], + activation=post_fcnet_activation, + padding="same", + data_format="channels_last", + name="conv_out", + )(last_layer) + # Add (optional) post-fc-stack after last Conv2D layer. + for i, out_size in enumerate( + post_fcnet_hiddens[1:] + [num_outputs] + ): + feature_out = last_layer + last_layer = tf.keras.layers.Dense( + out_size, + name="post_fcnet_{}".format(i + 1), + activation=post_fcnet_activation + if i < len(post_fcnet_hiddens) - 1 + else None, + kernel_initializer=normc_initializer(1.0), + )(last_layer) + else: + feature_out = last_layer + last_cnn = last_layer = tf.keras.layers.Conv2D( + num_outputs, + [1, 1], + activation=None, + padding="same", + data_format="channels_last", + name="conv_out", + )(last_layer) + + if last_cnn.shape[1] != 1 or last_cnn.shape[2] != 1: + raise ValueError( + "Given `conv_filters` ({}) do not result in a [B, 1, " + "1, {} (`num_outputs`)] shape (but in {})! Please " + "adjust your Conv2D stack such that the dims 1 and 2 " + "are both 1.".format( + self.model_config["conv_filters"], + self.num_outputs, + list(last_cnn.shape), + ) + ) + + # num_outputs not known -> Flatten, then set self.num_outputs + # to the resulting number of nodes. + else: + self.last_layer_is_flattened = True + last_layer = tf.keras.layers.Flatten(data_format="channels_last")( + last_layer + ) + + # Add (optional) post-fc-stack after last Conv2D layer. + for i, out_size in enumerate(post_fcnet_hiddens): + last_layer = tf.keras.layers.Dense( + out_size, + name="post_fcnet_{}".format(i), + activation=post_fcnet_activation, + kernel_initializer=normc_initializer(1.0), + )(last_layer) + feature_out = last_layer + self.num_outputs = last_layer.shape[1] + logits_out = last_layer + + # Build the value layers + if vf_share_layers: + if not self.last_layer_is_flattened: + feature_out = tf.keras.layers.Lambda( + lambda x: tf.squeeze(x, axis=[1, 2]) + )(feature_out) + value_out = tf.keras.layers.Dense( + 1, + name="value_out", + activation=None, + kernel_initializer=normc_initializer(0.01), + )(feature_out) + else: + # build a parallel set of hidden layers for the value net + last_layer = inputs + for i, (out_size, kernel, stride) in enumerate(filters[:-1], 1): + last_layer = tf.keras.layers.Conv2D( + out_size, + kernel, + strides=stride + if isinstance(stride, (list, tuple)) + else (stride, stride), + activation=activation, + padding="same", + data_format="channels_last", + name="conv_value_{}".format(i), + )(last_layer) + out_size, kernel, stride = filters[-1] + last_layer = tf.keras.layers.Conv2D( + out_size, + kernel, + strides=stride + if isinstance(stride, (list, tuple)) + else (stride, stride), + activation=activation, + padding="valid", + data_format="channels_last", + name="conv_value_{}".format(len(filters)), + )(last_layer) + last_layer = tf.keras.layers.Conv2D( + 1, + [1, 1], + activation=None, + padding="same", + data_format="channels_last", + name="conv_value_out", + )(last_layer) + value_out = tf.keras.layers.Lambda(lambda x: tf.squeeze(x, axis=[1, 2]))( + last_layer + ) + + self.base_model = tf.keras.Model(inputs, [logits_out, value_out]) + + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + obs = input_dict["obs"] + if self.data_format == "channels_first": + obs = tf.transpose(obs, [0, 2, 3, 1]) + # Explicit cast to float32 needed in eager. + model_out, self._value_out = self.base_model(tf.cast(obs, tf.float32)) + # Our last layer is already flat. + if self.last_layer_is_flattened: + return model_out, state + # Last layer is a n x [1,1] Conv2D -> Flatten. + else: + return tf.squeeze(model_out, axis=[1, 2]), state + + def value_function(self) -> TensorType: + return tf.reshape(self._value_out, [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abbe5ef604646d8de477335e18c0bc4c88363b2c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__init__.py @@ -0,0 +1,12 @@ +# from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +# from ray.rllib.models.torch.fcnet import FullyConnectedNetwork +# from ray.rllib.models.torch.recurrent_net import \ +# RecurrentNetwork +# from ray.rllib.models.torch.visionnet import VisionNetwork + +# __all__ = [ +# "FullyConnectedNetwork", +# "RecurrentNetwork", +# "TorchModelV2", +# "VisionNetwork", +# ] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cd574bc1a4267c0f322e44d221a31c7dde93443 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/attention_net.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/attention_net.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6597a8c13e221abfbbe5b9ca5edeb8dbc41926e5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/attention_net.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/complex_input_net.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/complex_input_net.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e18e7e3ea8621b7d7a561cbd854630d8b52078df Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/complex_input_net.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/fcnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/fcnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b93eeb6043e5864cc385f7cd1ab7ae469be9ab26 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/fcnet.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/mingpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/mingpt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f4ff6a994102c3add03c32c51e1c9dd1e58204c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/mingpt.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/misc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e395e11174ae294663dbd924a9af59c2cf612906 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/misc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/recurrent_net.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/recurrent_net.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eff74e7c9d540955ff06c04663297fd87b10cb94 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/recurrent_net.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_action_dist.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_action_dist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..867557131b68593453821912f59c13717f9603c3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_action_dist.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_distributions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_distributions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..173e7fb7fb08852784252c62baf1699cc13b0073 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_distributions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_modelv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_modelv2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e98fc22577228857e3d0d861d370a8300c0ef04 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/torch_modelv2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/visionnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/visionnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2577b06603163c4541a31e2e53bd1e8ca6203708 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/__pycache__/visionnet.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/attention_net.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/attention_net.py new file mode 100644 index 0000000000000000000000000000000000000000..2382a4da1381a7dad748155498578009b13170e0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/attention_net.py @@ -0,0 +1,457 @@ +""" +[1] - Attention Is All You Need - Vaswani, Jones, Shazeer, Parmar, + Uszkoreit, Gomez, Kaiser - Google Brain/Research, U Toronto - 2017. + https://arxiv.org/pdf/1706.03762.pdf +[2] - Stabilizing Transformers for Reinforcement Learning - E. Parisotto + et al. - DeepMind - 2019. https://arxiv.org/pdf/1910.06764.pdf +[3] - Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. + Z. Dai, Z. Yang, et al. - Carnegie Mellon U - 2019. + https://www.aclweb.org/anthology/P19-1285.pdf +""" +import gymnasium as gym +from gymnasium.spaces import Box, Discrete, MultiDiscrete +import numpy as np +import tree # pip install dm_tree +from typing import Dict, Optional, Union + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.modules import ( + GRUGate, + RelativeMultiHeadAttention, + SkipConnection, +) +from ray.rllib.models.torch.recurrent_net import RecurrentNetwork +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.torch_utils import flatten_inputs_to_1d_tensor, one_hot +from ray.rllib.utils.typing import ModelConfigDict, TensorType, List +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util import log_once + +torch, nn = try_import_torch() + + +@OldAPIStack +class GTrXLNet(RecurrentNetwork, nn.Module): + """A GTrXL net Model described in [2]. + + This is still in an experimental phase. + Can be used as a drop-in replacement for LSTMs in PPO and IMPALA. + + To use this network as a replacement for an RNN, configure your Algorithm + as follows: + + Examples: + >> config["model"]["custom_model"] = GTrXLNet + >> config["model"]["max_seq_len"] = 10 + >> config["model"]["custom_model_config"] = { + >> num_transformer_units=1, + >> attention_dim=32, + >> num_heads=2, + >> memory_tau=50, + >> etc.. + >> } + """ + + def __init__( + self, + observation_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: Optional[int], + model_config: ModelConfigDict, + name: str, + *, + num_transformer_units: int = 1, + attention_dim: int = 64, + num_heads: int = 2, + memory_inference: int = 50, + memory_training: int = 50, + head_dim: int = 32, + position_wise_mlp_dim: int = 32, + init_gru_gate_bias: float = 2.0 + ): + """Initializes a GTrXLNet. + + Args: + num_transformer_units: The number of Transformer repeats to + use (denoted L in [2]). + attention_dim: The input and output dimensions of one + Transformer unit. + num_heads: The number of attention heads to use in parallel. + Denoted as `H` in [3]. + memory_inference: The number of timesteps to concat (time + axis) and feed into the next transformer unit as inference + input. The first transformer unit will receive this number of + past observations (plus the current one), instead. + memory_training: The number of timesteps to concat (time + axis) and feed into the next transformer unit as training + input (plus the actual input sequence of len=max_seq_len). + The first transformer unit will receive this number of + past observations (plus the input sequence), instead. + head_dim: The dimension of a single(!) attention head within + a multi-head attention unit. Denoted as `d` in [3]. + position_wise_mlp_dim: The dimension of the hidden layer + within the position-wise MLP (after the multi-head attention + block within one Transformer unit). This is the size of the + first of the two layers within the PositionwiseFeedforward. The + second layer always has size=`attention_dim`. + init_gru_gate_bias: Initial bias values for the GRU gates + (two GRUs per Transformer unit, one after the MHA, one after + the position-wise MLP). + """ + super().__init__( + observation_space, action_space, num_outputs, model_config, name + ) + + nn.Module.__init__(self) + + self.num_transformer_units = num_transformer_units + self.attention_dim = attention_dim + self.num_heads = num_heads + self.memory_inference = memory_inference + self.memory_training = memory_training + self.head_dim = head_dim + self.max_seq_len = model_config["max_seq_len"] + self.obs_dim = observation_space.shape[0] + + self.linear_layer = SlimFC(in_size=self.obs_dim, out_size=self.attention_dim) + + self.layers = [self.linear_layer] + + attention_layers = [] + # 2) Create L Transformer blocks according to [2]. + for i in range(self.num_transformer_units): + # RelativeMultiHeadAttention part. + MHA_layer = SkipConnection( + RelativeMultiHeadAttention( + in_dim=self.attention_dim, + out_dim=self.attention_dim, + num_heads=num_heads, + head_dim=head_dim, + input_layernorm=True, + output_activation=nn.ReLU, + ), + fan_in_layer=GRUGate(self.attention_dim, init_gru_gate_bias), + ) + + # Position-wise MultiLayerPerceptron part. + E_layer = SkipConnection( + nn.Sequential( + torch.nn.LayerNorm(self.attention_dim), + SlimFC( + in_size=self.attention_dim, + out_size=position_wise_mlp_dim, + use_bias=False, + activation_fn=nn.ReLU, + ), + SlimFC( + in_size=position_wise_mlp_dim, + out_size=self.attention_dim, + use_bias=False, + activation_fn=nn.ReLU, + ), + ), + fan_in_layer=GRUGate(self.attention_dim, init_gru_gate_bias), + ) + + # Build a list of all attanlayers in order. + attention_layers.extend([MHA_layer, E_layer]) + + # Create a Sequential such that all parameters inside the attention + # layers are automatically registered with this top-level model. + self.attention_layers = nn.Sequential(*attention_layers) + self.layers.extend(attention_layers) + + # Final layers if num_outputs not None. + self.logits = None + self.values_out = None + # Last value output. + self._value_out = None + # Postprocess GTrXL output with another hidden layer. + if self.num_outputs is not None: + self.logits = SlimFC( + in_size=self.attention_dim, + out_size=self.num_outputs, + activation_fn=nn.ReLU, + ) + + # Value function used by all RLlib Torch RL implementations. + self.values_out = SlimFC( + in_size=self.attention_dim, out_size=1, activation_fn=None + ) + else: + self.num_outputs = self.attention_dim + + # Setup trajectory views (`memory-inference` x past memory outs). + for i in range(self.num_transformer_units): + space = Box(-1.0, 1.0, shape=(self.attention_dim,)) + self.view_requirements["state_in_{}".format(i)] = ViewRequirement( + "state_out_{}".format(i), + shift="-{}:-1".format(self.memory_inference), + # Repeat the incoming state every max-seq-len times. + batch_repeat_value=self.max_seq_len, + space=space, + ) + self.view_requirements["state_out_{}".format(i)] = ViewRequirement( + space=space, used_for_training=False + ) + + @override(ModelV2) + def forward( + self, input_dict, state: List[TensorType], seq_lens: TensorType + ) -> (TensorType, List[TensorType]): + assert seq_lens is not None + + # Add the needed batch rank (tf Models' Input requires this). + observations = input_dict[SampleBatch.OBS] + # Add the time dim to observations. + B = len(seq_lens) + T = observations.shape[0] // B + observations = torch.reshape( + observations, [-1, T] + list(observations.shape[1:]) + ) + + all_out = observations + memory_outs = [] + for i in range(len(self.layers)): + # MHA layers which need memory passed in. + if i % 2 == 1: + all_out = self.layers[i](all_out, memory=state[i // 2]) + # Either self.linear_layer (initial obs -> attn. dim layer) or + # MultiLayerPerceptrons. The output of these layers is always the + # memory for the next forward pass. + else: + all_out = self.layers[i](all_out) + memory_outs.append(all_out) + + # Discard last output (not needed as a memory since it's the last + # layer). + memory_outs = memory_outs[:-1] + + if self.logits is not None: + out = self.logits(all_out) + self._value_out = self.values_out(all_out) + out_dim = self.num_outputs + else: + out = all_out + out_dim = self.attention_dim + + return torch.reshape(out, [-1, out_dim]), [ + torch.reshape(m, [-1, self.attention_dim]) for m in memory_outs + ] + + # TODO: (sven) Deprecate this once trajectory view API has fully matured. + @override(RecurrentNetwork) + def get_initial_state(self) -> List[np.ndarray]: + return [] + + @override(ModelV2) + def value_function(self) -> TensorType: + assert ( + self._value_out is not None + ), "Must call forward first AND must have value branch!" + return torch.reshape(self._value_out, [-1]) + + +class AttentionWrapper(TorchModelV2, nn.Module): + """GTrXL wrapper serving as interface for ModelV2s that set use_attention.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + if log_once("deprecate_attention_wrapper_torch"): + deprecation_warning( + old="ray.rllib.models.torch.attention_net.AttentionWrapper" + ) + + nn.Module.__init__(self) + super().__init__(obs_space, action_space, None, model_config, name) + + self.use_n_prev_actions = model_config["attention_use_n_prev_actions"] + self.use_n_prev_rewards = model_config["attention_use_n_prev_rewards"] + + self.action_space_struct = get_base_struct_from_space(self.action_space) + self.action_dim = 0 + + for space in tree.flatten(self.action_space_struct): + if isinstance(space, Discrete): + self.action_dim += space.n + elif isinstance(space, MultiDiscrete): + self.action_dim += np.sum(space.nvec) + elif space.shape is not None: + self.action_dim += int(np.prod(space.shape)) + else: + self.action_dim += int(len(space)) + + # Add prev-action/reward nodes to input to LSTM. + if self.use_n_prev_actions: + self.num_outputs += self.use_n_prev_actions * self.action_dim + if self.use_n_prev_rewards: + self.num_outputs += self.use_n_prev_rewards + + cfg = model_config + + self.attention_dim = cfg["attention_dim"] + + if self.num_outputs is not None: + in_space = gym.spaces.Box( + float("-inf"), float("inf"), shape=(self.num_outputs,), dtype=np.float32 + ) + else: + in_space = obs_space + + # Construct GTrXL sub-module w/ num_outputs=None (so it does not + # create a logits/value output; we'll do this ourselves in this wrapper + # here). + self.gtrxl = GTrXLNet( + in_space, + action_space, + None, + model_config, + "gtrxl", + num_transformer_units=cfg["attention_num_transformer_units"], + attention_dim=self.attention_dim, + num_heads=cfg["attention_num_heads"], + head_dim=cfg["attention_head_dim"], + memory_inference=cfg["attention_memory_inference"], + memory_training=cfg["attention_memory_training"], + position_wise_mlp_dim=cfg["attention_position_wise_mlp_dim"], + init_gru_gate_bias=cfg["attention_init_gru_gate_bias"], + ) + + # Set final num_outputs to correct value (depending on action space). + self.num_outputs = num_outputs + + # Postprocess GTrXL output with another hidden layer and compute + # values. + self._logits_branch = SlimFC( + in_size=self.attention_dim, + out_size=self.num_outputs, + activation_fn=None, + initializer=torch.nn.init.xavier_uniform_, + ) + self._value_branch = SlimFC( + in_size=self.attention_dim, + out_size=1, + activation_fn=None, + initializer=torch.nn.init.xavier_uniform_, + ) + + self.view_requirements = self.gtrxl.view_requirements + self.view_requirements["obs"].space = self.obs_space + + # Add prev-a/r to this model's view, if required. + if self.use_n_prev_actions: + self.view_requirements[SampleBatch.PREV_ACTIONS] = ViewRequirement( + SampleBatch.ACTIONS, + space=self.action_space, + shift="-{}:-1".format(self.use_n_prev_actions), + ) + if self.use_n_prev_rewards: + self.view_requirements[SampleBatch.PREV_REWARDS] = ViewRequirement( + SampleBatch.REWARDS, shift="-{}:-1".format(self.use_n_prev_rewards) + ) + + @override(RecurrentNetwork) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + assert seq_lens is not None + # Push obs through "unwrapped" net's `forward()` first. + wrapped_out, _ = self._wrapped_forward(input_dict, [], None) + + # Concat. prev-action/reward if required. + prev_a_r = [] + + # Prev actions. + if self.use_n_prev_actions: + prev_n_actions = input_dict[SampleBatch.PREV_ACTIONS] + # If actions are not processed yet (in their original form as + # have been sent to environment): + # Flatten/one-hot into 1D array. + if self.model_config["_disable_action_flattening"]: + # Merge prev n actions into flat tensor. + flat = flatten_inputs_to_1d_tensor( + prev_n_actions, + spaces_struct=self.action_space_struct, + time_axis=True, + ) + # Fold time-axis into flattened data. + flat = torch.reshape(flat, [flat.shape[0], -1]) + prev_a_r.append(flat) + # If actions are already flattened (but not one-hot'd yet!), + # one-hot discrete/multi-discrete actions here and concatenate the + # n most recent actions together. + else: + if isinstance(self.action_space, Discrete): + for i in range(self.use_n_prev_actions): + prev_a_r.append( + one_hot( + prev_n_actions[:, i].float(), space=self.action_space + ) + ) + elif isinstance(self.action_space, MultiDiscrete): + for i in range( + 0, self.use_n_prev_actions, self.action_space.shape[0] + ): + prev_a_r.append( + one_hot( + prev_n_actions[ + :, i : i + self.action_space.shape[0] + ].float(), + space=self.action_space, + ) + ) + else: + prev_a_r.append( + torch.reshape( + prev_n_actions.float(), + [-1, self.use_n_prev_actions * self.action_dim], + ) + ) + # Prev rewards. + if self.use_n_prev_rewards: + prev_a_r.append( + torch.reshape( + input_dict[SampleBatch.PREV_REWARDS].float(), + [-1, self.use_n_prev_rewards], + ) + ) + + # Concat prev. actions + rewards to the "main" input. + if prev_a_r: + wrapped_out = torch.cat([wrapped_out] + prev_a_r, dim=1) + + # Then through our GTrXL. + input_dict["obs_flat"] = input_dict["obs"] = wrapped_out + + self._features, memory_outs = self.gtrxl(input_dict, state, seq_lens) + model_out = self._logits_branch(self._features) + return model_out, memory_outs + + @override(ModelV2) + def get_initial_state(self) -> Union[List[np.ndarray], List[TensorType]]: + return [ + torch.zeros( + self.gtrxl.view_requirements["state_in_{}".format(i)].space.shape + ) + for i in range(self.gtrxl.num_transformer_units) + ] + + @override(ModelV2) + def value_function(self) -> TensorType: + assert self._features is not None, "Must call forward() first!" + return torch.reshape(self._value_branch(self._features), [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/complex_input_net.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/complex_input_net.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c81dba790c4f97f2c6ab5d2b765af0691005c8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/complex_input_net.py @@ -0,0 +1,237 @@ +from gymnasium.spaces import Box, Discrete, MultiDiscrete +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.models.torch.misc import ( + normc_initializer as torch_normc_initializer, + SlimFC, +) +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2, restore_original_dimensions +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.models.utils import get_filter_config +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.spaces.space_utils import flatten_space +from ray.rllib.utils.torch_utils import one_hot + +torch, nn = try_import_torch() + + +@OldAPIStack +class ComplexInputNetwork(TorchModelV2, nn.Module): + """TorchModelV2 concat'ing CNN outputs to flat input(s), followed by FC(s). + + Note: This model should be used for complex (Dict or Tuple) observation + spaces that have one or more image components. + + The data flow is as follows: + + `obs` (e.g. Tuple[img0, img1, discrete0]) -> `CNN0 + CNN1 + ONE-HOT` + `CNN0 + CNN1 + ONE-HOT` -> concat all flat outputs -> `out` + `out` -> (optional) FC-stack -> `out2` + `out2` -> action (logits) and value heads. + """ + + def __init__(self, obs_space, action_space, num_outputs, model_config, name): + self.original_space = ( + obs_space.original_space + if hasattr(obs_space, "original_space") + else obs_space + ) + + self.processed_obs_space = ( + self.original_space + if model_config.get("_disable_preprocessor_api") + else obs_space + ) + + nn.Module.__init__(self) + TorchModelV2.__init__( + self, self.original_space, action_space, num_outputs, model_config, name + ) + + self.flattened_input_space = flatten_space(self.original_space) + + # Atari type CNNs or IMPALA type CNNs (with residual layers)? + # self.cnn_type = self.model_config["custom_model_config"].get( + # "conv_type", "atari") + + # Build the CNN(s) given obs_space's image components. + self.cnns = nn.ModuleDict() + self.one_hot = nn.ModuleDict() + self.flatten_dims = {} + self.flatten = nn.ModuleDict() + concat_size = 0 + for i, component in enumerate(self.flattened_input_space): + i = str(i) + # Image space. + if len(component.shape) == 3 and isinstance(component, Box): + config = { + "conv_filters": model_config["conv_filters"] + if "conv_filters" in model_config + else get_filter_config(component.shape), + "conv_activation": model_config.get("conv_activation"), + "post_fcnet_hiddens": [], + } + # if self.cnn_type == "atari": + self.cnns[i] = ModelCatalog.get_model_v2( + component, + action_space, + num_outputs=None, + model_config=config, + framework="torch", + name="cnn_{}".format(i), + ) + # TODO (sven): add IMPALA-style option. + # else: + # cnn = TorchImpalaVisionNet( + # component, + # action_space, + # num_outputs=None, + # model_config=config, + # name="cnn_{}".format(i)) + + concat_size += self.cnns[i].num_outputs + self.add_module("cnn_{}".format(i), self.cnns[i]) + # Discrete|MultiDiscrete inputs -> One-hot encode. + elif isinstance(component, (Discrete, MultiDiscrete)): + if isinstance(component, Discrete): + size = component.n + else: + size = np.sum(component.nvec) + config = { + "fcnet_hiddens": model_config["fcnet_hiddens"], + "fcnet_activation": model_config.get("fcnet_activation"), + "post_fcnet_hiddens": [], + } + self.one_hot[i] = ModelCatalog.get_model_v2( + Box(-1.0, 1.0, (size,), np.float32), + action_space, + num_outputs=None, + model_config=config, + framework="torch", + name="one_hot_{}".format(i), + ) + concat_size += self.one_hot[i].num_outputs + self.add_module("one_hot_{}".format(i), self.one_hot[i]) + # Everything else (1D Box). + else: + size = int(np.prod(component.shape)) + config = { + "fcnet_hiddens": model_config["fcnet_hiddens"], + "fcnet_activation": model_config.get("fcnet_activation"), + "post_fcnet_hiddens": [], + } + self.flatten[i] = ModelCatalog.get_model_v2( + Box(-1.0, 1.0, (size,), np.float32), + action_space, + num_outputs=None, + model_config=config, + framework="torch", + name="flatten_{}".format(i), + ) + self.flatten_dims[i] = size + concat_size += self.flatten[i].num_outputs + self.add_module("flatten_{}".format(i), self.flatten[i]) + + # Optional post-concat FC-stack. + post_fc_stack_config = { + "fcnet_hiddens": model_config.get("post_fcnet_hiddens", []), + "fcnet_activation": model_config.get("post_fcnet_activation", "relu"), + } + self.post_fc_stack = ModelCatalog.get_model_v2( + Box(float("-inf"), float("inf"), shape=(concat_size,), dtype=np.float32), + self.action_space, + None, + post_fc_stack_config, + framework="torch", + name="post_fc_stack", + ) + + # Actions and value heads. + self.logits_layer = None + self.value_layer = None + self._value_out = None + + if num_outputs: + # Action-distribution head. + self.logits_layer = SlimFC( + in_size=self.post_fc_stack.num_outputs, + out_size=num_outputs, + activation_fn=None, + initializer=torch_normc_initializer(0.01), + ) + # Create the value branch model. + self.value_layer = SlimFC( + in_size=self.post_fc_stack.num_outputs, + out_size=1, + activation_fn=None, + initializer=torch_normc_initializer(0.01), + ) + else: + self.num_outputs = concat_size + + @override(ModelV2) + def forward(self, input_dict, state, seq_lens): + if SampleBatch.OBS in input_dict and "obs_flat" in input_dict: + orig_obs = input_dict[SampleBatch.OBS] + else: + orig_obs = restore_original_dimensions( + input_dict[SampleBatch.OBS], self.processed_obs_space, tensorlib="torch" + ) + # Push observations through the different components + # (CNNs, one-hot + FC, etc..). + outs = [] + for i, component in enumerate(tree.flatten(orig_obs)): + i = str(i) + if i in self.cnns: + cnn_out, _ = self.cnns[i](SampleBatch({SampleBatch.OBS: component})) + outs.append(cnn_out) + elif i in self.one_hot: + if component.dtype in [ + torch.int8, + torch.int16, + torch.int32, + torch.int64, + torch.uint8, + ]: + one_hot_in = { + SampleBatch.OBS: one_hot( + component, self.flattened_input_space[int(i)] + ) + } + else: + one_hot_in = {SampleBatch.OBS: component} + one_hot_out, _ = self.one_hot[i](SampleBatch(one_hot_in)) + outs.append(one_hot_out) + else: + nn_out, _ = self.flatten[i]( + SampleBatch( + { + SampleBatch.OBS: torch.reshape( + component, [-1, self.flatten_dims[i]] + ) + } + ) + ) + outs.append(nn_out) + + # Concat all outputs and the non-image inputs. + out = torch.cat(outs, dim=1) + # Push through (optional) FC-stack (this may be an empty stack). + out, _ = self.post_fc_stack(SampleBatch({SampleBatch.OBS: out})) + + # No logits/value branches. + if self.logits_layer is None: + return out, [] + + # Logits- and value branches. + logits, values = self.logits_layer(out), self.value_layer(out) + self._value_out = torch.reshape(values, [-1]) + return logits, [] + + @override(ModelV2) + def value_function(self): + return self._value_out diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/fcnet.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/fcnet.py new file mode 100644 index 0000000000000000000000000000000000000000..2ba907a54ed09b207c62a161ab54a27f89a281f4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/fcnet.py @@ -0,0 +1,160 @@ +import logging +import numpy as np +import gymnasium as gym + +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.models.torch.misc import SlimFC, AppendBiasLayer, normc_initializer +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import Dict, TensorType, List, ModelConfigDict + +torch, nn = try_import_torch() + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class FullyConnectedNetwork(TorchModelV2, nn.Module): + """Generic fully connected network.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + TorchModelV2.__init__( + self, obs_space, action_space, num_outputs, model_config, name + ) + nn.Module.__init__(self) + + hiddens = list(model_config.get("fcnet_hiddens", [])) + list( + model_config.get("post_fcnet_hiddens", []) + ) + activation = model_config.get("fcnet_activation") + if not model_config.get("fcnet_hiddens", []): + activation = model_config.get("post_fcnet_activation") + no_final_linear = model_config.get("no_final_linear") + self.vf_share_layers = model_config.get("vf_share_layers") + self.free_log_std = model_config.get("free_log_std") + # Generate free-floating bias variables for the second half of + # the outputs. + if self.free_log_std: + assert num_outputs % 2 == 0, ( + "num_outputs must be divisible by two", + num_outputs, + ) + num_outputs = num_outputs // 2 + + layers = [] + prev_layer_size = int(np.prod(obs_space.shape)) + self._logits = None + + # Create layers 0 to second-last. + for size in hiddens[:-1]: + layers.append( + SlimFC( + in_size=prev_layer_size, + out_size=size, + initializer=normc_initializer(1.0), + activation_fn=activation, + ) + ) + prev_layer_size = size + + # The last layer is adjusted to be of size num_outputs, but it's a + # layer with activation. + if no_final_linear and num_outputs: + layers.append( + SlimFC( + in_size=prev_layer_size, + out_size=num_outputs, + initializer=normc_initializer(1.0), + activation_fn=activation, + ) + ) + prev_layer_size = num_outputs + # Finish the layers with the provided sizes (`hiddens`), plus - + # iff num_outputs > 0 - a last linear layer of size num_outputs. + else: + if len(hiddens) > 0: + layers.append( + SlimFC( + in_size=prev_layer_size, + out_size=hiddens[-1], + initializer=normc_initializer(1.0), + activation_fn=activation, + ) + ) + prev_layer_size = hiddens[-1] + if num_outputs: + self._logits = SlimFC( + in_size=prev_layer_size, + out_size=num_outputs, + initializer=normc_initializer(0.01), + activation_fn=None, + ) + else: + self.num_outputs = ([int(np.prod(obs_space.shape))] + hiddens[-1:])[-1] + + # Layer to add the log std vars to the state-dependent means. + if self.free_log_std and self._logits: + self._append_free_log_std = AppendBiasLayer(num_outputs) + + self._hidden_layers = nn.Sequential(*layers) + + self._value_branch_separate = None + if not self.vf_share_layers: + # Build a parallel set of hidden layers for the value net. + prev_vf_layer_size = int(np.prod(obs_space.shape)) + vf_layers = [] + for size in hiddens: + vf_layers.append( + SlimFC( + in_size=prev_vf_layer_size, + out_size=size, + activation_fn=activation, + initializer=normc_initializer(1.0), + ) + ) + prev_vf_layer_size = size + self._value_branch_separate = nn.Sequential(*vf_layers) + + self._value_branch = SlimFC( + in_size=prev_layer_size, + out_size=1, + initializer=normc_initializer(0.01), + activation_fn=None, + ) + # Holds the current "base" output (before logits layer). + self._features = None + # Holds the last input, in case value branch is separate. + self._last_flat_in = None + + @override(TorchModelV2) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + obs = input_dict["obs_flat"].float() + self._last_flat_in = obs.reshape(obs.shape[0], -1) + self._features = self._hidden_layers(self._last_flat_in) + logits = self._logits(self._features) if self._logits else self._features + if self.free_log_std: + logits = self._append_free_log_std(logits) + return logits, state + + @override(TorchModelV2) + def value_function(self) -> TensorType: + assert self._features is not None, "must call forward() first" + if self._value_branch_separate: + out = self._value_branch( + self._value_branch_separate(self._last_flat_in) + ).squeeze(1) + else: + out = self._value_branch(self._features).squeeze(1) + return out diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/mingpt.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/mingpt.py new file mode 100644 index 0000000000000000000000000000000000000000..7e24cfdc730af4017c7d926d21785d5256e489ca --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/mingpt.py @@ -0,0 +1,303 @@ +# LICENSE: MIT +""" +Adapted from https://github.com/karpathy/minGPT + +Full definition of a GPT Language Model, all of it in this single file. +References: +1) the official GPT-2 TensorFlow implementation released by OpenAI: +https://github.com/openai/gpt-2/blob/master/src/model.py +2) huggingface/transformers PyTorch implementation: +https://github.com/huggingface/transformers/blob/main/src/transformers + /models/gpt2/modeling_gpt2.py +""" + +import math +from dataclasses import dataclass +from typing import Tuple + +import torch +import torch.nn as nn +from torch.nn import functional as F + +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.deprecation import Deprecated + + +@DeveloperAPI +@dataclass +class GPTConfig: + # block size must be provided + block_size: int + + # transformer config + n_layer: int = 12 + n_head: int = 12 + n_embed: int = 768 + + # dropout config + embed_pdrop: float = 0.1 + resid_pdrop: float = 0.1 + attn_pdrop: float = 0.1 + + +@Deprecated(error=False) +class NewGELU(nn.Module): + """ + Implementation of the GELU activation function currently in Google BERT + repo (identical to OpenAI GPT). + Reference: Gaussian Error Linear Units (GELU) paper: + https://arxiv.org/abs/1606.08415 + """ + + def forward(self, x): + return ( + 0.5 + * x + * ( + 1.0 + + torch.tanh( + math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0)) + ) + ) + ) + + +@Deprecated(error=False) +class CausalSelfAttention(nn.Module): + """ + Vanilla multi-head masked self-attention layer with a projection at the end. + It is possible to use torch.nn.MultiheadAttention here but I am including an + explicit implementation here to show that there is nothing too scary here. + """ + + def __init__(self, config: GPTConfig): + super().__init__() + assert config.n_embed % config.n_head == 0 + # key, query, value projections for all heads, but in a batch + self.c_attn = nn.Linear(config.n_embed, 3 * config.n_embed) + # output projection + self.c_proj = nn.Linear(config.n_embed, config.n_embed) + # regularization + self.attn_dropout = nn.Dropout(config.attn_pdrop) + self.resid_dropout = nn.Dropout(config.resid_pdrop) + # causal mask to ensure that attention is only applied to the left + # in the input sequence + self.register_buffer( + "bias", + torch.tril(torch.ones(config.block_size, config.block_size)).view( + 1, 1, config.block_size, config.block_size + ), + ) + self.n_head = config.n_head + self.n_embed = config.n_embed + + def forward(self, x, attention_masks=None): + # batch size, sequence length, embedding dimensionality (n_embed) + B, T, C = x.size() + + # calculate query, key, values for all heads in batch and move head + # forward to be the batch dim + q, k, v = self.c_attn(x).split(self.n_embed, dim=2) + # (B, nh, T, hs) + k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) + # (B, nh, T, hs) + q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) + # (B, nh, T, hs) + v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) + + # causal self-attention; Self-attend: + # (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T) + att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) + att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float("-inf")) + if attention_masks is not None: + att = att + attention_masks + att = F.softmax(att, dim=-1) + att = self.attn_dropout(att) + y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs) + # re-assemble all head outputs side by side + y = y.transpose(1, 2).contiguous().view(B, T, C) + + # output projection + y = self.resid_dropout(self.c_proj(y)) + return y, att + + +@Deprecated(error=False) +class Block(nn.Module): + """an unassuming Transformer block""" + + def __init__(self, config: GPTConfig): + super().__init__() + self.ln_1 = nn.LayerNorm(config.n_embed) + self.attn = CausalSelfAttention(config) + self.ln_2 = nn.LayerNorm(config.n_embed) + self.mlp = nn.ModuleDict( + dict( + c_fc=nn.Linear(config.n_embed, 4 * config.n_embed), + c_proj=nn.Linear(4 * config.n_embed, config.n_embed), + act=NewGELU(), + dropout=nn.Dropout(config.resid_pdrop), + ) + ) + + def forward(self, x, attention_masks=None): + # Multi-head attention sub-layer. + x_att, att = self.attn(self.ln_1(x), attention_masks=attention_masks) + # Residual of multi-head attention sub-layer. + x = x + x_att + + # Position-wise FFN sub-layer: fc + activation + fc + dropout + x_ffn = self.mlp.dropout(self.mlp.c_proj(self.mlp.act(self.mlp.c_fc(x)))) + # Residual of position-wise FFN sub-layer. + x = x + x_ffn + return x, att + + +@Deprecated(error=False) +def configure_gpt_optimizer( + model: nn.Module, + learning_rate: float, + weight_decay: float, + betas: Tuple[float, float] = (0.9, 0.95), + **kwargs, +) -> torch.optim.Optimizer: + """ + This long function is unfortunately doing something very simple and is + being very defensive: We are separating out all parameters of the model + into two buckets: those that will experience weight decay for regularization + and those that won't (biases, and layernorm/embedding weights). We are then + returning the PyTorch optimizer object. + """ + + # separate out all parameters to those that will and won't experience + # regularizing weight decay + decay = set() + no_decay = set() + whitelist_w_modules = (torch.nn.Linear,) + blacklist_w_modules = (torch.nn.LayerNorm, torch.nn.Embedding) + for mn, m in model.named_modules(): + for pn, p in m.named_parameters(): + fpn = "%s.%s" % (mn, pn) if mn else pn # full param name + # random note: because named_modules and named_parameters are + # recursive we will see the same tensors p many many times. but + # doing it this way allows us to know which parent module any + # tensor p belongs to... + if pn.endswith("bias"): + # all biases will not be decayed + no_decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, whitelist_w_modules): + # weights of whitelist modules will be weight decayed + decay.add(fpn) + elif pn.endswith("weight") and isinstance(m, blacklist_w_modules): + # weights of blacklist modules will NOT be weight decayed + no_decay.add(fpn) + + # validate that we considered every parameter + param_dict = dict(model.named_parameters()) + inter_params = decay & no_decay + union_params = decay | no_decay + assert ( + len(inter_params) == 0 + ), f"parameters {str(inter_params)} made it into both decay/no_decay sets!" + assert len(param_dict.keys() - union_params) == 0, ( + f"parameters {str(param_dict.keys() - union_params)} were not " + f"separated into either decay/no_decay set!" + ) + + # create the pytorch optimizer object + optim_groups = [ + { + "params": [param_dict[pn] for pn in sorted(decay)], + "weight_decay": weight_decay, + }, + { + "params": [param_dict[pn] for pn in sorted(no_decay)], + "weight_decay": 0.0, + }, + ] + optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **kwargs) + return optimizer + + +@Deprecated(error=False) +class GPT(nn.Module): + """GPT Transformer Model""" + + def __init__(self, config: GPTConfig): + super().__init__() + assert config.block_size is not None + self.block_size = config.block_size + + self.transformer = nn.ModuleDict( + dict( + drop=nn.Dropout(config.embed_pdrop), + h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]), + ln_f=nn.LayerNorm(config.n_embed), + ) + ) + + # init all weights, and apply a special scaled init to the residual + # projections, per GPT-2 paper + self.apply(self._init_weights) + for pn, p in self.named_parameters(): + if pn.endswith("c_proj.weight"): + torch.nn.init.normal_( + p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layer) + ) + + def _init_weights(self, module): + if isinstance(module, nn.Linear): + torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) + if module.bias is not None: + torch.nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) + elif isinstance(module, nn.LayerNorm): + torch.nn.init.zeros_(module.bias) + torch.nn.init.ones_(module.weight) + + def forward(self, input_embeds, attention_masks=None, return_attentions=False): + """ + input_embeds: [batch_size x seq_len x n_embed] + attention_masks: [batch_size x seq_len], 0 don't attend, 1 attend + """ + B, T, C = input_embeds.size() + assert T <= self.block_size, ( + f"Cannot forward sequence of length {T}, " + f"block size is only {self.block_size}" + ) + + if attention_masks is not None: + _B, _T = attention_masks.size() + assert _B == B and _T == T + # We create a 3D attention mask from a 2D tensor mask. + # Sizes are [batch_size, 1, 1, to_seq_len] + # So we can broadcast to + # [batch_size, num_heads, from_seq_length, to_seq_length] + # this attention mask is more simple than the triangular + # masking of causal attention used in OpenAI GPT, we just need + # to prepare the broadcast dimension here. + attention_masks = attention_masks[:, None, None, :] + + # Since attention_mask is 1.0 for positions we want to attend + # and 0.0 for masked positions, this operation will create a + # tensor which is 0.0 for positions we want to attend and -inf + # for masked positions. Since we are adding it to the raw scores + # before the softmax, this is effectively the same as removing + # these entirely. + attention_masks = attention_masks.to(dtype=input_embeds.dtype) + attention_masks = (1.0 - attention_masks) * -1e9 + + # forward the GPT model itself + x = self.transformer.drop(input_embeds) + + atts = [] + for block in self.transformer.h: + x, att = block(x, attention_masks=attention_masks) + atts.append(att) + x = self.transformer.ln_f(x) + + if return_attentions: + return x, atts + else: + return x diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/misc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..5850eba0a3df007499bfc7caf65a1ab46c6b6913 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/misc.py @@ -0,0 +1,323 @@ +""" Code adapted from https://github.com/ikostrikov/pytorch-a3c""" +import numpy as np +from typing import Union, Tuple, Any, List + +from ray.rllib.models.utils import get_activation_fn +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +@DeveloperAPI +def normc_initializer(std: float = 1.0) -> Any: + def initializer(tensor): + tensor.data.normal_(0, 1) + tensor.data *= std / torch.sqrt(tensor.data.pow(2).sum(1, keepdim=True)) + + return initializer + + +@DeveloperAPI +def same_padding( + in_size: Tuple[int, int], + filter_size: Union[int, Tuple[int, int]], + stride_size: Union[int, Tuple[int, int]], +) -> (Union[int, Tuple[int, int]], Tuple[int, int]): + """Note: Padding is added to match TF conv2d `same` padding. + + See www.tensorflow.org/versions/r0.12/api_docs/python/nn/convolution + + Args: + in_size: Rows (Height), Column (Width) for input + stride_size (Union[int,Tuple[int, int]]): Rows (Height), column (Width) + for stride. If int, height == width. + filter_size: Rows (Height), column (Width) for filter + + Returns: + padding: For input into torch.nn.ZeroPad2d. + output: Output shape after padding and convolution. + """ + in_height, in_width = in_size + if isinstance(filter_size, int): + filter_height, filter_width = filter_size, filter_size + else: + filter_height, filter_width = filter_size + if isinstance(stride_size, (int, float)): + stride_height, stride_width = int(stride_size), int(stride_size) + else: + stride_height, stride_width = int(stride_size[0]), int(stride_size[1]) + + out_height = int(np.ceil(float(in_height) / float(stride_height))) + out_width = int(np.ceil(float(in_width) / float(stride_width))) + + pad_along_height = int((out_height - 1) * stride_height + filter_height - in_height) + pad_along_width = int((out_width - 1) * stride_width + filter_width - in_width) + pad_top = pad_along_height // 2 + pad_bottom = pad_along_height - pad_top + pad_left = pad_along_width // 2 + pad_right = pad_along_width - pad_left + padding = (pad_left, pad_right, pad_top, pad_bottom) + output = (out_height, out_width) + return padding, output + + +@DeveloperAPI +def same_padding_transpose_after_stride( + strided_size: Tuple[int, int], + kernel: Tuple[int, int], + stride: Union[int, Tuple[int, int]], +) -> (Union[int, Tuple[int, int]], Tuple[int, int]): + """Computes padding and output size such that TF Conv2DTranspose `same` is matched. + + Note that when padding="same", TensorFlow's Conv2DTranspose makes sure that + 0-padding is added to the already strided image in such a way that the output image + has the same size as the input image times the stride (and no matter the + kernel size). + + For example: Input image is (4, 4, 24) (not yet strided), padding is "same", + stride=2, kernel=5. + + First, the input image is strided (with stride=2): + + Input image (4x4): + A B C D + E F G H + I J K L + M N O P + + Stride with stride=2 -> (7x7) + A 0 B 0 C 0 D + 0 0 0 0 0 0 0 + E 0 F 0 G 0 H + 0 0 0 0 0 0 0 + I 0 J 0 K 0 L + 0 0 0 0 0 0 0 + M 0 N 0 O 0 P + + Then this strided image (strided_size=7x7) is padded (exact padding values will be + output by this function): + + padding -> (left=3, right=2, top=3, bottom=2) + + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 A 0 B 0 C 0 D 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 E 0 F 0 G 0 H 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 I 0 J 0 K 0 L 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 M 0 N 0 O 0 P 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + + Then deconvolution with kernel=5 yields an output image of 8x8 (x num output + filters). + + Args: + strided_size: The size (width x height) of the already strided image. + kernel: Either width x height (tuple of ints) or - if a square kernel is used - + a single int for both width and height. + stride: Either stride width x stride height (tuple of ints) or - if square + striding is used - a single int for both width- and height striding. + + Returns: + Tuple consisting of 1) `padding`: A 4-tuple to pad the input after(!) striding. + The values are for left, right, top, and bottom padding, individually. + This 4-tuple can be used in a torch.nn.ZeroPad2d layer, and 2) the output shape + after striding, padding, and the conv transpose layer. + """ + + # Solve single int (squared) inputs for kernel and/or stride. + k_w, k_h = (kernel, kernel) if isinstance(kernel, int) else kernel + s_w, s_h = (stride, stride) if isinstance(stride, int) else stride + + # Compute the total size of the 0-padding on both axes. If results are odd numbers, + # the padding on e.g. left and right (or top and bottom) side will have to differ + # by 1. + pad_total_w, pad_total_h = k_w - 1 + s_w - 1, k_h - 1 + s_h - 1 + pad_right = pad_total_w // 2 + pad_left = pad_right + (1 if pad_total_w % 2 == 1 else 0) + pad_bottom = pad_total_h // 2 + pad_top = pad_bottom + (1 if pad_total_h % 2 == 1 else 0) + + # Compute the output size. + output_shape = ( + strided_size[0] + pad_total_w - k_w + 1, + strided_size[1] + pad_total_h - k_h + 1, + ) + + # Return padding and output shape. + return (pad_left, pad_right, pad_top, pad_bottom), output_shape + + +@DeveloperAPI +def valid_padding( + in_size: Tuple[int, int], + filter_size: Union[int, Tuple[int, int]], + stride_size: Union[int, Tuple[int, int]], +) -> Tuple[int, int]: + """Emulates TF Conv2DLayer "valid" padding (no padding) and computes output dims. + + This method, analogous to its "same" counterpart, but it only computes the output + image size, since valid padding means (0, 0, 0, 0). + + See www.tensorflow.org/versions/r0.12/api_docs/python/nn/convolution + + Args: + in_size: Rows (Height), Column (Width) for input + stride_size (Union[int,Tuple[int, int]]): Rows (Height), column (Width) + for stride. If int, height == width. + filter_size: Rows (Height), column (Width) for filter + + Returns: + The output shape after padding and convolution. + """ + in_height, in_width = in_size + if isinstance(filter_size, int): + filter_height, filter_width = filter_size, filter_size + else: + filter_height, filter_width = filter_size + if isinstance(stride_size, (int, float)): + stride_height, stride_width = int(stride_size), int(stride_size) + else: + stride_height, stride_width = int(stride_size[0]), int(stride_size[1]) + + out_height = int(np.ceil((in_height - filter_height + 1) / float(stride_height))) + out_width = int(np.ceil((in_width - filter_width + 1) / float(stride_width))) + + return (out_height, out_width) + + +@DeveloperAPI +class SlimConv2d(nn.Module): + """Simple mock of tf.slim Conv2d""" + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel: Union[int, Tuple[int, int]], + stride: Union[int, Tuple[int, int]], + padding: Union[int, Tuple[int, int]], + # Defaulting these to nn.[..] will break soft torch import. + initializer: Any = "default", + activation_fn: Any = "default", + bias_init: float = 0, + ): + """Creates a standard Conv2d layer, similar to torch.nn.Conv2d + + Args: + in_channels: Number of input channels + out_channels: Number of output channels + kernel: If int, the kernel is + a tuple(x,x). Elsewise, the tuple can be specified + stride: Controls the stride + for the cross-correlation. If int, the stride is a + tuple(x,x). Elsewise, the tuple can be specified + padding: Controls the amount + of implicit zero-paddings during the conv operation + initializer: Initializer function for kernel weights + activation_fn: Activation function at the end of layer + bias_init: Initalize bias weights to bias_init const + """ + super(SlimConv2d, self).__init__() + layers = [] + # Padding layer. + if padding: + layers.append(nn.ZeroPad2d(padding)) + # Actual Conv2D layer (including correct initialization logic). + conv = nn.Conv2d(in_channels, out_channels, kernel, stride) + if initializer: + if initializer == "default": + initializer = nn.init.xavier_uniform_ + initializer(conv.weight) + nn.init.constant_(conv.bias, bias_init) + layers.append(conv) + # Activation function (if any; default=ReLu). + if isinstance(activation_fn, str): + if activation_fn == "default": + activation_fn = nn.ReLU + else: + activation_fn = get_activation_fn(activation_fn, "torch") + if activation_fn is not None: + layers.append(activation_fn()) + # Put everything in sequence. + self._model = nn.Sequential(*layers) + + def forward(self, x: TensorType) -> TensorType: + return self._model(x) + + +@DeveloperAPI +class SlimFC(nn.Module): + """Simple PyTorch version of `linear` function""" + + def __init__( + self, + in_size: int, + out_size: int, + initializer: Any = None, + activation_fn: Any = None, + use_bias: bool = True, + bias_init: float = 0.0, + ): + """Creates a standard FC layer, similar to torch.nn.Linear + + Args: + in_size: Input size for FC Layer + out_size: Output size for FC Layer + initializer: Initializer function for FC layer weights + activation_fn: Activation function at the end of layer + use_bias: Whether to add bias weights or not + bias_init: Initalize bias weights to bias_init const + """ + super(SlimFC, self).__init__() + layers = [] + # Actual nn.Linear layer (including correct initialization logic). + linear = nn.Linear(in_size, out_size, bias=use_bias) + if initializer is None: + initializer = nn.init.xavier_uniform_ + initializer(linear.weight) + if use_bias is True: + nn.init.constant_(linear.bias, bias_init) + layers.append(linear) + # Activation function (if any; default=None (linear)). + if isinstance(activation_fn, str): + activation_fn = get_activation_fn(activation_fn, "torch") + if activation_fn is not None: + layers.append(activation_fn()) + # Put everything in sequence. + self._model = nn.Sequential(*layers) + + def forward(self, x: TensorType) -> TensorType: + return self._model(x) + + +@DeveloperAPI +class AppendBiasLayer(nn.Module): + """Simple bias appending layer for free_log_std.""" + + def __init__(self, num_bias_vars: int): + super().__init__() + self.log_std = torch.nn.Parameter(torch.as_tensor([0.0] * num_bias_vars)) + self.register_parameter("log_std", self.log_std) + + def forward(self, x: TensorType) -> TensorType: + out = torch.cat([x, self.log_std.unsqueeze(0).repeat([len(x), 1])], axis=1) + return out + + +@DeveloperAPI +class Reshape(nn.Module): + """Standard module that reshapes/views a tensor""" + + def __init__(self, shape: List): + super().__init__() + self.shape = shape + + def forward(self, x): + return x.view(*self.shape) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2585dcc77abe4acd4cd6daf49f902a4117a1438c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__init__.py @@ -0,0 +1,13 @@ +from ray.rllib.models.torch.modules.gru_gate import GRUGate +from ray.rllib.models.torch.modules.multi_head_attention import MultiHeadAttention +from ray.rllib.models.torch.modules.relative_multi_head_attention import ( + RelativeMultiHeadAttention, +) +from ray.rllib.models.torch.modules.skip_connection import SkipConnection + +__all__ = [ + "GRUGate", + "RelativeMultiHeadAttention", + "SkipConnection", + "MultiHeadAttention", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99be3df48ff2fe72254098fdbf2485641fb981cc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/gru_gate.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/gru_gate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2ba51719b9c3de182693d7119e2bf5512481b4c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/gru_gate.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/multi_head_attention.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/multi_head_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3125170dc7edc5a74fee5524c85fa16c3b07671f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/multi_head_attention.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/noisy_layer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/noisy_layer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c6bb1f261d805f328b92aa64063a254740e2274 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/noisy_layer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/relative_multi_head_attention.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/relative_multi_head_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15ebbde8af6b5a8c6624012be94564795a9bd2a5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/relative_multi_head_attention.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/skip_connection.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/skip_connection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78045438dee98d7fd807a752a1223b0f9bf86cab Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/__pycache__/skip_connection.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/gru_gate.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/gru_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb6eee845423898c7a553667bc18159cd9f2ff2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/gru_gate.py @@ -0,0 +1,67 @@ +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +@OldAPIStack +class GRUGate(nn.Module): + """Implements a gated recurrent unit for use in AttentionNet""" + + def __init__(self, dim: int, init_bias: int = 0.0, **kwargs): + """ + input_shape (torch.Tensor): dimension of the input + init_bias: Bias added to every input to stabilize training + """ + super().__init__(**kwargs) + # Xavier initialization of torch tensors + self._w_r = nn.Parameter(torch.zeros(dim, dim)) + self._w_z = nn.Parameter(torch.zeros(dim, dim)) + self._w_h = nn.Parameter(torch.zeros(dim, dim)) + nn.init.xavier_uniform_(self._w_r) + nn.init.xavier_uniform_(self._w_z) + nn.init.xavier_uniform_(self._w_h) + self.register_parameter("_w_r", self._w_r) + self.register_parameter("_w_z", self._w_z) + self.register_parameter("_w_h", self._w_h) + + self._u_r = nn.Parameter(torch.zeros(dim, dim)) + self._u_z = nn.Parameter(torch.zeros(dim, dim)) + self._u_h = nn.Parameter(torch.zeros(dim, dim)) + nn.init.xavier_uniform_(self._u_r) + nn.init.xavier_uniform_(self._u_z) + nn.init.xavier_uniform_(self._u_h) + self.register_parameter("_u_r", self._u_r) + self.register_parameter("_u_z", self._u_z) + self.register_parameter("_u_h", self._u_h) + + self._bias_z = nn.Parameter( + torch.zeros( + dim, + ).fill_(init_bias) + ) + self.register_parameter("_bias_z", self._bias_z) + + def forward(self, inputs: TensorType, **kwargs) -> TensorType: + # Pass in internal state first. + h, X = inputs + + r = torch.tensordot(X, self._w_r, dims=1) + torch.tensordot( + h, self._u_r, dims=1 + ) + r = torch.sigmoid(r) + + z = ( + torch.tensordot(X, self._w_z, dims=1) + + torch.tensordot(h, self._u_z, dims=1) + - self._bias_z + ) + z = torch.sigmoid(z) + + h_next = torch.tensordot(X, self._w_h, dims=1) + torch.tensordot( + (h * r), self._u_h, dims=1 + ) + h_next = torch.tanh(h_next) + + return (1 - z) * h + z * h_next diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/multi_head_attention.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/multi_head_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4dfb50b2648b3ccd133a6b7be2e26839052969 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/multi_head_attention.py @@ -0,0 +1,70 @@ +""" +[1] - Attention Is All You Need - Vaswani, Jones, Shazeer, Parmar, + Uszkoreit, Gomez, Kaiser - Google Brain/Research, U Toronto - 2017. + https://arxiv.org/pdf/1706.03762.pdf +""" +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.torch_utils import sequence_mask +from ray.rllib.utils.framework import TensorType + +torch, nn = try_import_torch() + + +@OldAPIStack +class MultiHeadAttention(nn.Module): + """A multi-head attention layer described in [1].""" + + def __init__( + self, in_dim: int, out_dim: int, num_heads: int, head_dim: int, **kwargs + ): + """ + in_dim: Dimension of input + out_dim: Dimension of output + num_heads: Number of attention heads + head_dim: Output dimension of each attention head + """ + super().__init__(**kwargs) + + # No bias or non-linearity. + self._num_heads = num_heads + self._head_dim = head_dim + self._qkv_layer = SlimFC( + in_size=in_dim, out_size=3 * num_heads * head_dim, use_bias=False + ) + + self._linear_layer = SlimFC( + in_size=num_heads * head_dim, out_size=out_dim, use_bias=False + ) + + def forward(self, inputs: TensorType) -> TensorType: + L = list(inputs.size())[1] # length of segment + H = self._num_heads # number of attention heads + D = self._head_dim # attention head dimension + + qkv = self._qkv_layer(inputs) + + queries, keys, values = torch.chunk(input=qkv, chunks=3, dim=-1) + queries = queries[:, -L:] # only query based on the segment + + queries = torch.reshape(queries, [-1, L, H, D]) + keys = torch.reshape(keys, [-1, L, H, D]) + values = torch.reshape(values, [-1, L, H, D]) + + score = torch.einsum("bihd,bjhd->bijh", queries, keys) + score = score / D**0.5 + + # causal mask of the same length as the sequence + mask = sequence_mask(torch.arange(1, L + 1), dtype=score.dtype) + mask = mask[None, :, :, None] + mask = mask.float() + + masked_score = score * mask + 1e30 * (mask - 1.0) + wmat = nn.functional.softmax(masked_score, dim=2) + + out = torch.einsum("bijh,bjhd->bihd", wmat, values) + shape = list(out.size())[:2] + [H * D] + # temp = torch.cat(temp2, [H * D], dim=0) + out = torch.reshape(out, shape) + return self._linear_layer(out) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/noisy_layer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/noisy_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9fe999cf79baeaa35af895311fbe8ecacdd302 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/noisy_layer.py @@ -0,0 +1,99 @@ +import numpy as np + +from ray.rllib.models.utils import get_activation_fn +from ray.rllib.utils.framework import try_import_torch, TensorType + +torch, nn = try_import_torch() + + +class NoisyLayer(nn.Module): + r"""A Layer that adds learnable Noise to some previous layer's outputs. + + Consists of: + - a common dense layer: y = w^{T}x + b + - a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + + (b+\epsilon_b*\sigma_b) + , where \epsilon are random variables sampled from factorized normal + distributions and \sigma are trainable variables which are expected to + vanish along the training procedure. + """ + + def __init__( + self, in_size: int, out_size: int, sigma0: float, activation: str = "relu" + ): + """Initializes a NoisyLayer object. + + Args: + in_size: Input size for Noisy Layer + out_size: Output size for Noisy Layer + sigma0: Initialization value for sigma_b (bias noise) + activation: Non-linear activation for Noisy Layer + """ + super().__init__() + + self.in_size = in_size + self.out_size = out_size + self.sigma0 = sigma0 + self.activation = get_activation_fn(activation, framework="torch") + if self.activation is not None: + self.activation = self.activation() + + sigma_w = nn.Parameter( + torch.from_numpy( + np.random.uniform( + low=-1.0 / np.sqrt(float(self.in_size)), + high=1.0 / np.sqrt(float(self.in_size)), + size=[self.in_size, out_size], + ) + ).float() + ) + self.register_parameter("sigma_w", sigma_w) + sigma_b = nn.Parameter( + torch.from_numpy( + np.full( + shape=[out_size], fill_value=sigma0 / np.sqrt(float(self.in_size)) + ) + ).float() + ) + self.register_parameter("sigma_b", sigma_b) + + w = nn.Parameter( + torch.from_numpy( + np.full( + shape=[self.in_size, self.out_size], + fill_value=6 / np.sqrt(float(in_size) + float(out_size)), + ) + ).float() + ) + self.register_parameter("w", w) + b = nn.Parameter(torch.from_numpy(np.zeros([out_size])).float()) + self.register_parameter("b", b) + + def forward(self, inputs: TensorType) -> TensorType: + epsilon_in = self._f_epsilon( + torch.normal( + mean=torch.zeros([self.in_size]), std=torch.ones([self.in_size]) + ).to(inputs.device) + ) + epsilon_out = self._f_epsilon( + torch.normal( + mean=torch.zeros([self.out_size]), std=torch.ones([self.out_size]) + ).to(inputs.device) + ) + epsilon_w = torch.matmul( + torch.unsqueeze(epsilon_in, -1), other=torch.unsqueeze(epsilon_out, 0) + ) + epsilon_b = epsilon_out + + action_activation = ( + torch.matmul(inputs, self.w + self.sigma_w * epsilon_w) + + self.b + + self.sigma_b * epsilon_b + ) + + if self.activation is not None: + action_activation = self.activation(action_activation) + return action_activation + + def _f_epsilon(self, x: TensorType) -> TensorType: + return torch.sign(x) * torch.pow(torch.abs(x), 0.5) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/relative_multi_head_attention.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/relative_multi_head_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..aa19207e024d7d3f4a365e455974b4127b279606 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/relative_multi_head_attention.py @@ -0,0 +1,177 @@ +from typing import Union + +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import sequence_mask +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +@OldAPIStack +class RelativePositionEmbedding(nn.Module): + """Creates a [seq_length x seq_length] matrix for rel. pos encoding. + + Denoted as Phi in [2] and [3]. Phi is the standard sinusoid encoding + matrix. + + Args: + seq_length: The max. sequence length (time axis). + out_dim: The number of nodes to go into the first Tranformer + layer with. + + Returns: + torch.Tensor: The encoding matrix Phi. + """ + + def __init__(self, out_dim, **kwargs): + super().__init__() + self.out_dim = out_dim + + out_range = torch.arange(0, self.out_dim, 2.0) + inverse_freq = 1 / (10000 ** (out_range / self.out_dim)) + self.register_buffer("inverse_freq", inverse_freq) + + def forward(self, seq_length): + pos_input = torch.arange(seq_length - 1, -1, -1.0, dtype=torch.float).to( + self.inverse_freq.device + ) + sinusoid_input = torch.einsum("i,j->ij", pos_input, self.inverse_freq) + pos_embeddings = torch.cat( + [torch.sin(sinusoid_input), torch.cos(sinusoid_input)], dim=-1 + ) + return pos_embeddings[:, None, :] + + +class RelativeMultiHeadAttention(nn.Module): + """A RelativeMultiHeadAttention layer as described in [3]. + + Uses segment level recurrence with state reuse. + """ + + def __init__( + self, + in_dim: int, + out_dim: int, + num_heads: int, + head_dim: int, + input_layernorm: bool = False, + output_activation: Union[str, callable] = None, + **kwargs + ): + """Initializes a RelativeMultiHeadAttention nn.Module object. + + Args: + in_dim (int): + out_dim: The output dimension of this module. Also known as + "attention dim". + num_heads: The number of attention heads to use. + Denoted `H` in [2]. + head_dim: The dimension of a single(!) attention head + Denoted `D` in [2]. + input_layernorm: Whether to prepend a LayerNorm before + everything else. Should be True for building a GTrXL. + output_activation (Union[str, callable]): Optional activation + function or activation function specifier (str). + Should be "relu" for GTrXL. + **kwargs: + """ + super().__init__(**kwargs) + + # No bias or non-linearity. + self._num_heads = num_heads + self._head_dim = head_dim + + # 3=Query, key, and value inputs. + self._qkv_layer = SlimFC( + in_size=in_dim, out_size=3 * num_heads * head_dim, use_bias=False + ) + + self._linear_layer = SlimFC( + in_size=num_heads * head_dim, + out_size=out_dim, + use_bias=False, + activation_fn=output_activation, + ) + + self._uvar = nn.Parameter(torch.zeros(num_heads, head_dim)) + self._vvar = nn.Parameter(torch.zeros(num_heads, head_dim)) + nn.init.xavier_uniform_(self._uvar) + nn.init.xavier_uniform_(self._vvar) + self.register_parameter("_uvar", self._uvar) + self.register_parameter("_vvar", self._vvar) + + self._pos_proj = SlimFC( + in_size=in_dim, out_size=num_heads * head_dim, use_bias=False + ) + self._rel_pos_embedding = RelativePositionEmbedding(out_dim) + + self._input_layernorm = None + if input_layernorm: + self._input_layernorm = torch.nn.LayerNorm(in_dim) + + def forward(self, inputs: TensorType, memory: TensorType = None) -> TensorType: + T = list(inputs.size())[1] # length of segment (time) + H = self._num_heads # number of attention heads + d = self._head_dim # attention head dimension + + # Add previous memory chunk (as const, w/o gradient) to input. + # Tau (number of (prev) time slices in each memory chunk). + Tau = list(memory.shape)[1] + inputs = torch.cat((memory.detach(), inputs), dim=1) + + # Apply the Layer-Norm. + if self._input_layernorm is not None: + inputs = self._input_layernorm(inputs) + + qkv = self._qkv_layer(inputs) + + queries, keys, values = torch.chunk(input=qkv, chunks=3, dim=-1) + # Cut out Tau memory timesteps from query. + queries = queries[:, -T:] + + queries = torch.reshape(queries, [-1, T, H, d]) + keys = torch.reshape(keys, [-1, Tau + T, H, d]) + values = torch.reshape(values, [-1, Tau + T, H, d]) + + R = self._pos_proj(self._rel_pos_embedding(Tau + T)) + R = torch.reshape(R, [Tau + T, H, d]) + + # b=batch + # i and j=time indices (i=max-timesteps (inputs); j=Tau memory space) + # h=head + # d=head-dim (over which we will reduce-sum) + score = torch.einsum("bihd,bjhd->bijh", queries + self._uvar, keys) + pos_score = torch.einsum("bihd,jhd->bijh", queries + self._vvar, R) + score = score + self.rel_shift(pos_score) + score = score / d**0.5 + + # causal mask of the same length as the sequence + mask = sequence_mask(torch.arange(Tau + 1, Tau + T + 1), dtype=score.dtype).to( + score.device + ) + mask = mask[None, :, :, None] + + masked_score = score * mask + 1e30 * (mask.float() - 1.0) + wmat = nn.functional.softmax(masked_score, dim=2) + + out = torch.einsum("bijh,bjhd->bihd", wmat, values) + shape = list(out.shape)[:2] + [H * d] + out = torch.reshape(out, shape) + + return self._linear_layer(out) + + @staticmethod + def rel_shift(x: TensorType) -> TensorType: + # Transposed version of the shift approach described in [3]. + # https://github.com/kimiyoung/transformer-xl/blob/ + # 44781ed21dbaec88b280f74d9ae2877f52b492a5/tf/model.py#L31 + x_size = list(x.shape) + + x = torch.nn.functional.pad(x, (0, 0, 1, 0, 0, 0, 0, 0)) + x = torch.reshape(x, [x_size[0], x_size[2] + 1, x_size[1], x_size[3]]) + x = x[:, 1:, :, :] + x = torch.reshape(x, x_size) + + return x diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/skip_connection.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/skip_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..444c1680686153b04d44abe61fb581b94fbc49b3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/modules/skip_connection.py @@ -0,0 +1,43 @@ +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType +from typing import Optional + +torch, nn = try_import_torch() + + +@OldAPIStack +class SkipConnection(nn.Module): + """Skip connection layer. + + Adds the original input to the output (regular residual layer) OR uses + input as hidden state input to a given fan_in_layer. + """ + + def __init__( + self, layer: nn.Module, fan_in_layer: Optional[nn.Module] = None, **kwargs + ): + """Initializes a SkipConnection nn Module object. + + Args: + layer (nn.Module): Any layer processing inputs. + fan_in_layer (Optional[nn.Module]): An optional + layer taking two inputs: The original input and the output + of `layer`. + """ + super().__init__(**kwargs) + self._layer = layer + self._fan_in_layer = fan_in_layer + + def forward(self, inputs: TensorType, **kwargs) -> TensorType: + # del kwargs + outputs = self._layer(inputs, **kwargs) + # Residual case, just add inputs to outputs. + if self._fan_in_layer is None: + outputs = outputs + inputs + # Fan-in e.g. RNN: Call fan-in with `inputs` and `outputs`. + else: + # NOTE: In the GRU case, `inputs` is the state input. + outputs = self._fan_in_layer((inputs, outputs)) + + return outputs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/recurrent_net.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/recurrent_net.py new file mode 100644 index 0000000000000000000000000000000000000000..01fbab223e29fe721914bab0e15860cb91f760d4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/recurrent_net.py @@ -0,0 +1,295 @@ +import numpy as np +import gymnasium as gym +from gymnasium.spaces import Discrete, MultiDiscrete +import tree # pip install dm_tree +from typing import Dict, List, Union, Tuple + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.policy.rnn_sequencing import add_time_dimension +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.torch_utils import flatten_inputs_to_1d_tensor, one_hot +from ray.rllib.utils.typing import ModelConfigDict, TensorType +from ray.rllib.utils.deprecation import deprecation_warning +from ray.util.debug import log_once + +torch, nn = try_import_torch() + + +@OldAPIStack +class RecurrentNetwork(TorchModelV2): + """Helper class to simplify implementing RNN models with TorchModelV2. + + Instead of implementing forward(), you can implement forward_rnn() which + takes batches with the time dimension added already. + + Here is an example implementation for a subclass + ``MyRNNClass(RecurrentNetwork, nn.Module)``:: + + def __init__(self, obs_space, num_outputs): + nn.Module.__init__(self) + super().__init__(obs_space, action_space, num_outputs, + model_config, name) + self.obs_size = _get_size(obs_space) + self.rnn_hidden_dim = model_config["lstm_cell_size"] + self.fc1 = nn.Linear(self.obs_size, self.rnn_hidden_dim) + self.rnn = nn.GRUCell(self.rnn_hidden_dim, self.rnn_hidden_dim) + self.fc2 = nn.Linear(self.rnn_hidden_dim, num_outputs) + + self.value_branch = nn.Linear(self.rnn_hidden_dim, 1) + self._cur_value = None + + @override(ModelV2) + def get_initial_state(self): + # Place hidden states on same device as model. + h = [self.fc1.weight.new( + 1, self.rnn_hidden_dim).zero_().squeeze(0)] + return h + + @override(ModelV2) + def value_function(self): + assert self._cur_value is not None, "must call forward() first" + return self._cur_value + + @override(RecurrentNetwork) + def forward_rnn(self, input_dict, state, seq_lens): + x = nn.functional.relu(self.fc1(input_dict["obs_flat"].float())) + h_in = state[0].reshape(-1, self.rnn_hidden_dim) + h = self.rnn(x, h_in) + q = self.fc2(h) + self._cur_value = self.value_branch(h).squeeze(1) + return q, [h] + """ + + @override(ModelV2) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> Tuple[TensorType, List[TensorType]]: + """Adds time dimension to batch before sending inputs to forward_rnn(). + + You should implement forward_rnn() in your subclass.""" + # Creating a __init__ function that acts as a passthrough and adding the warning + # there led to errors probably due to the multiple inheritance. We encountered + # the same error if we add the Deprecated decorator. We therefore add the + # deprecation warning here. + if log_once("recurrent_network_tf"): + deprecation_warning( + old="ray.rllib.models.torch.recurrent_net.RecurrentNetwork" + ) + flat_inputs = input_dict["obs_flat"].float() + # Note that max_seq_len != input_dict.max_seq_len != seq_lens.max() + # as input_dict may have extra zero-padding beyond seq_lens.max(). + # Use add_time_dimension to handle this + self.time_major = self.model_config.get("_time_major", False) + inputs = add_time_dimension( + flat_inputs, + seq_lens=seq_lens, + framework="torch", + time_major=self.time_major, + ) + output, new_state = self.forward_rnn(inputs, state, seq_lens) + output = torch.reshape(output, [-1, self.num_outputs]) + return output, new_state + + def forward_rnn( + self, inputs: TensorType, state: List[TensorType], seq_lens: TensorType + ) -> Tuple[TensorType, List[TensorType]]: + """Call the model with the given input tensors and state. + + Args: + inputs: Observation tensor with shape [B, T, obs_size]. + state: List of state tensors, each with shape [B, size]. + seq_lens: 1D tensor holding input sequence lengths. + Note: len(seq_lens) == B. + + Returns: + (outputs, new_state): The model output tensor of shape + [B, T, num_outputs] and the list of new state tensors each with + shape [B, size]. + + Examples: + def forward_rnn(self, inputs, state, seq_lens): + model_out, h, c = self.rnn_model([inputs, seq_lens] + state) + return model_out, [h, c] + """ + raise NotImplementedError("You must implement this for an RNN model") + + +@OldAPIStack +class LSTMWrapper(RecurrentNetwork, nn.Module): + """An LSTM wrapper serving as an interface for ModelV2s that set use_lstm.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + nn.Module.__init__(self) + super(LSTMWrapper, self).__init__( + obs_space, action_space, None, model_config, name + ) + + # At this point, self.num_outputs is the number of nodes coming + # from the wrapped (underlying) model. In other words, self.num_outputs + # is the input size for the LSTM layer. + # If None, set it to the observation space. + if self.num_outputs is None: + self.num_outputs = int(np.prod(self.obs_space.shape)) + + self.cell_size = model_config["lstm_cell_size"] + self.time_major = model_config.get("_time_major", False) + self.use_prev_action = model_config["lstm_use_prev_action"] + self.use_prev_reward = model_config["lstm_use_prev_reward"] + + self.action_space_struct = get_base_struct_from_space(self.action_space) + self.action_dim = 0 + + for space in tree.flatten(self.action_space_struct): + if isinstance(space, Discrete): + self.action_dim += space.n + elif isinstance(space, MultiDiscrete): + self.action_dim += np.sum(space.nvec) + elif space.shape is not None: + self.action_dim += int(np.prod(space.shape)) + else: + self.action_dim += int(len(space)) + + # Add prev-action/reward nodes to input to LSTM. + if self.use_prev_action: + self.num_outputs += self.action_dim + if self.use_prev_reward: + self.num_outputs += 1 + + # Define actual LSTM layer (with num_outputs being the nodes coming + # from the wrapped (underlying) layer). + self.lstm = nn.LSTM( + self.num_outputs, self.cell_size, batch_first=not self.time_major + ) + + # Set self.num_outputs to the number of output nodes desired by the + # caller of this constructor. + self.num_outputs = num_outputs + + # Postprocess LSTM output with another hidden layer and compute values. + self._logits_branch = SlimFC( + in_size=self.cell_size, + out_size=self.num_outputs, + activation_fn=None, + initializer=torch.nn.init.xavier_uniform_, + ) + self._value_branch = SlimFC( + in_size=self.cell_size, + out_size=1, + activation_fn=None, + initializer=torch.nn.init.xavier_uniform_, + ) + + # __sphinx_doc_begin__ + # Add prev-a/r to this model's view, if required. + if model_config["lstm_use_prev_action"]: + self.view_requirements[SampleBatch.PREV_ACTIONS] = ViewRequirement( + SampleBatch.ACTIONS, space=self.action_space, shift=-1 + ) + if model_config["lstm_use_prev_reward"]: + self.view_requirements[SampleBatch.PREV_REWARDS] = ViewRequirement( + SampleBatch.REWARDS, shift=-1 + ) + # __sphinx_doc_end__ + + @override(RecurrentNetwork) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> Tuple[TensorType, List[TensorType]]: + assert seq_lens is not None + # Push obs through "unwrapped" net's `forward()` first. + wrapped_out, _ = self._wrapped_forward(input_dict, [], None) + + # Concat. prev-action/reward if required. + prev_a_r = [] + + # Prev actions. + if self.model_config["lstm_use_prev_action"]: + prev_a = input_dict[SampleBatch.PREV_ACTIONS] + # If actions are not processed yet (in their original form as + # have been sent to environment): + # Flatten/one-hot into 1D array. + if self.model_config["_disable_action_flattening"]: + prev_a_r.append( + flatten_inputs_to_1d_tensor( + prev_a, spaces_struct=self.action_space_struct, time_axis=False + ) + ) + # If actions are already flattened (but not one-hot'd yet!), + # one-hot discrete/multi-discrete actions here. + else: + if isinstance(self.action_space, (Discrete, MultiDiscrete)): + prev_a = one_hot(prev_a.float(), self.action_space) + else: + prev_a = prev_a.float() + prev_a_r.append(torch.reshape(prev_a, [-1, self.action_dim])) + # Prev rewards. + if self.model_config["lstm_use_prev_reward"]: + prev_a_r.append( + torch.reshape(input_dict[SampleBatch.PREV_REWARDS].float(), [-1, 1]) + ) + + # Concat prev. actions + rewards to the "main" input. + if prev_a_r: + wrapped_out = torch.cat([wrapped_out] + prev_a_r, dim=1) + + # Push everything through our LSTM. + input_dict["obs_flat"] = wrapped_out + return super().forward(input_dict, state, seq_lens) + + @override(RecurrentNetwork) + def forward_rnn( + self, inputs: TensorType, state: List[TensorType], seq_lens: TensorType + ) -> Tuple[TensorType, List[TensorType]]: + # Don't show paddings to RNN(?) + # TODO: (sven) For now, only allow, iff time_major=True to not break + # anything retrospectively (time_major not supported previously). + # max_seq_len = inputs.shape[0] + # time_major = self.model_config["_time_major"] + # if time_major and max_seq_len > 1: + # inputs = torch.nn.utils.rnn.pack_padded_sequence( + # inputs, seq_lens, + # batch_first=not time_major, enforce_sorted=False) + self._features, [h, c] = self.lstm( + inputs, [torch.unsqueeze(state[0], 0), torch.unsqueeze(state[1], 0)] + ) + # Re-apply paddings. + # if time_major and max_seq_len > 1: + # self._features, _ = torch.nn.utils.rnn.pad_packed_sequence( + # self._features, + # batch_first=not time_major) + model_out = self._logits_branch(self._features) + return model_out, [torch.squeeze(h, 0), torch.squeeze(c, 0)] + + @override(ModelV2) + def get_initial_state(self) -> Union[List[np.ndarray], List[TensorType]]: + # Place hidden states on same device as model. + linear = next(self._logits_branch._model.children()) + h = [ + linear.weight.new(1, self.cell_size).zero_().squeeze(0), + linear.weight.new(1, self.cell_size).zero_().squeeze(0), + ] + return h + + @override(ModelV2) + def value_function(self) -> TensorType: + assert self._features is not None, "must call forward() first" + return torch.reshape(self._value_branch(self._features), [-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_action_dist.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_action_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..91c69180070e9797d62f39939db03340979ee2d6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_action_dist.py @@ -0,0 +1,644 @@ +import functools +import gymnasium as gym +from math import log +import numpy as np +import tree # pip install dm_tree +from typing import Optional + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import SMALL_NUMBER, MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import TensorType, List, Union, Tuple, ModelConfigDict + +torch, nn = try_import_torch() + + +@OldAPIStack +class TorchDistributionWrapper(ActionDistribution): + """Wrapper class for torch.distributions.""" + + @override(ActionDistribution) + def __init__(self, inputs: List[TensorType], model: TorchModelV2): + # If inputs are not a torch Tensor, make them one and make sure they + # are on the correct device. + if not isinstance(inputs, torch.Tensor): + inputs = torch.from_numpy(inputs) + if isinstance(model, TorchModelV2): + inputs = inputs.to(next(model.parameters()).device) + super().__init__(inputs, model) + # Store the last sample here. + self.last_sample = None + + @override(ActionDistribution) + def logp(self, actions: TensorType) -> TensorType: + return self.dist.log_prob(actions) + + @override(ActionDistribution) + def entropy(self) -> TensorType: + return self.dist.entropy() + + @override(ActionDistribution) + def kl(self, other: ActionDistribution) -> TensorType: + return torch.distributions.kl.kl_divergence(self.dist, other.dist) + + @override(ActionDistribution) + def sample(self) -> TensorType: + self.last_sample = self.dist.sample() + return self.last_sample + + @override(ActionDistribution) + def sampled_action_logp(self) -> TensorType: + assert self.last_sample is not None + return self.logp(self.last_sample) + + +@OldAPIStack +class TorchCategorical(TorchDistributionWrapper): + """Wrapper class for PyTorch Categorical distribution.""" + + @override(ActionDistribution) + def __init__( + self, + inputs: List[TensorType], + model: TorchModelV2 = None, + temperature: float = 1.0, + ): + if temperature != 1.0: + assert temperature > 0.0, "Categorical `temperature` must be > 0.0!" + inputs /= temperature + super().__init__(inputs, model) + self.dist = torch.distributions.categorical.Categorical(logits=self.inputs) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + self.last_sample = self.dist.probs.argmax(dim=1) + return self.last_sample + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return action_space.n + + +@OldAPIStack +def get_torch_categorical_class_with_temperature(t: float): + """TorchCategorical distribution class that has customized default temperature.""" + + class TorchCategoricalWithTemperature(TorchCategorical): + def __init__(self, inputs, model=None, temperature=t): + super().__init__(inputs, model, temperature) + + return TorchCategoricalWithTemperature + + +@OldAPIStack +class TorchMultiCategorical(TorchDistributionWrapper): + """MultiCategorical distribution for MultiDiscrete action spaces.""" + + @override(TorchDistributionWrapper) + def __init__( + self, + inputs: List[TensorType], + model: TorchModelV2, + input_lens: Union[List[int], np.ndarray, Tuple[int, ...]], + action_space=None, + ): + super().__init__(inputs, model) + # If input_lens is np.ndarray or list, force-make it a tuple. + inputs_split = self.inputs.split(tuple(input_lens), dim=1) + self.cats = [ + torch.distributions.categorical.Categorical(logits=input_) + for input_ in inputs_split + ] + # Used in case we are dealing with an Int Box. + self.action_space = action_space + + @override(TorchDistributionWrapper) + def sample(self) -> TensorType: + arr = [cat.sample() for cat in self.cats] + sample_ = torch.stack(arr, dim=1) + if isinstance(self.action_space, gym.spaces.Box): + sample_ = torch.reshape(sample_, [-1] + list(self.action_space.shape)) + self.last_sample = sample_ + return sample_ + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + arr = [torch.argmax(cat.probs, -1) for cat in self.cats] + sample_ = torch.stack(arr, dim=1) + if isinstance(self.action_space, gym.spaces.Box): + sample_ = torch.reshape(sample_, [-1] + list(self.action_space.shape)) + self.last_sample = sample_ + return sample_ + + @override(TorchDistributionWrapper) + def logp(self, actions: TensorType) -> TensorType: + # # If tensor is provided, unstack it into list. + if isinstance(actions, torch.Tensor): + if isinstance(self.action_space, gym.spaces.Box): + actions = torch.reshape( + actions, [-1, int(np.prod(self.action_space.shape))] + ) + actions = torch.unbind(actions, dim=1) + logps = torch.stack([cat.log_prob(act) for cat, act in zip(self.cats, actions)]) + return torch.sum(logps, dim=0) + + @override(ActionDistribution) + def multi_entropy(self) -> TensorType: + return torch.stack([cat.entropy() for cat in self.cats], dim=1) + + @override(TorchDistributionWrapper) + def entropy(self) -> TensorType: + return torch.sum(self.multi_entropy(), dim=1) + + @override(ActionDistribution) + def multi_kl(self, other: ActionDistribution) -> TensorType: + return torch.stack( + [ + torch.distributions.kl.kl_divergence(cat, oth_cat) + for cat, oth_cat in zip(self.cats, other.cats) + ], + dim=1, + ) + + @override(TorchDistributionWrapper) + def kl(self, other: ActionDistribution) -> TensorType: + return torch.sum(self.multi_kl(other), dim=1) + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + # Int Box. + if isinstance(action_space, gym.spaces.Box): + assert action_space.dtype.name.startswith("int") + low_ = np.min(action_space.low) + high_ = np.max(action_space.high) + assert np.all(action_space.low == low_) + assert np.all(action_space.high == high_) + return np.prod(action_space.shape, dtype=np.int32) * (high_ - low_ + 1) + # MultiDiscrete space. + else: + # `nvec` is already integer. No need to cast. + return np.sum(action_space.nvec) + + +@OldAPIStack +class TorchSlateMultiCategorical(TorchCategorical): + """MultiCategorical distribution for MultiDiscrete action spaces. + + The action space must be uniform, meaning all nvec items have the same size, e.g. + MultiDiscrete([10, 10, 10]), where 10 is the number of candidates to pick from + and 3 is the slate size (pick 3 out of 10). When picking candidates, no candidate + must be picked more than once. + """ + + def __init__( + self, + inputs: List[TensorType], + model: TorchModelV2 = None, + temperature: float = 1.0, + action_space: Optional[gym.spaces.MultiDiscrete] = None, + all_slates=None, + ): + assert temperature > 0.0, "Categorical `temperature` must be > 0.0!" + # Allow softmax formula w/ temperature != 1.0: + # Divide inputs by temperature. + super().__init__(inputs / temperature, model) + self.action_space = action_space + # Assert uniformness of the action space (all discrete buckets have the same + # size). + assert isinstance(self.action_space, gym.spaces.MultiDiscrete) and all( + n == self.action_space.nvec[0] for n in self.action_space.nvec + ) + self.all_slates = all_slates + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + # Get a sample from the underlying Categorical (batch of ints). + sample = super().deterministic_sample() + # Use the sampled ints to pick the actual slates. + return torch.take_along_dim(self.all_slates, sample.long(), dim=-1) + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + # TODO: Implement. + return torch.ones_like(self.inputs[:, 0]) + + +@OldAPIStack +class TorchDiagGaussian(TorchDistributionWrapper): + """Wrapper class for PyTorch Normal distribution.""" + + @override(ActionDistribution) + def __init__( + self, + inputs: List[TensorType], + model: TorchModelV2, + *, + action_space: Optional[gym.spaces.Space] = None + ): + super().__init__(inputs, model) + mean, log_std = torch.chunk(self.inputs, 2, dim=1) + self.log_std = log_std + self.dist = torch.distributions.normal.Normal(mean, torch.exp(log_std)) + # Remember to squeeze action samples in case action space is Box(shape) + self.zero_action_dim = action_space and action_space.shape == () + + @override(TorchDistributionWrapper) + def sample(self) -> TensorType: + sample = super().sample() + if self.zero_action_dim: + return torch.squeeze(sample, dim=-1) + return sample + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + self.last_sample = self.dist.mean + return self.last_sample + + @override(TorchDistributionWrapper) + def logp(self, actions: TensorType) -> TensorType: + return super().logp(actions).sum(-1) + + @override(TorchDistributionWrapper) + def entropy(self) -> TensorType: + return super().entropy().sum(-1) + + @override(TorchDistributionWrapper) + def kl(self, other: ActionDistribution) -> TensorType: + return super().kl(other).sum(-1) + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) * 2 + + +@OldAPIStack +class TorchSquashedGaussian(TorchDistributionWrapper): + """A tanh-squashed Gaussian distribution defined by: mean, std, low, high. + + The distribution will never return low or high exactly, but + `low`+SMALL_NUMBER or `high`-SMALL_NUMBER respectively. + """ + + def __init__( + self, + inputs: List[TensorType], + model: TorchModelV2, + low: float = -1.0, + high: float = 1.0, + ): + """Parameterizes the distribution via `inputs`. + + Args: + low: The lowest possible sampling value + (excluding this value). + high: The highest possible sampling value + (excluding this value). + """ + super().__init__(inputs, model) + # Split inputs into mean and log(std). + mean, log_std = torch.chunk(self.inputs, 2, dim=-1) + # Clip `scale` values (coming from NN) to reasonable values. + log_std = torch.clamp(log_std, MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT) + std = torch.exp(log_std) + self.dist = torch.distributions.normal.Normal(mean, std) + assert np.all(np.less(low, high)) + self.low = low + self.high = high + self.mean = mean + self.std = std + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + self.last_sample = self._squash(self.dist.mean) + return self.last_sample + + @override(TorchDistributionWrapper) + def sample(self) -> TensorType: + # Use the reparameterization version of `dist.sample` to allow for + # the results to be backprop'able e.g. in a loss term. + + normal_sample = self.dist.rsample() + self.last_sample = self._squash(normal_sample) + return self.last_sample + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + # Unsquash values (from [low,high] to ]-inf,inf[) + unsquashed_values = self._unsquash(x) + # Get log prob of unsquashed values from our Normal. + log_prob_gaussian = self.dist.log_prob(unsquashed_values) + # For safety reasons, clamp somehow, only then sum up. + log_prob_gaussian = torch.clamp(log_prob_gaussian, -100, 100) + log_prob_gaussian = torch.sum(log_prob_gaussian, dim=-1) + # Get log-prob for squashed Gaussian. + unsquashed_values_tanhd = torch.tanh(unsquashed_values) + log_prob = log_prob_gaussian - torch.sum( + torch.log(1 - unsquashed_values_tanhd**2 + SMALL_NUMBER), dim=-1 + ) + return log_prob + + def sample_logp(self): + z = self.dist.rsample() + actions = self._squash(z) + return actions, torch.sum( + self.dist.log_prob(z) - torch.log(1 - actions * actions + SMALL_NUMBER), + dim=-1, + ) + + @override(TorchDistributionWrapper) + def entropy(self) -> TensorType: + raise ValueError("Entropy not defined for SquashedGaussian!") + + @override(TorchDistributionWrapper) + def kl(self, other: ActionDistribution) -> TensorType: + raise ValueError("KL not defined for SquashedGaussian!") + + def _squash(self, raw_values: TensorType) -> TensorType: + # Returned values are within [low, high] (including `low` and `high`). + squashed = ((torch.tanh(raw_values) + 1.0) / 2.0) * ( + self.high - self.low + ) + self.low + return torch.clamp(squashed, self.low, self.high) + + def _unsquash(self, values: TensorType) -> TensorType: + normed_values = (values - self.low) / (self.high - self.low) * 2.0 - 1.0 + # Stabilize input to atanh. + save_normed_values = torch.clamp( + normed_values, -1.0 + SMALL_NUMBER, 1.0 - SMALL_NUMBER + ) + unsquashed = torch.atanh(save_normed_values) + return unsquashed + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) * 2 + + +@OldAPIStack +class TorchBeta(TorchDistributionWrapper): + """ + A Beta distribution is defined on the interval [0, 1] and parameterized by + shape parameters alpha and beta (also called concentration parameters). + + PDF(x; alpha, beta) = x**(alpha - 1) (1 - x)**(beta - 1) / Z + with Z = Gamma(alpha) Gamma(beta) / Gamma(alpha + beta) + and Gamma(n) = (n - 1)! + """ + + def __init__( + self, + inputs: List[TensorType], + model: TorchModelV2, + low: float = 0.0, + high: float = 1.0, + ): + super().__init__(inputs, model) + # Stabilize input parameters (possibly coming from a linear layer). + self.inputs = torch.clamp(self.inputs, log(SMALL_NUMBER), -log(SMALL_NUMBER)) + self.inputs = torch.log(torch.exp(self.inputs) + 1.0) + 1.0 + self.low = low + self.high = high + alpha, beta = torch.chunk(self.inputs, 2, dim=-1) + # Note: concentration0==beta, concentration1=alpha (!) + self.dist = torch.distributions.Beta(concentration1=alpha, concentration0=beta) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + self.last_sample = self._squash(self.dist.mean) + return self.last_sample + + @override(TorchDistributionWrapper) + def sample(self) -> TensorType: + # Use the reparameterization version of `dist.sample` to allow for + # the results to be backprop'able e.g. in a loss term. + normal_sample = self.dist.rsample() + self.last_sample = self._squash(normal_sample) + return self.last_sample + + @override(ActionDistribution) + def logp(self, x: TensorType) -> TensorType: + unsquashed_values = self._unsquash(x) + return torch.sum(self.dist.log_prob(unsquashed_values), dim=-1) + + def _squash(self, raw_values: TensorType) -> TensorType: + return raw_values * (self.high - self.low) + self.low + + def _unsquash(self, values: TensorType) -> TensorType: + return (values - self.low) / (self.high - self.low) + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) * 2 + + +@OldAPIStack +class TorchDeterministic(TorchDistributionWrapper): + """Action distribution that returns the input values directly. + + This is similar to DiagGaussian with standard deviation zero (thus only + requiring the "mean" values as NN output). + """ + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + return self.inputs + + @override(TorchDistributionWrapper) + def sampled_action_logp(self) -> TensorType: + return torch.zeros((self.inputs.size()[0],), dtype=torch.float32) + + @override(TorchDistributionWrapper) + def sample(self) -> TensorType: + return self.deterministic_sample() + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + return np.prod(action_space.shape, dtype=np.int32) + + +@OldAPIStack +class TorchMultiActionDistribution(TorchDistributionWrapper): + """Action distribution that operates on multiple, possibly nested actions.""" + + def __init__(self, inputs, model, *, child_distributions, input_lens, action_space): + """Initializes a TorchMultiActionDistribution object. + + Args: + inputs (torch.Tensor): A single tensor of shape [BATCH, size]. + model (TorchModelV2): The TorchModelV2 object used to produce + inputs for this distribution. + child_distributions (any[torch.Tensor]): Any struct + that contains the child distribution classes to use to + instantiate the child distributions from `inputs`. This could + be an already flattened list or a struct according to + `action_space`. + input_lens (any[int]): A flat list or a nested struct of input + split lengths used to split `inputs`. + action_space (Union[gym.spaces.Dict,gym.spaces.Tuple]): The complex + and possibly nested action space. + """ + if not isinstance(inputs, torch.Tensor): + inputs = torch.from_numpy(inputs) + if isinstance(model, TorchModelV2): + inputs = inputs.to(next(model.parameters()).device) + super().__init__(inputs, model) + + self.action_space_struct = get_base_struct_from_space(action_space) + + self.input_lens = tree.flatten(input_lens) + flat_child_distributions = tree.flatten(child_distributions) + split_inputs = torch.split(inputs, self.input_lens, dim=1) + self.flat_child_distributions = tree.map_structure( + lambda dist, input_: dist(input_, model), + flat_child_distributions, + list(split_inputs), + ) + + @override(ActionDistribution) + def logp(self, x): + if isinstance(x, np.ndarray): + x = torch.Tensor(x) + # Single tensor input (all merged). + if isinstance(x, torch.Tensor): + split_indices = [] + for dist in self.flat_child_distributions: + if isinstance(dist, TorchCategorical): + split_indices.append(1) + elif ( + isinstance(dist, TorchMultiCategorical) + and dist.action_space is not None + ): + split_indices.append(int(np.prod(dist.action_space.shape))) + else: + sample = dist.sample() + # Cover Box(shape=()) case. + if len(sample.shape) == 1: + split_indices.append(1) + else: + split_indices.append(sample.size()[1]) + split_x = list(torch.split(x, split_indices, dim=1)) + # Structured or flattened (by single action component) input. + else: + split_x = tree.flatten(x) + + def map_(val, dist): + # Remove extra categorical dimension. + if isinstance(dist, TorchCategorical): + val = (torch.squeeze(val, dim=-1) if len(val.shape) > 1 else val).int() + return dist.logp(val) + + # Remove extra categorical dimension and take the logp of each + # component. + flat_logps = tree.map_structure(map_, split_x, self.flat_child_distributions) + + return functools.reduce(lambda a, b: a + b, flat_logps) + + @override(ActionDistribution) + def kl(self, other): + kl_list = [ + d.kl(o) + for d, o in zip( + self.flat_child_distributions, other.flat_child_distributions + ) + ] + return functools.reduce(lambda a, b: a + b, kl_list) + + @override(ActionDistribution) + def entropy(self): + entropy_list = [d.entropy() for d in self.flat_child_distributions] + return functools.reduce(lambda a, b: a + b, entropy_list) + + @override(ActionDistribution) + def sample(self): + child_distributions = tree.unflatten_as( + self.action_space_struct, self.flat_child_distributions + ) + return tree.map_structure(lambda s: s.sample(), child_distributions) + + @override(ActionDistribution) + def deterministic_sample(self): + child_distributions = tree.unflatten_as( + self.action_space_struct, self.flat_child_distributions + ) + return tree.map_structure( + lambda s: s.deterministic_sample(), child_distributions + ) + + @override(TorchDistributionWrapper) + def sampled_action_logp(self): + p = self.flat_child_distributions[0].sampled_action_logp() + for c in self.flat_child_distributions[1:]: + p += c.sampled_action_logp() + return p + + @override(ActionDistribution) + def required_model_output_shape(self, action_space, model_config): + return np.sum(self.input_lens, dtype=np.int32) + + +@OldAPIStack +class TorchDirichlet(TorchDistributionWrapper): + """Dirichlet distribution for continuous actions that are between + [0,1] and sum to 1. + + e.g. actions that represent resource allocation.""" + + def __init__(self, inputs, model): + """Input is a tensor of logits. The exponential of logits is used to + parametrize the Dirichlet distribution as all parameters need to be + positive. An arbitrary small epsilon is added to the concentration + parameters to be zero due to numerical error. + + See issue #4440 for more details. + """ + self.epsilon = torch.tensor(1e-7).to(inputs.device) + concentration = torch.exp(inputs) + self.epsilon + self.dist = torch.distributions.dirichlet.Dirichlet( + concentration=concentration, + validate_args=True, + ) + super().__init__(concentration, model) + + @override(ActionDistribution) + def deterministic_sample(self) -> TensorType: + self.last_sample = nn.functional.softmax(self.dist.concentration, dim=-1) + return self.last_sample + + @override(ActionDistribution) + def logp(self, x): + # Support of Dirichlet are positive real numbers. x is already + # an array of positive numbers, but we clip to avoid zeros due to + # numerical errors. + x = torch.max(x, self.epsilon) + x = x / torch.sum(x, dim=-1, keepdim=True) + return self.dist.log_prob(x) + + @override(ActionDistribution) + def entropy(self): + return self.dist.entropy() + + @staticmethod + @override(ActionDistribution) + def required_model_output_shape(action_space, model_config): + return np.prod(action_space.shape, dtype=np.int32) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_distributions.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..afba9a9a16a689b95ab0924841771084077b13e1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_distributions.py @@ -0,0 +1,16 @@ +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.core.distribution.torch.torch_distribution import ( # noqa + TorchDistribution, + TorchCategorical, + TorchDiagGaussian, + TorchSquashedGaussian, + TorchDeterministic, + TorchMultiCategorical, + TorchMultiDistribution, +) + +deprecation_warning( + old="ray.rllib.models.torch.torch_distributions.TorchDistribution", + new="ray.rllib.core.distribution.torch.torch_distribution.TorchDistribution", + error=False, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_modelv2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_modelv2.py new file mode 100644 index 0000000000000000000000000000000000000000..dd473c70de3ef91384306ef7c23e58314179ba27 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/torch_modelv2.py @@ -0,0 +1,80 @@ +import gymnasium as gym +from typing import Dict, List, Union + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModelConfigDict, TensorType + +_, nn = try_import_torch() + + +@OldAPIStack +class TorchModelV2(ModelV2): + """Torch version of ModelV2. + + Note that this class by itself is not a valid model unless you + inherit from nn.Module and implement forward() in a subclass.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + """Initialize a TorchModelV2. + + Here is an example implementation for a subclass + ``MyModelClass(TorchModelV2, nn.Module)``:: + + def __init__(self, *args, **kwargs): + TorchModelV2.__init__(self, *args, **kwargs) + nn.Module.__init__(self) + self._hidden_layers = nn.Sequential(...) + self._logits = ... + self._value_branch = ... + """ + if not isinstance(self, nn.Module): + raise ValueError( + "Subclasses of TorchModelV2 must also inherit from " + "nn.Module, e.g., MyModel(TorchModelV2, nn.Module)" + ) + + ModelV2.__init__( + self, + obs_space, + action_space, + num_outputs, + model_config, + name, + framework="torch", + ) + + # Dict to store per multi-gpu tower stats into. + # In PyTorch multi-GPU, we use a single TorchPolicy and copy + # it's Model(s) n times (1 copy for each GPU). When computing the loss + # on each tower, we cannot store the stats (e.g. `entropy`) inside the + # policy object as this would lead to race conditions between the + # different towers all accessing the same property at the same time. + self.tower_stats = {} + + @override(ModelV2) + def variables( + self, as_dict: bool = False + ) -> Union[List[TensorType], Dict[str, TensorType]]: + p = list(self.parameters()) + if as_dict: + return {k: p[i] for i, k in enumerate(self.state_dict().keys())} + return p + + @override(ModelV2) + def trainable_variables( + self, as_dict: bool = False + ) -> Union[List[TensorType], Dict[str, TensorType]]: + if as_dict: + return { + k: v for k, v in self.variables(as_dict=True).items() if v.requires_grad + } + return [v for v in self.variables() if v.requires_grad] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/visionnet.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/visionnet.py new file mode 100644 index 0000000000000000000000000000000000000000..748ba5796e3bfb76cc0c04a4a2d14cffaede48ab --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/torch/visionnet.py @@ -0,0 +1,293 @@ +import numpy as np +from typing import Dict, List +import gymnasium as gym + +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.models.torch.misc import ( + normc_initializer, + same_padding, + SlimConv2d, + SlimFC, +) +from ray.rllib.models.utils import get_activation_fn, get_filter_config +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModelConfigDict, TensorType + +torch, nn = try_import_torch() + + +@OldAPIStack +class VisionNetwork(TorchModelV2, nn.Module): + """Generic vision network.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + ): + if not model_config.get("conv_filters"): + model_config["conv_filters"] = get_filter_config(obs_space.shape) + + TorchModelV2.__init__( + self, obs_space, action_space, num_outputs, model_config, name + ) + nn.Module.__init__(self) + + activation = self.model_config.get("conv_activation") + filters = self.model_config["conv_filters"] + assert len(filters) > 0, "Must provide at least 1 entry in `conv_filters`!" + + # Post FC net config. + post_fcnet_hiddens = model_config.get("post_fcnet_hiddens", []) + post_fcnet_activation = get_activation_fn( + model_config.get("post_fcnet_activation"), framework="torch" + ) + + no_final_linear = self.model_config.get("no_final_linear") + vf_share_layers = self.model_config.get("vf_share_layers") + + # Whether the last layer is the output of a Flattened (rather than + # a n x (1,1) Conv2D). + self.last_layer_is_flattened = False + self._logits = None + + layers = [] + (w, h, in_channels) = obs_space.shape + + in_size = [w, h] + for out_channels, kernel, stride in filters[:-1]: + padding, out_size = same_padding(in_size, kernel, stride) + layers.append( + SlimConv2d( + in_channels, + out_channels, + kernel, + stride, + padding, + activation_fn=activation, + ) + ) + in_channels = out_channels + in_size = out_size + + out_channels, kernel, stride = filters[-1] + + # No final linear: Last layer has activation function and exits with + # num_outputs nodes (this could be a 1x1 conv or a FC layer, depending + # on `post_fcnet_...` settings). + if no_final_linear and num_outputs: + out_channels = out_channels if post_fcnet_hiddens else num_outputs + layers.append( + SlimConv2d( + in_channels, + out_channels, + kernel, + stride, + None, # padding=valid + activation_fn=activation, + ) + ) + + # Add (optional) post-fc-stack after last Conv2D layer. + layer_sizes = post_fcnet_hiddens[:-1] + ( + [num_outputs] if post_fcnet_hiddens else [] + ) + for i, out_size in enumerate(layer_sizes): + layers.append( + SlimFC( + in_size=out_channels, + out_size=out_size, + activation_fn=post_fcnet_activation, + initializer=normc_initializer(1.0), + ) + ) + out_channels = out_size + + # Finish network normally (w/o overriding last layer size with + # `num_outputs`), then add another linear one of size `num_outputs`. + else: + layers.append( + SlimConv2d( + in_channels, + out_channels, + kernel, + stride, + None, # padding=valid + activation_fn=activation, + ) + ) + + # num_outputs defined. Use that to create an exact + # `num_output`-sized (1,1)-Conv2D. + if num_outputs: + in_size = [ + np.ceil((in_size[0] - kernel[0]) / stride), + np.ceil((in_size[1] - kernel[1]) / stride), + ] + padding, _ = same_padding(in_size, [1, 1], [1, 1]) + if post_fcnet_hiddens: + layers.append(nn.Flatten()) + in_size = out_channels + # Add (optional) post-fc-stack after last Conv2D layer. + for i, out_size in enumerate(post_fcnet_hiddens + [num_outputs]): + layers.append( + SlimFC( + in_size=in_size, + out_size=out_size, + activation_fn=post_fcnet_activation + if i < len(post_fcnet_hiddens) - 1 + else None, + initializer=normc_initializer(1.0), + ) + ) + in_size = out_size + # Last layer is logits layer. + self._logits = layers.pop() + + else: + self._logits = SlimConv2d( + out_channels, + num_outputs, + [1, 1], + 1, + padding, + activation_fn=None, + ) + + # num_outputs not known -> Flatten, then set self.num_outputs + # to the resulting number of nodes. + else: + self.last_layer_is_flattened = True + layers.append(nn.Flatten()) + + self._convs = nn.Sequential(*layers) + + # If our num_outputs still unknown, we need to do a test pass to + # figure out the output dimensions. This could be the case, if we have + # the Flatten layer at the end. + if self.num_outputs is None: + # Create a B=1 dummy sample and push it through out conv-net. + dummy_in = ( + torch.from_numpy(self.obs_space.sample()) + .permute(2, 0, 1) + .unsqueeze(0) + .float() + ) + dummy_out = self._convs(dummy_in) + self.num_outputs = dummy_out.shape[1] + + # Build the value layers + self._value_branch_separate = self._value_branch = None + if vf_share_layers: + self._value_branch = SlimFC( + out_channels, 1, initializer=normc_initializer(0.01), activation_fn=None + ) + else: + vf_layers = [] + (w, h, in_channels) = obs_space.shape + in_size = [w, h] + for out_channels, kernel, stride in filters[:-1]: + padding, out_size = same_padding(in_size, kernel, stride) + vf_layers.append( + SlimConv2d( + in_channels, + out_channels, + kernel, + stride, + padding, + activation_fn=activation, + ) + ) + in_channels = out_channels + in_size = out_size + + out_channels, kernel, stride = filters[-1] + vf_layers.append( + SlimConv2d( + in_channels, + out_channels, + kernel, + stride, + None, + activation_fn=activation, + ) + ) + + vf_layers.append( + SlimConv2d( + in_channels=out_channels, + out_channels=1, + kernel=1, + stride=1, + padding=None, + activation_fn=None, + ) + ) + self._value_branch_separate = nn.Sequential(*vf_layers) + + # Holds the current "base" output (before logits layer). + self._features = None + + @override(TorchModelV2) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + self._features = input_dict["obs"].float() + # Permuate b/c data comes in as [B, dim, dim, channels]: + self._features = self._features.permute(0, 3, 1, 2) + conv_out = self._convs(self._features) + # Store features to save forward pass when getting value_function out. + if not self._value_branch_separate: + self._features = conv_out + + if not self.last_layer_is_flattened: + if self._logits: + conv_out = self._logits(conv_out) + if len(conv_out.shape) == 4: + if conv_out.shape[2] != 1 or conv_out.shape[3] != 1: + raise ValueError( + "Given `conv_filters` ({}) do not result in a [B, {} " + "(`num_outputs`), 1, 1] shape (but in {})! Please " + "adjust your Conv2D stack such that the last 2 dims " + "are both 1.".format( + self.model_config["conv_filters"], + self.num_outputs, + list(conv_out.shape), + ) + ) + logits = conv_out.squeeze(3) + logits = logits.squeeze(2) + else: + logits = conv_out + return logits, state + else: + return conv_out, state + + @override(TorchModelV2) + def value_function(self) -> TensorType: + assert self._features is not None, "must call forward() first" + if self._value_branch_separate: + value = self._value_branch_separate(self._features) + value = value.squeeze(3) + value = value.squeeze(2) + return value.squeeze(1) + else: + if not self.last_layer_is_flattened: + features = self._features.squeeze(3) + features = features.squeeze(2) + else: + features = self._features + return self._value_branch(features).squeeze(1) + + def _hidden_layers(self, obs: TensorType) -> TensorType: + res = self._convs(obs.permute(0, 3, 1, 2)) # switch to channel-major + res = res.squeeze(3) + res = res.squeeze(2) + return res diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb5b1c82f6a4e03fc7a82be789f01d3880e6945d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/d4rl_reader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/d4rl_reader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4056f8cb38ff7821a3f5693222d3a6ea2df2d58 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/d4rl_reader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/dataset_reader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/dataset_reader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d23b114be7c32ca0561eb91142a57e5b71bb0c9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/dataset_reader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/dataset_writer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/dataset_writer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2255af76125f9ac66916e4fd426f8448f1a2f5e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/dataset_writer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/feature_importance.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/feature_importance.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..426ca8d2ad63a14f2d085c164851742a8cb078d2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/feature_importance.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/input_reader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/input_reader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..941d4b9ebacf47c74fb9c578ccc94d3275be780b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/input_reader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/io_context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/io_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..720caa71b5d8a08d44aa2b5c53130dcc9e13b9a1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/io_context.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/is_estimator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/is_estimator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78fad5087d222df72846075212cc58377a207f08 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/is_estimator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/json_reader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/json_reader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb10b9d9ed12a221941708d0e0b6cea91f0bd804 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/json_reader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/json_writer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/json_writer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4919f2cbb9ecff9949184b16f96bc68ac7c139a8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/json_writer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/mixed_input.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/mixed_input.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fc0901c624627b06469ea0923b44629dc59f4f2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/mixed_input.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/off_policy_estimator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/off_policy_estimator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16e10b1a9426293b34fa1c01030000a878c684ea Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/off_policy_estimator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_data.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfa7ad7855b328321f3798ee7851cab7a2a1729f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_data.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_env_runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_env_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ceb4253888e1006b070a3c42e4b5b0b1e3c868c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_env_runner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..288dbb6748c7b004fa9d78800b797ba3a783fffa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_runner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_runner_group.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_runner_group.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b558815e273d8bc8c9bee6ed1f05ff7e8d4221f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_runner_group.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddd8cb07c4dc4ece7304a5d99ef0afeb26d5d9e3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluation_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..275ef638379d1b3928299e88ae0f9953e201ea4b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_evaluator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_policy_evaluation_runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_policy_evaluation_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7793a0c7cfcb65a3aeb580a4d8466157b141d7eb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_policy_evaluation_runner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_prelearner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_prelearner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f88bf016055ba3509f7c56ebb44d8dcd1c6473cd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/offline_prelearner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/output_writer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/output_writer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11e0bc4923063f36a5357ff4e69a1b790f425099 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/output_writer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/resource.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/resource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f9984eb5be5c4e974c0ec259343e05e3a5e4ff1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/resource.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/shuffled_input.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/shuffled_input.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0cfeb6aa5aae6aea5a5091441b4addfdc4ca358 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/shuffled_input.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/wis_estimator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/wis_estimator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3beec1311b92cd744926dc1e39778655e4c6bfd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__pycache__/wis_estimator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..74131faf3eb6d98c81ea97aa064bc991c01afe96 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__init__.py @@ -0,0 +1,15 @@ +from ray.rllib.offline.estimators.importance_sampling import ImportanceSampling +from ray.rllib.offline.estimators.weighted_importance_sampling import ( + WeightedImportanceSampling, +) +from ray.rllib.offline.estimators.direct_method import DirectMethod +from ray.rllib.offline.estimators.doubly_robust import DoublyRobust +from ray.rllib.offline.estimators.off_policy_estimator import OffPolicyEstimator + +__all__ = [ + "OffPolicyEstimator", + "ImportanceSampling", + "WeightedImportanceSampling", + "DirectMethod", + "DoublyRobust", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..febe0e60d4283c75b6464476ecc0b1a003b311af Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/direct_method.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/direct_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40807b86c74f504e90a67e117fcc2730a3a6f4a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/direct_method.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/doubly_robust.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/doubly_robust.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a33e3a129b09abc0f9a15ab06c8601d51c9fd22 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/doubly_robust.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/feature_importance.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/feature_importance.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50ace3e476280a72b11b39d09793700e11935184 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/feature_importance.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/fqe_torch_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/fqe_torch_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fd89333d7d6cdb1d86555f8647794b322b50c15 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/fqe_torch_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/importance_sampling.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/importance_sampling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13671b63586e66ba73350110cc06301fa28c701e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/importance_sampling.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/off_policy_estimator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/off_policy_estimator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c52a7d58e4489a442250c56c2a0ace062a075ba Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/off_policy_estimator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/weighted_importance_sampling.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/weighted_importance_sampling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbc97c49e1d1f0a81c16323bbc2cd4a9845e9341 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/__pycache__/weighted_importance_sampling.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/direct_method.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/direct_method.py new file mode 100644 index 0000000000000000000000000000000000000000..c735b93a5e1b23b5217e8d2f1eec39c58ef4c2c2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/direct_method.py @@ -0,0 +1,180 @@ +import logging +from typing import Dict, Any, Optional, List +import math +import numpy as np + +from ray.data import Dataset + +from ray.rllib.offline.estimators.off_policy_estimator import OffPolicyEstimator +from ray.rllib.offline.offline_evaluation_utils import compute_q_and_v_values +from ray.rllib.offline.offline_evaluator import OfflineEvaluator +from ray.rllib.offline.estimators.fqe_torch_model import FQETorchModel +from ray.rllib.policy import Policy +from ray.rllib.policy.sample_batch import convert_ma_batch_to_sample_batch +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import DeveloperAPI, override +from ray.rllib.utils.typing import SampleBatchType +from ray.rllib.utils.numpy import convert_to_numpy + +logger = logging.getLogger() + + +@DeveloperAPI +class DirectMethod(OffPolicyEstimator): + r"""The Direct Method estimator. + + Let s_t, a_t, and r_t be the state, action, and reward at timestep t. + + This method trains a Q-model for the evaluation policy \pi_e on behavior + data generated by \pi_b. Currently, RLlib implements this using + Fitted-Q Evaluation (FQE). You can also implement your own model + and pass it in as `q_model_config = {"type": your_model_class, **your_kwargs}`. + + This estimator computes the expected return for \pi_e for an episode as: + V^{\pi_e}(s_0) = \sum_{a \in A} \pi_e(a | s_0) Q(s_0, a) + and returns the mean and standard deviation over episodes. + + For more information refer to https://arxiv.org/pdf/1911.06854.pdf""" + + @override(OffPolicyEstimator) + def __init__( + self, + policy: Policy, + gamma: float, + epsilon_greedy: float = 0.0, + q_model_config: Optional[Dict] = None, + ): + """Initializes a Direct Method OPE Estimator. + + Args: + policy: Policy to evaluate. + gamma: Discount factor of the environment. + epsilon_greedy: The probability by which we act acording to a fully random + policy during deployment. With 1-epsilon_greedy we act according the + target policy. + q_model_config: Arguments to specify the Q-model. Must specify + a `type` key pointing to the Q-model class. + This Q-model is trained in the train() method and is used + to compute the state-value estimates for the DirectMethod estimator. + It must implement `train` and `estimate_v`. + TODO (Rohan138): Unify this with RLModule API. + """ + + super().__init__(policy, gamma, epsilon_greedy) + + # Some dummy policies and ones that are not based on a tensor framework + # backend can come without a config or without a framework key. + if hasattr(policy, "config"): + assert ( + policy.config.get("framework", "torch") == "torch" + ), "Framework must be torch to use DirectMethod." + + q_model_config = q_model_config or {} + model_cls = q_model_config.pop("type", FQETorchModel) + self.model = model_cls( + policy=policy, + gamma=gamma, + **q_model_config, + ) + assert hasattr( + self.model, "estimate_v" + ), "self.model must implement `estimate_v`!" + + @override(OffPolicyEstimator) + def estimate_on_single_episode(self, episode: SampleBatch) -> Dict[str, Any]: + estimates_per_epsiode = {} + rewards = episode["rewards"] + + v_behavior = 0.0 + for t in range(episode.count): + v_behavior += rewards[t] * self.gamma**t + + v_target = self._compute_v_target(episode[:1]) + + estimates_per_epsiode["v_behavior"] = v_behavior + estimates_per_epsiode["v_target"] = v_target + + return estimates_per_epsiode + + @override(OffPolicyEstimator) + def estimate_on_single_step_samples( + self, batch: SampleBatch + ) -> Dict[str, List[float]]: + estimates_per_epsiode = {} + rewards = batch["rewards"] + + v_behavior = rewards + v_target = self._compute_v_target(batch) + + estimates_per_epsiode["v_behavior"] = v_behavior + estimates_per_epsiode["v_target"] = v_target + + return estimates_per_epsiode + + def _compute_v_target(self, init_step): + v_target = self.model.estimate_v(init_step) + v_target = convert_to_numpy(v_target) + return v_target + + @override(OffPolicyEstimator) + def train(self, batch: SampleBatchType) -> Dict[str, Any]: + """Trains self.model on the given batch. + + Args: + batch: A SampleBatchType to train on + + Returns: + A dict with key "loss" and value as the mean training loss. + """ + batch = convert_ma_batch_to_sample_batch(batch) + losses = self.model.train(batch) + return {"loss": np.mean(losses)} + + @override(OfflineEvaluator) + def estimate_on_dataset( + self, dataset: Dataset, *, n_parallelism: int = ... + ) -> Dict[str, Any]: + """Calculates the Direct Method estimate on the given dataset. + + Note: This estimate works for only discrete action spaces for now. + + Args: + dataset: Dataset to compute the estimate on. Each record in dataset should + include the following columns: `obs`, `actions`, `action_prob` and + `rewards`. The `obs` on each row shoud be a vector of D dimensions. + n_parallelism: The number of parallel workers to use. + + Returns: + Dictionary with the following keys: + v_target: The estimated value of the target policy. + v_behavior: The estimated value of the behavior policy. + v_gain: The estimated gain of the target policy over the behavior + policy. + v_std: The standard deviation of the estimated value of the target. + """ + # compute v_values + batch_size = max(dataset.count() // n_parallelism, 1) + updated_ds = dataset.map_batches( + compute_q_and_v_values, + batch_size=batch_size, + batch_format="pandas", + fn_kwargs={ + "model_class": self.model.__class__, + "model_state": self.model.get_state(), + "compute_q_values": False, + }, + ) + + v_behavior = updated_ds.mean("rewards") + v_target = updated_ds.mean("v_values") + v_gain_mean = v_target / v_behavior + v_gain_ste = ( + updated_ds.std("v_values") / v_behavior / math.sqrt(dataset.count()) + ) + + return { + "v_behavior": v_behavior, + "v_target": v_target, + "v_gain_mean": v_gain_mean, + "v_gain_ste": v_gain_ste, + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/doubly_robust.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/doubly_robust.py new file mode 100644 index 0000000000000000000000000000000000000000..4341055789b1bdc565199796a1dc2e29013fffcc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/doubly_robust.py @@ -0,0 +1,253 @@ +import logging +import numpy as np +import math +import pandas as pd + +from typing import Dict, Any, Optional, List + +from ray.data import Dataset + +from ray.rllib.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch, convert_ma_batch_to_sample_batch +from ray.rllib.utils.annotations import DeveloperAPI, override +from ray.rllib.utils.typing import SampleBatchType +from ray.rllib.utils.numpy import convert_to_numpy + +from ray.rllib.offline.estimators.off_policy_estimator import OffPolicyEstimator +from ray.rllib.offline.estimators.fqe_torch_model import FQETorchModel +from ray.rllib.offline.offline_evaluator import OfflineEvaluator +from ray.rllib.offline.offline_evaluation_utils import ( + compute_is_weights, + compute_q_and_v_values, +) + +logger = logging.getLogger() + + +@DeveloperAPI +class DoublyRobust(OffPolicyEstimator): + r"""The Doubly Robust estimator. + + Let s_t, a_t, and r_t be the state, action, and reward at timestep t. + + This method trains a Q-model for the evaluation policy \pi_e on behavior + data generated by \pi_b. Currently, RLlib implements this using + Fitted-Q Evaluation (FQE). You can also implement your own model + and pass it in as `q_model_config = {"type": your_model_class, **your_kwargs}`. + + For behavior policy \pi_b and evaluation policy \pi_e, define the + cumulative importance ratio at timestep t as: + p_t = \sum_{t'=0}^t (\pi_e(a_{t'} | s_{t'}) / \pi_b(a_{t'} | s_{t'})). + + Consider an episode with length T. Let V_T = 0. + For all t in {0, T - 1}, use the following recursive update: + V_t^DR = (\sum_{a \in A} \pi_e(a | s_t) Q(s_t, a)) + + p_t * (r_t + \gamma * V_{t+1}^DR - Q(s_t, a_t)) + + This estimator computes the expected return for \pi_e for an episode as: + V^{\pi_e}(s_0) = V_0^DR + and returns the mean and standard deviation over episodes. + + For more information refer to https://arxiv.org/pdf/1911.06854.pdf""" + + @override(OffPolicyEstimator) + def __init__( + self, + policy: Policy, + gamma: float, + epsilon_greedy: float = 0.0, + normalize_weights: bool = True, + q_model_config: Optional[Dict] = None, + ): + """Initializes a Doubly Robust OPE Estimator. + + Args: + policy: Policy to evaluate. + gamma: Discount factor of the environment. + epsilon_greedy: The probability by which we act acording to a fully random + policy during deployment. With 1-epsilon_greedy we act + according the target policy. + normalize_weights: If True, the inverse propensity scores are normalized to + their sum across the entire dataset. The effect of this is similar to + weighted importance sampling compared to standard importance sampling. + q_model_config: Arguments to specify the Q-model. Must specify + a `type` key pointing to the Q-model class. + This Q-model is trained in the train() method and is used + to compute the state-value and Q-value estimates + for the DoublyRobust estimator. + It must implement `train`, `estimate_q`, and `estimate_v`. + TODO (Rohan138): Unify this with RLModule API. + """ + + super().__init__(policy, gamma, epsilon_greedy) + q_model_config = q_model_config or {} + q_model_config["gamma"] = gamma + + self._model_cls = q_model_config.pop("type", FQETorchModel) + self._model_configs = q_model_config + self._normalize_weights = normalize_weights + + self.model = self._model_cls( + policy=policy, + **q_model_config, + ) + assert hasattr( + self.model, "estimate_v" + ), "self.model must implement `estimate_v`!" + assert hasattr( + self.model, "estimate_q" + ), "self.model must implement `estimate_q`!" + + @override(OffPolicyEstimator) + def estimate_on_single_episode(self, episode: SampleBatch) -> Dict[str, Any]: + estimates_per_epsiode = {} + + rewards, old_prob = episode["rewards"], episode["action_prob"] + new_prob = self.compute_action_probs(episode) + + weight = new_prob / old_prob + + v_behavior = 0.0 + v_target = 0.0 + q_values = self.model.estimate_q(episode) + q_values = convert_to_numpy(q_values) + v_values = self.model.estimate_v(episode) + v_values = convert_to_numpy(v_values) + assert q_values.shape == v_values.shape == (episode.count,) + + for t in reversed(range(episode.count)): + v_behavior = rewards[t] + self.gamma * v_behavior + v_target = v_values[t] + weight[t] * ( + rewards[t] + self.gamma * v_target - q_values[t] + ) + v_target = v_target.item() + + estimates_per_epsiode["v_behavior"] = v_behavior + estimates_per_epsiode["v_target"] = v_target + + return estimates_per_epsiode + + @override(OffPolicyEstimator) + def estimate_on_single_step_samples( + self, batch: SampleBatch + ) -> Dict[str, List[float]]: + estimates_per_epsiode = {} + + rewards, old_prob = batch["rewards"], batch["action_prob"] + new_prob = self.compute_action_probs(batch) + + q_values = self.model.estimate_q(batch) + q_values = convert_to_numpy(q_values) + v_values = self.model.estimate_v(batch) + v_values = convert_to_numpy(v_values) + + v_behavior = rewards + + weight = new_prob / old_prob + v_target = v_values + weight * (rewards - q_values) + + estimates_per_epsiode["v_behavior"] = v_behavior + estimates_per_epsiode["v_target"] = v_target + + return estimates_per_epsiode + + @override(OffPolicyEstimator) + def train(self, batch: SampleBatchType) -> Dict[str, Any]: + """Trains self.model on the given batch. + + Args: + batch: A SampleBatch or MultiAgentbatch to train on + + Returns: + A dict with key "loss" and value as the mean training loss. + """ + batch = convert_ma_batch_to_sample_batch(batch) + losses = self.model.train(batch) + return {"loss": np.mean(losses)} + + @override(OfflineEvaluator) + def estimate_on_dataset( + self, dataset: Dataset, *, n_parallelism: int = ... + ) -> Dict[str, Any]: + """Estimates the policy value using the Doubly Robust estimator. + + The doubly robust estimator uses normalization of importance sampling weights + (aka. propensity ratios) to the average of the importance weights across the + entire dataset. This is done to reduce the variance of the estimate (similar to + weighted importance sampling). You can disable this by setting + `normalize_weights=False` in the constructor. + + Note: This estimate works for only discrete action spaces for now. + + Args: + dataset: Dataset to compute the estimate on. Each record in dataset should + include the following columns: `obs`, `actions`, `action_prob` and + `rewards`. The `obs` on each row shoud be a vector of D dimensions. + n_parallelism: Number of parallelism to use for the computation. + + Returns: + A dict with the following keys: + v_target: The estimated value of the target policy. + v_behavior: The estimated value of the behavior policy. + v_gain: The estimated gain of the target policy over the behavior + policy. + v_std: The standard deviation of the estimated value of the target. + """ + + # step 1: compute the weights and weighted rewards + batch_size = max(dataset.count() // n_parallelism, 1) + updated_ds = dataset.map_batches( + compute_is_weights, + batch_size=batch_size, + batch_format="pandas", + fn_kwargs={ + "policy_state": self.policy.get_state(), + "estimator_class": self.__class__, + }, + ) + + # step 2: compute q_values and v_values + batch_size = max(updated_ds.count() // n_parallelism, 1) + updated_ds = updated_ds.map_batches( + compute_q_and_v_values, + batch_size=batch_size, + batch_format="pandas", + fn_kwargs={ + "model_class": self.model.__class__, + "model_state": self.model.get_state(), + }, + ) + + # step 3: compute the v_target + def compute_v_target(batch: pd.DataFrame, normalizer: float = 1.0): + weights = batch["weights"] / normalizer + batch["v_target"] = batch["v_values"] + weights * ( + batch["rewards"] - batch["q_values"] + ) + batch["v_behavior"] = batch["rewards"] + return batch + + normalizer = updated_ds.mean("weights") if self._normalize_weights else 1.0 + updated_ds = updated_ds.map_batches( + compute_v_target, + batch_size=batch_size, + batch_format="pandas", + fn_kwargs={"normalizer": normalizer}, + ) + + v_behavior = updated_ds.mean("v_behavior") + v_target = updated_ds.mean("v_target") + v_gain_mean = v_target / v_behavior + v_gain_ste = ( + updated_ds.std("v_target") + / normalizer + / v_behavior + / math.sqrt(dataset.count()) + ) + + return { + "v_behavior": v_behavior, + "v_target": v_target, + "v_gain_mean": v_gain_mean, + "v_gain_ste": v_gain_ste, + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/feature_importance.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/feature_importance.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d4d171893239f51936dc9f1bd33803a79b1f55 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/feature_importance.py @@ -0,0 +1,11 @@ +from ray.rllib.offline.feature_importance import FeatureImportance + +__all__ = ["FeatureImportance"] + +from ray.rllib.utils.deprecation import deprecation_warning + +deprecation_warning( + "ray.rllib.offline.estimators.feature_importance.FeatureImportance", + "ray.rllib.offline.feature_importance.FeatureImportance", + error=True, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/fqe_torch_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/fqe_torch_model.py new file mode 100644 index 0000000000000000000000000000000000000000..f071640a9afd380ad30f549113085f579cd86fa9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/fqe_torch_model.py @@ -0,0 +1,297 @@ +from typing import Dict, Any +from ray.rllib.models.utils import get_initializer +from ray.rllib.policy import Policy + +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.annotations import is_overridden +from ray.rllib.utils.typing import ModelConfigDict, TensorType +from gymnasium.spaces import Discrete + +torch, nn = try_import_torch() + +# TODO: Create a config object for FQE and unify it with the RLModule API + + +@DeveloperAPI +class FQETorchModel: + """Pytorch implementation of the Fitted Q-Evaluation (FQE) model from + https://arxiv.org/abs/1911.06854 + """ + + def __init__( + self, + policy: Policy, + gamma: float, + model_config: ModelConfigDict = None, + n_iters: int = 1, + lr: float = 1e-3, + min_loss_threshold: float = 1e-4, + clip_grad_norm: float = 100.0, + minibatch_size: int = None, + polyak_coef: float = 1.0, + ) -> None: + """ + Args: + policy: Policy to evaluate. + gamma: Discount factor of the environment. + model_config: The ModelConfigDict for self.q_model, defaults to: + { + "fcnet_hiddens": [8, 8], + "fcnet_activation": "relu", + "vf_share_layers": True, + }, + n_iters: Number of gradient steps to run on batch, defaults to 1 + lr: Learning rate for Adam optimizer + min_loss_threshold: Early stopping if mean loss < min_loss_threshold + clip_grad_norm: Clip loss gradients to this maximum value + minibatch_size: Minibatch size for training Q-function; + if None, train on the whole batch + polyak_coef: Polyak averaging factor for target Q-function + """ + self.policy = policy + assert isinstance( + policy.action_space, Discrete + ), f"{self.__class__.__name__} only supports discrete action spaces!" + self.gamma = gamma + self.observation_space = policy.observation_space + self.action_space = policy.action_space + + if model_config is None: + model_config = { + "fcnet_hiddens": [32, 32, 32], + "fcnet_activation": "relu", + "vf_share_layers": True, + } + self.model_config = model_config + + self.device = self.policy.device + self.q_model: TorchModelV2 = ModelCatalog.get_model_v2( + self.observation_space, + self.action_space, + self.action_space.n, + model_config, + framework="torch", + name="TorchQModel", + ).to(self.device) + + self.target_q_model: TorchModelV2 = ModelCatalog.get_model_v2( + self.observation_space, + self.action_space, + self.action_space.n, + model_config, + framework="torch", + name="TargetTorchQModel", + ).to(self.device) + + self.n_iters = n_iters + self.lr = lr + self.min_loss_threshold = min_loss_threshold + self.clip_grad_norm = clip_grad_norm + self.minibatch_size = minibatch_size + self.polyak_coef = polyak_coef + self.optimizer = torch.optim.Adam(self.q_model.variables(), self.lr) + initializer = get_initializer("xavier_uniform", framework="torch") + # Hard update target + self.update_target(polyak_coef=1.0) + + def f(m): + if isinstance(m, nn.Linear): + initializer(m.weight) + + self.initializer = f + + def train(self, batch: SampleBatch) -> TensorType: + """Trains self.q_model using FQE loss on given batch. + + Args: + batch: A SampleBatch of episodes to train on + + Returns: + A list of losses for each training iteration + """ + losses = [] + minibatch_size = self.minibatch_size or batch.count + # Copy batch for shuffling + batch = batch.copy(shallow=True) + for _ in range(self.n_iters): + minibatch_losses = [] + batch.shuffle() + for idx in range(0, batch.count, minibatch_size): + minibatch = batch[idx : idx + minibatch_size] + obs = torch.tensor(minibatch[SampleBatch.OBS], device=self.device) + actions = torch.tensor( + minibatch[SampleBatch.ACTIONS], + device=self.device, + dtype=int, + ) + rewards = torch.tensor( + minibatch[SampleBatch.REWARDS], device=self.device + ) + next_obs = torch.tensor( + minibatch[SampleBatch.NEXT_OBS], device=self.device + ) + dones = torch.tensor( + minibatch[SampleBatch.TERMINATEDS], device=self.device, dtype=float + ) + + # Compute Q-values for current obs + q_values, _ = self.q_model({"obs": obs}, [], None) + q_acts = torch.gather(q_values, -1, actions.unsqueeze(-1)).squeeze(-1) + + next_action_probs = self._compute_action_probs(next_obs) + + # Compute Q-values for next obs + with torch.no_grad(): + next_q_values, _ = self.target_q_model({"obs": next_obs}, [], None) + + # Compute estimated state value next_v = E_{a ~ pi(s)} [Q(next_obs,a)] + next_v = torch.sum(next_q_values * next_action_probs, axis=-1) + targets = rewards + (1 - dones) * self.gamma * next_v + loss = (targets - q_acts) ** 2 + loss = torch.mean(loss) + self.optimizer.zero_grad() + loss.backward() + nn.utils.clip_grad.clip_grad_norm_( + self.q_model.variables(), self.clip_grad_norm + ) + self.optimizer.step() + minibatch_losses.append(loss.item()) + iter_loss = sum(minibatch_losses) / len(minibatch_losses) + losses.append(iter_loss) + if iter_loss < self.min_loss_threshold: + break + self.update_target() + return losses + + def estimate_q(self, batch: SampleBatch) -> TensorType: + obs = torch.tensor(batch[SampleBatch.OBS], device=self.device) + with torch.no_grad(): + q_values, _ = self.q_model({"obs": obs}, [], None) + actions = torch.tensor( + batch[SampleBatch.ACTIONS], device=self.device, dtype=int + ) + q_values = torch.gather(q_values, -1, actions.unsqueeze(-1)).squeeze(-1) + return q_values + + def estimate_v(self, batch: SampleBatch) -> TensorType: + obs = torch.tensor(batch[SampleBatch.OBS], device=self.device) + with torch.no_grad(): + q_values, _ = self.q_model({"obs": obs}, [], None) + # Compute pi(a | s) for each action a in policy.action_space + action_probs = self._compute_action_probs(obs) + v_values = torch.sum(q_values * action_probs, axis=-1) + return v_values + + def update_target(self, polyak_coef=None): + # Update_target will be called periodically to copy Q network to + # target Q network, using (soft) polyak_coef-synching. + polyak_coef = polyak_coef or self.polyak_coef + model_state_dict = self.q_model.state_dict() + # Support partial (soft) synching. + # If polyak_coef == 1.0: Full sync from Q-model to target Q-model. + target_state_dict = self.target_q_model.state_dict() + model_state_dict = { + k: polyak_coef * model_state_dict[k] + (1 - polyak_coef) * v + for k, v in target_state_dict.items() + } + + self.target_q_model.load_state_dict(model_state_dict) + + def _compute_action_probs(self, obs: TensorType) -> TensorType: + """Compute action distribution over the action space. + + Args: + obs: A tensor of observations of shape (batch_size * obs_dim) + + Returns: + action_probs: A tensor of action probabilities + of shape (batch_size * action_dim) + """ + input_dict = {SampleBatch.OBS: obs} + seq_lens = torch.ones(len(obs), device=self.device, dtype=int) + state_batches = [] + if is_overridden(self.policy.action_distribution_fn): + try: + # TorchPolicyV2 function signature + dist_inputs, dist_class, _ = self.policy.action_distribution_fn( + self.policy.model, + obs_batch=input_dict, + state_batches=state_batches, + seq_lens=seq_lens, + explore=False, + is_training=False, + ) + except TypeError: + # TorchPolicyV1 function signature for compatibility with DQN + # TODO: Remove this once DQNTorchPolicy is migrated to PolicyV2 + dist_inputs, dist_class, _ = self.policy.action_distribution_fn( + self.policy, + self.policy.model, + input_dict=input_dict, + state_batches=state_batches, + seq_lens=seq_lens, + explore=False, + is_training=False, + ) + else: + dist_class = self.policy.dist_class + dist_inputs, _ = self.policy.model(input_dict, state_batches, seq_lens) + action_dist = dist_class(dist_inputs, self.policy.model) + assert isinstance( + action_dist.dist, torch.distributions.categorical.Categorical + ), "FQE only supports Categorical or MultiCategorical distributions!" + action_probs = action_dist.dist.probs + return action_probs + + def get_state(self) -> Dict[str, Any]: + """Returns the current state of the FQE Model.""" + return { + "policy_state": self.policy.get_state(), + "model_config": self.model_config, + "n_iters": self.n_iters, + "lr": self.lr, + "min_loss_threshold": self.min_loss_threshold, + "clip_grad_norm": self.clip_grad_norm, + "minibatch_size": self.minibatch_size, + "polyak_coef": self.polyak_coef, + "gamma": self.gamma, + "q_model_state": self.q_model.state_dict(), + "target_q_model_state": self.target_q_model.state_dict(), + } + + def set_state(self, state: Dict[str, Any]) -> None: + """Sets the current state of the FQE Model. + Args: + state: A state dict returned by `get_state()`. + """ + self.n_iters = state["n_iters"] + self.lr = state["lr"] + self.min_loss_threshold = state["min_loss_threshold"] + self.clip_grad_norm = state["clip_grad_norm"] + self.minibatch_size = state["minibatch_size"] + self.polyak_coef = state["polyak_coef"] + self.gamma = state["gamma"] + self.policy.set_state(state["policy_state"]) + self.q_model.load_state_dict(state["q_model_state"]) + self.target_q_model.load_state_dict(state["target_q_model_state"]) + + @classmethod + def from_state(cls, state: Dict[str, Any]) -> "FQETorchModel": + """Creates a FQE Model from a state dict. + + Args: + state: A state dict returned by `get_state`. + + Returns: + An instance of the FQETorchModel. + """ + policy = Policy.from_state(state["policy_state"]) + model = cls( + policy=policy, gamma=state["gamma"], model_config=state["model_config"] + ) + model.set_state(state) + return model diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/importance_sampling.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/importance_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..630859820948b7f1139ab27649f21096ce2f28e9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/importance_sampling.py @@ -0,0 +1,126 @@ +from typing import Dict, List, Any +import math + +from ray.data import Dataset + +from ray.rllib.utils.annotations import override, DeveloperAPI +from ray.rllib.offline.offline_evaluator import OfflineEvaluator +from ray.rllib.offline.offline_evaluation_utils import ( + remove_time_dim, + compute_is_weights, +) +from ray.rllib.offline.estimators.off_policy_estimator import OffPolicyEstimator +from ray.rllib.policy.sample_batch import SampleBatch + + +@DeveloperAPI +class ImportanceSampling(OffPolicyEstimator): + r"""The step-wise IS estimator. + + Let s_t, a_t, and r_t be the state, action, and reward at timestep t. + + For behavior policy \pi_b and evaluation policy \pi_e, define the + cumulative importance ratio at timestep t as: + p_t = \sum_{t'=0}^t (\pi_e(a_{t'} | s_{t'}) / \pi_b(a_{t'} | s_{t'})). + + This estimator computes the expected return for \pi_e for an episode as: + V^{\pi_e}(s_0) = \sum_t \gamma ^ {t} * p_t * r_t + and returns the mean and standard deviation over episodes. + + For more information refer to https://arxiv.org/pdf/1911.06854.pdf""" + + @override(OffPolicyEstimator) + def estimate_on_single_episode(self, episode: SampleBatch) -> Dict[str, float]: + estimates_per_epsiode = {} + + rewards, old_prob = episode["rewards"], episode["action_prob"] + new_prob = self.compute_action_probs(episode) + + # calculate importance ratios + p = [] + for t in range(episode.count): + if t == 0: + pt_prev = 1.0 + else: + pt_prev = p[t - 1] + p.append(pt_prev * new_prob[t] / old_prob[t]) + + # calculate stepwise IS estimate + v_behavior = 0.0 + v_target = 0.0 + for t in range(episode.count): + v_behavior += rewards[t] * self.gamma**t + v_target += p[t] * rewards[t] * self.gamma**t + + estimates_per_epsiode["v_behavior"] = v_behavior + estimates_per_epsiode["v_target"] = v_target + + return estimates_per_epsiode + + @override(OffPolicyEstimator) + def estimate_on_single_step_samples( + self, batch: SampleBatch + ) -> Dict[str, List[float]]: + estimates_per_epsiode = {} + + rewards, old_prob = batch["rewards"], batch["action_prob"] + new_prob = self.compute_action_probs(batch) + + weights = new_prob / old_prob + v_behavior = rewards + v_target = weights * rewards + + estimates_per_epsiode["v_behavior"] = v_behavior + estimates_per_epsiode["v_target"] = v_target + + return estimates_per_epsiode + + @override(OfflineEvaluator) + def estimate_on_dataset( + self, dataset: Dataset, *, n_parallelism: int = ... + ) -> Dict[str, Any]: + """Computes the Importance sampling estimate on the given dataset. + + Note: This estimate works for both continuous and discrete action spaces. + + Args: + dataset: Dataset to compute the estimate on. Each record in dataset should + include the following columns: `obs`, `actions`, `action_prob` and + `rewards`. The `obs` on each row shoud be a vector of D dimensions. + n_parallelism: The number of parallel workers to use. + + Returns: + A dictionary containing the following keys: + v_target: The estimated value of the target policy. + v_behavior: The estimated value of the behavior policy. + v_gain_mean: The mean of the gain of the target policy over the + behavior policy. + v_gain_ste: The standard error of the gain of the target policy over + the behavior policy. + """ + batch_size = max(dataset.count() // n_parallelism, 1) + dataset = dataset.map_batches( + remove_time_dim, batch_size=batch_size, batch_format="pandas" + ) + updated_ds = dataset.map_batches( + compute_is_weights, + batch_size=batch_size, + batch_format="pandas", + fn_kwargs={ + "policy_state": self.policy.get_state(), + "estimator_class": self.__class__, + }, + ) + v_target = updated_ds.mean("weighted_rewards") + v_behavior = updated_ds.mean("rewards") + v_gain_mean = v_target / v_behavior + v_gain_ste = ( + updated_ds.std("weighted_rewards") / v_behavior / math.sqrt(dataset.count()) + ) + + return { + "v_target": v_target, + "v_behavior": v_behavior, + "v_gain_mean": v_gain_mean, + "v_gain_ste": v_gain_ste, + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/off_policy_estimator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/off_policy_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6ef95eb78bbaa24cec1f7598ce494f954f945d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/off_policy_estimator.py @@ -0,0 +1,248 @@ +import gymnasium as gym +import numpy as np +import tree +from typing import Dict, Any, List + +import logging +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy import Policy +from ray.rllib.policy.sample_batch import convert_ma_batch_to_sample_batch +from ray.rllib.utils.policy import compute_log_likelihoods_from_input_dict +from ray.rllib.utils.annotations import ( + DeveloperAPI, + ExperimentalAPI, + OverrideToImplementCustomLogic, +) +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import TensorType, SampleBatchType +from ray.rllib.offline.offline_evaluator import OfflineEvaluator + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class OffPolicyEstimator(OfflineEvaluator): + """Interface for an off policy estimator for counterfactual evaluation.""" + + @DeveloperAPI + def __init__( + self, + policy: Policy, + gamma: float = 0.0, + epsilon_greedy: float = 0.0, + ): + """Initializes an OffPolicyEstimator instance. + + Args: + policy: Policy to evaluate. + gamma: Discount factor of the environment. + epsilon_greedy: The probability by which we act acording to a fully random + policy during deployment. With 1-epsilon_greedy we act according the target + policy. + # TODO (kourosh): convert the input parameters to a config dict. + """ + super().__init__(policy) + self.gamma = gamma + self.epsilon_greedy = epsilon_greedy + + @DeveloperAPI + def estimate_on_single_episode(self, episode: SampleBatch) -> Dict[str, Any]: + """Returns off-policy estimates for the given one episode. + + Args: + batch: The episode to calculate the off-policy estimates (OPE) on. The + episode must be a sample batch type that contains the fields "obs", + "actions", and "action_prob" and it needs to represent a + complete trajectory. + + Returns: + The off-policy estimates (OPE) calculated on the given episode. The returned + dict can be any arbitrary mapping of strings to metrics. + """ + raise NotImplementedError + + @DeveloperAPI + def estimate_on_single_step_samples( + self, + batch: SampleBatch, + ) -> Dict[str, List[float]]: + """Returns off-policy estimates for the batch of single timesteps. This is + highly optimized for bandits assuming each episode is a single timestep. + + Args: + batch: The batch to calculate the off-policy estimates (OPE) on. The + batch must be a sample batch type that contains the fields "obs", + "actions", and "action_prob". + + Returns: + The off-policy estimates (OPE) calculated on the given batch of single time + step samples. The returned dict can be any arbitrary mapping of strings to + a list of floats capturing the values per each record. + """ + raise NotImplementedError + + def on_before_split_batch_by_episode( + self, sample_batch: SampleBatch + ) -> SampleBatch: + """Called before the batch is split by episode. You can perform any + preprocessing on the batch that you want here. + e.g. adding done flags to the batch, or reseting some stats that you want to + track per episode later during estimation, .etc. + + Args: + sample_batch: The batch to split by episode. This contains multiple + episodes. + + Returns: + The modified batch before calling split_by_episode(). + """ + return sample_batch + + @OverrideToImplementCustomLogic + def on_after_split_batch_by_episode( + self, all_episodes: List[SampleBatch] + ) -> List[SampleBatch]: + """Called after the batch is split by episode. You can perform any + postprocessing on each episode that you want here. + e.g. computing advantage per episode, .etc. + + Args: + all_episodes: The list of episodes in the original batch. Each element is a + sample batch type that is a single episode. + """ + + return all_episodes + + @OverrideToImplementCustomLogic + def peek_on_single_episode(self, episode: SampleBatch) -> None: + """This is called on each episode before it is passed to + estimate_on_single_episode(). Using this method, you can get a peek at the + entire validation dataset before runnining the estimation. For examlpe if you + need to perform any normalizations of any sorts on the dataset, you can compute + the normalization parameters here. + + Args: + episode: The episode that is split from the original batch. This is a + sample batch type that is a single episode. + """ + pass + + @DeveloperAPI + def estimate( + self, batch: SampleBatchType, split_batch_by_episode: bool = True + ) -> Dict[str, Any]: + """Compute off-policy estimates. + + Args: + batch: The batch to calculate the off-policy estimates (OPE) on. The + batch must contain the fields "obs", "actions", and "action_prob". + split_batch_by_episode: Whether to split the batch by episode. + + Returns: + The off-policy estimates (OPE) calculated on the given batch. The returned + dict can be any arbitrary mapping of strings to metrics. + The dict consists of the following metrics: + - v_behavior: The discounted return averaged over episodes in the batch + - v_behavior_std: The standard deviation corresponding to v_behavior + - v_target: The estimated discounted return for `self.policy`, + averaged over episodes in the batch + - v_target_std: The standard deviation corresponding to v_target + - v_gain: v_target / max(v_behavior, 1e-8) + - v_delta: The difference between v_target and v_behavior. + """ + batch = convert_ma_batch_to_sample_batch(batch) + self.check_action_prob_in_batch(batch) + estimates_per_epsiode = [] + if split_batch_by_episode: + batch = self.on_before_split_batch_by_episode(batch) + all_episodes = batch.split_by_episode() + all_episodes = self.on_after_split_batch_by_episode(all_episodes) + for episode in all_episodes: + assert len(set(episode[SampleBatch.EPS_ID])) == 1, ( + "The episode must contain only one episode id. For some reason " + "the split_by_episode() method could not successfully split " + "the batch by episodes. Each row in the dataset should be " + "one episode. Check your evaluation dataset for errors." + ) + self.peek_on_single_episode(episode) + + for episode in all_episodes: + estimate_step_results = self.estimate_on_single_episode(episode) + estimates_per_epsiode.append(estimate_step_results) + + # turn a list of identical dicts into a dict of lists + estimates_per_epsiode = tree.map_structure( + lambda *x: list(x), *estimates_per_epsiode + ) + else: + # the returned dict is a mapping of strings to a list of floats + estimates_per_epsiode = self.estimate_on_single_step_samples(batch) + + estimates = { + "v_behavior": np.mean(estimates_per_epsiode["v_behavior"]), + "v_behavior_std": np.std(estimates_per_epsiode["v_behavior"]), + "v_target": np.mean(estimates_per_epsiode["v_target"]), + "v_target_std": np.std(estimates_per_epsiode["v_target"]), + } + estimates["v_gain"] = estimates["v_target"] / max(estimates["v_behavior"], 1e-8) + estimates["v_delta"] = estimates["v_target"] - estimates["v_behavior"] + + return estimates + + @DeveloperAPI + def check_action_prob_in_batch(self, batch: SampleBatchType) -> None: + """Checks if we support off policy estimation (OPE) on given batch. + + Args: + batch: The batch to check. + + Raises: + ValueError: In case `action_prob` key is not in batch + """ + + if "action_prob" not in batch: + raise ValueError( + "Off-policy estimation is not possible unless the inputs " + "include action probabilities (i.e., the policy is stochastic " + "and emits the 'action_prob' key). For DQN this means using " + "`exploration_config: {type: 'SoftQ'}`. You can also set " + "`off_policy_estimation_methods: {}` to disable estimation." + ) + + @ExperimentalAPI + def compute_action_probs(self, batch: SampleBatch): + log_likelihoods = compute_log_likelihoods_from_input_dict(self.policy, batch) + new_prob = np.exp(convert_to_numpy(log_likelihoods)) + + if self.epsilon_greedy > 0.0: + if not isinstance(self.policy.action_space, gym.spaces.Discrete): + raise ValueError( + "Evaluation with epsilon-greedy exploration is only supported " + "with discrete action spaces." + ) + eps = self.epsilon_greedy + new_prob = new_prob * (1 - eps) + eps / self.policy.action_space.n + + return new_prob + + @DeveloperAPI + def train(self, batch: SampleBatchType) -> Dict[str, Any]: + """Train a model for Off-Policy Estimation. + + Args: + batch: SampleBatch to train on + + Returns: + Any optional metrics to return from the estimator + """ + return {} + + @Deprecated( + old="OffPolicyEstimator.action_log_likelihood", + new="ray.rllib.utils.policy.compute_log_likelihoods_from_input_dict", + error=True, + ) + def action_log_likelihood(self, batch: SampleBatchType) -> TensorType: + log_likelihoods = compute_log_likelihoods_from_input_dict(self.policy, batch) + return convert_to_numpy(log_likelihoods) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/weighted_importance_sampling.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/weighted_importance_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..cfca393a021253ccdd346ea529c3f0d54690067d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/estimators/weighted_importance_sampling.py @@ -0,0 +1,185 @@ +from typing import Dict, Any, List +import numpy as np +import math + +from ray.data import Dataset + +from ray.rllib.offline.offline_evaluator import OfflineEvaluator +from ray.rllib.offline.estimators.off_policy_estimator import OffPolicyEstimator +from ray.rllib.offline.offline_evaluation_utils import ( + remove_time_dim, + compute_is_weights, +) +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy import Policy +from ray.rllib.utils.annotations import override, DeveloperAPI + + +@DeveloperAPI +class WeightedImportanceSampling(OffPolicyEstimator): + r"""The step-wise WIS estimator. + + Let s_t, a_t, and r_t be the state, action, and reward at timestep t. + + For behavior policy \pi_b and evaluation policy \pi_e, define the + cumulative importance ratio at timestep t as: + p_t = \sum_{t'=0}^t (\pi_e(a_{t'} | s_{t'}) / \pi_b(a_{t'} | s_{t'})). + + Define the average importance ratio over episodes i in the dataset D as: + w_t = \sum_{i \in D} p^(i)_t / |D| + + This estimator computes the expected return for \pi_e for an episode as: + V^{\pi_e}(s_0) = \E[\sum_t \gamma ^ {t} * (p_t / w_t) * r_t] + and returns the mean and standard deviation over episodes. + + For more information refer to https://arxiv.org/pdf/1911.06854.pdf""" + + @override(OffPolicyEstimator) + def __init__(self, policy: Policy, gamma: float, epsilon_greedy: float = 0.0): + super().__init__(policy, gamma, epsilon_greedy) + # map from time to cummulative propensity values + self.cummulative_ips_values = [] + # map from time to number of episodes that reached this time + self.episode_timestep_count = [] + # map from eps id to mapping from time to propensity values + self.p = {} + + @override(OffPolicyEstimator) + def estimate_on_single_episode(self, episode: SampleBatch) -> Dict[str, Any]: + estimates_per_epsiode = {} + rewards = episode["rewards"] + + eps_id = episode[SampleBatch.EPS_ID][0] + if eps_id not in self.p: + raise ValueError( + f"Cannot find target weight for episode {eps_id}. " + f"Did it go though the peek_on_single_episode() function?" + ) + + # calculate stepwise weighted IS estimate + v_behavior = 0.0 + v_target = 0.0 + episode_p = self.p[eps_id] + for t in range(episode.count): + v_behavior += rewards[t] * self.gamma**t + w_t = self.cummulative_ips_values[t] / self.episode_timestep_count[t] + v_target += episode_p[t] / w_t * rewards[t] * self.gamma**t + + estimates_per_epsiode["v_behavior"] = v_behavior + estimates_per_epsiode["v_target"] = v_target + + return estimates_per_epsiode + + @override(OffPolicyEstimator) + def estimate_on_single_step_samples( + self, batch: SampleBatch + ) -> Dict[str, List[float]]: + estimates_per_epsiode = {} + rewards, old_prob = batch["rewards"], batch["action_prob"] + new_prob = self.compute_action_probs(batch) + + weights = new_prob / old_prob + v_behavior = rewards + v_target = weights * rewards / np.mean(weights) + + estimates_per_epsiode["v_behavior"] = v_behavior + estimates_per_epsiode["v_target"] = v_target + estimates_per_epsiode["weights"] = weights + estimates_per_epsiode["new_prob"] = new_prob + estimates_per_epsiode["old_prob"] = old_prob + + return estimates_per_epsiode + + @override(OffPolicyEstimator) + def on_before_split_batch_by_episode( + self, sample_batch: SampleBatch + ) -> SampleBatch: + self.cummulative_ips_values = [] + self.episode_timestep_count = [] + self.p = {} + + return sample_batch + + @override(OffPolicyEstimator) + def peek_on_single_episode(self, episode: SampleBatch) -> None: + old_prob = episode["action_prob"] + new_prob = self.compute_action_probs(episode) + + # calculate importance ratios + episode_p = [] + for t in range(episode.count): + if t == 0: + pt_prev = 1.0 + else: + pt_prev = episode_p[t - 1] + episode_p.append(pt_prev * new_prob[t] / old_prob[t]) + + for t, p_t in enumerate(episode_p): + if t >= len(self.cummulative_ips_values): + self.cummulative_ips_values.append(p_t) + self.episode_timestep_count.append(1.0) + else: + self.cummulative_ips_values[t] += p_t + self.episode_timestep_count[t] += 1.0 + + eps_id = episode[SampleBatch.EPS_ID][0] + if eps_id in self.p: + raise ValueError( + f"eps_id {eps_id} was already passed to the peek function. " + f"Make sure dataset contains only unique episodes with unique ids." + ) + self.p[eps_id] = episode_p + + @override(OfflineEvaluator) + def estimate_on_dataset( + self, dataset: Dataset, *, n_parallelism: int = ... + ) -> Dict[str, Any]: + """Computes the weighted importance sampling estimate on a dataset. + + Note: This estimate works for both continuous and discrete action spaces. + + Args: + dataset: Dataset to compute the estimate on. Each record in dataset should + include the following columns: `obs`, `actions`, `action_prob` and + `rewards`. The `obs` on each row shoud be a vector of D dimensions. + n_parallelism: Number of parallel workers to use for the computation. + + Returns: + Dictionary with the following keys: + v_target: The weighted importance sampling estimate. + v_behavior: The behavior policy estimate. + v_gain_mean: The mean of the gain of the target policy over the + behavior policy. + v_gain_ste: The standard error of the gain of the target policy over + the behavior policy. + """ + # compute the weights and weighted rewards + batch_size = max(dataset.count() // n_parallelism, 1) + dataset = dataset.map_batches( + remove_time_dim, batch_size=batch_size, batch_format="pandas" + ) + updated_ds = dataset.map_batches( + compute_is_weights, + batch_size=batch_size, + batch_format="pandas", + fn_kwargs={ + "policy_state": self.policy.get_state(), + "estimator_class": self.__class__, + }, + ) + v_target = updated_ds.mean("weighted_rewards") / updated_ds.mean("weights") + v_behavior = updated_ds.mean("rewards") + v_gain_mean = v_target / v_behavior + v_gain_ste = ( + updated_ds.std("weighted_rewards") + / updated_ds.mean("weights") + / v_behavior + / math.sqrt(dataset.count()) + ) + + return { + "v_target": v_target, + "v_behavior": v_behavior, + "v_gain_mean": v_gain_mean, + "v_gain_ste": v_gain_ste, + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3d4d4b75707388ac8e6f3c2dca0a68cdc7b29e0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/dynamic_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/dynamic_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d1bf6d036cea891078a735aeb510a3b8342ff19 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/dynamic_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/dynamic_tf_policy_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/dynamic_tf_policy_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..048beca496a33ad8eed9d593d2bae58b7abbc944 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/dynamic_tf_policy_v2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/eager_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/eager_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcfe14ea0d240c5e57a9dd73cc4cf14d5fe3cae3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/eager_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/eager_tf_policy_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/eager_tf_policy_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..209389289cf78dbec0860a9c7381963a19f0d1a5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/eager_tf_policy_v2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5db93097bd2aeac2d8e8918f16190b671eff9c2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy_map.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy_map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de2b96e58db5d1b0721e1d111ac8bfef93b4c285 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy_map.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy_template.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea25bba6a971c65daf2a0aa6cc9a34120a3d013 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/policy_template.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/rnn_sequencing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/rnn_sequencing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a81fdf535c9adeb982a1781c3cd2aba3bf9f963a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/rnn_sequencing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/sample_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/sample_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7abb974847b2c8f3e661aba0e443b6145d341bfe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/sample_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_mixins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_mixins.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..133bc6e82f2767ca592c6c764b698fcec4eb6ae4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_mixins.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94d9f5887504e24ca47e6b7d2223e6aeeac4084f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_policy_template.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_policy_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e3b3d5c413df7c380a8f92c976be5f1d91a3d49 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/tf_policy_template.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_mixins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_mixins.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a60bc84a51f36291484c189fae58b5f60ef1e120 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_mixins.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f335a3664a1741a018e72fd21714309d25296f0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_policy_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_policy_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c56ca52bc77a4c80f5eaf406f0d7f8590cfbbba4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/torch_policy_v2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/view_requirement.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/view_requirement.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b0865353a909d18072d9f78a537197ea3e48c27 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__pycache__/view_requirement.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6bfc952919bee85d29f7d052026651d018f7972 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/__pycache__/cleanup_experiment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/__pycache__/cleanup_experiment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2261056c1ec91d7178a901b0b6d64048742e781f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/__pycache__/cleanup_experiment.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3f1c3abb484d82704b14ce99c606edf423de2d7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/atari_100k_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/atari_100k_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1bf6167e62e1dc361430203dd497210d2b02553 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/atari_100k_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/atari_200M_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/atari_200M_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31c170afb286565ab166968b0b7793f09ac41fb8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/atari_200M_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/cartpole_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/cartpole_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..439925e5b0f698e086b5ae5d302ae4efb704c4e5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/cartpole_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/dm_control_suite_vision_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/dm_control_suite_vision_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3668467a6e25bd9bb823ed07ec6ab12456c6fd3f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/dm_control_suite_vision_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/flappy_bird_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/flappy_bird_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8201c90101885a5744160bb2e3a1f89e53b1aff1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/flappy_bird_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/frozenlake_2x2_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/frozenlake_2x2_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efbb71db67969e4a57f212d85d6fd2a943b55731 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/frozenlake_2x2_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/frozenlake_4x4_deterministic_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/frozenlake_4x4_deterministic_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ace44ad4ea2eef8c4d6335b342480571e8494eae Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/frozenlake_4x4_deterministic_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/gymnasium_robotics_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/gymnasium_robotics_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..358d99cd15f9ee778635dd03de15c68afcbb08d6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/gymnasium_robotics_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/highway_env_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/highway_env_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b9c0b1f6ea059345efcd51aeb5f76042a89e769 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/highway_env_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/pendulum_dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/pendulum_dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b24f56c978102bfc146853b377004f562c4efb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/__pycache__/pendulum_dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/atari_100k_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/atari_100k_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..dabf4cfd96eadadd2ad4b716ab0f78533e88e457 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/atari_100k_dreamerv3.py @@ -0,0 +1,99 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" + +# Run with: +# python [this script name].py --env ale_py:ALE/[gym ID e.g. Pong-v5] + +# To see all available options: +# python [this script name].py --help + +import gymnasium as gym + +from ray import tune +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config +from ray.rllib.env.wrappers.atari_wrappers import wrap_atari_for_new_api_stack +from ray.rllib.utils.test_utils import add_rllib_example_script_args + +parser = add_rllib_example_script_args( + default_iters=1000000, + default_reward=20.0, + default_timesteps=100000, +) +parser.set_defaults(env="ale_py:ALE/Pong-v5") +# Use `parser` to add your own custom command line options to this script +# and (if needed) use their values to set up `config` below. +args = parser.parse_args() +# If we use >1 GPU and increase the batch size accordingly, we should also +# increase the number of envs per worker. +if args.num_envs_per_env_runner is None: + args.num_envs_per_env_runner = args.num_learners or 1 + + +# Create the DreamerV3-typical Atari setup. +def _env_creator(cfg): + return wrap_atari_for_new_api_stack( + gym.make(args.env, **cfg, render_mode="rgb_array"), + # No framestacking necessary for Dreamer. + framestack=None, + # No grayscaling necessary for Dreamer. + grayscale=False, + ) + + +tune.register_env("env", _env_creator) + +default_config = DreamerV3Config() +lr_multiplier = args.num_learners or 1 + +config = ( + DreamerV3Config() + .environment( + env="env", + # [2]: "We follow the evaluation protocol of Machado et al. (2018) with 200M + # environment steps, action repeat of 4, a time limit of 108,000 steps per + # episode that correspond to 30 minutes of game play, no access to life + # information, full action space, and sticky actions. Because the world model + # integrates information over time, DreamerV2 does not use frame stacking. + # The experiments use a single-task setup where a separate agent is trained + # for each game. Moreover, each agent uses only a single environment instance. + env_config={ + # "sticky actions" but not according to Danijar's 100k configs. + "repeat_action_probability": 0.0, + # "full action space" but not according to Danijar's 100k configs. + "full_action_space": False, + # Already done by MaxAndSkip wrapper: "action repeat" == 4. + "frameskip": 1, + }, + ) + .env_runners( + remote_worker_envs=(args.num_learners and args.num_learners > 1), + ) + .reporting( + metrics_num_episodes_for_smoothing=(args.num_learners or 1), + report_images_and_videos=False, + report_dream_data=False, + report_individual_batch_item_stats=False, + ) + # See Appendix A. + .training( + model_size="S", + training_ratio=1024, + batch_size_B=16 * (args.num_learners or 1), + world_model_lr=default_config.world_model_lr * lr_multiplier, + actor_lr=default_config.actor_lr * lr_multiplier, + critic_lr=default_config.critic_lr * lr_multiplier, + ) +) + + +if __name__ == "__main__": + from ray.rllib.utils.test_utils import run_rllib_example_script_experiment + + run_rllib_example_script_experiment(config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/atari_200M_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/atari_200M_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..9ae42a172adac35dc179bc9c2bab9fa756a63a8a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/atari_200M_dreamerv3.py @@ -0,0 +1,87 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" + +# Run with: +# python [this script name].py --env ale_py:ALE/[gym ID e.g. Pong-v5] + +# To see all available options: +# python [this script name].py --help + +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config +from ray.rllib.utils.test_utils import add_rllib_example_script_args + +parser = add_rllib_example_script_args( + default_iters=1000000, + default_reward=20.0, + default_timesteps=1000000, +) +# Use `parser` to add your own custom command line options to this script +# and (if needed) use their values to set up `config` below. +args = parser.parse_args() + +# If we use >1 GPU and increase the batch size accordingly, we should also +# increase the number of envs per worker. +if args.num_envs_per_env_runner is None: + args.num_envs_per_env_runner = 8 * (args.num_learners or 1) + +default_config = DreamerV3Config() +lr_multiplier = (args.num_learners or 1) ** 0.5 + +config = ( + DreamerV3Config() + .resources( + # For each (parallelized) env, we should provide a CPU. Lower this number + # if you don't have enough CPUs. + num_cpus_for_main_process=8 + * (args.num_learners or 1), + ) + .environment( + env=args.env, + # [2]: "We follow the evaluation protocol of Machado et al. (2018) with 200M + # environment steps, action repeat of 4, a time limit of 108,000 steps per + # episode that correspond to 30 minutes of game play, no access to life + # information, full action space, and sticky actions. Because the world model + # integrates information over time, DreamerV2 does not use frame stacking. + # The experiments use a single-task setup where a separate agent is trained + # for each game. Moreover, each agent uses only a single environment instance. + env_config={ + # "sticky actions" but not according to Danijar's 100k configs. + "repeat_action_probability": 0.0, + # "full action space" but not according to Danijar's 100k configs. + "full_action_space": False, + # Already done by MaxAndSkip wrapper: "action repeat" == 4. + "frameskip": 1, + }, + ) + .env_runners( + remote_worker_envs=True, + ) + .reporting( + metrics_num_episodes_for_smoothing=(args.num_learners or 1), + report_images_and_videos=False, + report_dream_data=False, + report_individual_batch_item_stats=False, + ) + # See Appendix A. + .training( + model_size="XL", + training_ratio=64, + batch_size_B=16 * (args.num_learners or 1), + world_model_lr=default_config.world_model_lr * lr_multiplier, + actor_lr=default_config.actor_lr * lr_multiplier, + critic_lr=default_config.critic_lr * lr_multiplier, + ) +) + + +if __name__ == "__main__": + from ray.rllib.utils.test_utils import run_rllib_example_script_experiment + + run_rllib_example_script_experiment(config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/cartpole_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/cartpole_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..87e5111397fe92377a7475ad9836901e238a481f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/cartpole_dreamerv3.py @@ -0,0 +1,22 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config + +# Run with: +# python [this script name].py + +config = ( + DreamerV3Config() + .environment("CartPole-v1") + .training( + model_size="XS", + training_ratio=1024, + ) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/dm_control_suite_vision_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/dm_control_suite_vision_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..645b4adb2d9004d70da3748bb1f052cdda64e806 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/dm_control_suite_vision_dreamerv3.py @@ -0,0 +1,87 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" + +# Run with: +# python [this script name].py --env DMC/[task]/[domain] (e.g. DMC/cartpole/swingup) + +# To see all available options: +# python [this script name].py --help + +from ray import tune +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config +from ray.rllib.env.wrappers.dm_control_wrapper import ActionClip, DMCEnv +from ray.rllib.utils.test_utils import add_rllib_example_script_args + +parser = add_rllib_example_script_args( + default_iters=1000000, + default_reward=800.0, + default_timesteps=1000000, +) +parser.set_defaults(env="DMC/cartpole/swingup") +# Use `parser` to add your own custom command line options to this script +# and (if needed) use their values to set up `config` below. +args = parser.parse_args() +# If we use >1 GPU and increase the batch size accordingly, we should also +# increase the number of envs per worker. +if args.num_envs_per_env_runner is None: + args.num_envs_per_env_runner = 4 * (args.num_learners or 1) + +parts = args.env.split("/") +assert len(parts) == 3, ( + "ERROR: DMC env must be formatted as 'DMC/[task]/[domain]', e.g. " + f"'DMC/cartpole/swingup'! You provided '{args.env}'." +) + + +def env_creator(cfg): + return ActionClip( + DMCEnv( + parts[1], + parts[2], + from_pixels=True, + channels_first=False, + ) + ) + + +tune.register_env("env", env_creator) + +default_config = DreamerV3Config() +lr_multiplier = (args.num_learners or 1) ** 0.5 + +config = ( + DreamerV3Config() + # Use image observations. + .environment(env="env") + .env_runners( + remote_worker_envs=True, + ) + .reporting( + metrics_num_episodes_for_smoothing=(args.num_learners or 1), + report_images_and_videos=False, + report_dream_data=False, + report_individual_batch_item_stats=False, + ) + # See Appendix A. + .training( + model_size="S", + training_ratio=512, + batch_size_B=16 * (args.num_learners or 1), + world_model_lr=default_config.world_model_lr * lr_multiplier, + actor_lr=default_config.actor_lr * lr_multiplier, + critic_lr=default_config.critic_lr * lr_multiplier, + ) +) + + +if __name__ == "__main__": + from ray.rllib.utils.test_utils import run_rllib_example_script_experiment + + run_rllib_example_script_experiment(config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/flappy_bird_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/flappy_bird_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..9df59d67f384c24623a16c1b9b8b8e270c71c258 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/flappy_bird_dreamerv3.py @@ -0,0 +1,81 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" + +# Run with: +# python [this script name].py + +# To see all available options: +# python [this script name].py --help + +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config +from ray import tune + + +# Number of GPUs to run on. +num_gpus = 0 + +# DreamerV3 config and default (1 GPU) learning rates. +config = DreamerV3Config() +w = config.world_model_lr +c = config.critic_lr + + +def _env_creator(ctx): + import flappy_bird_gymnasium # noqa doctest: +SKIP + import gymnasium as gym + from supersuit.generic_wrappers import resize_v1 + from ray.rllib.env.wrappers.atari_wrappers import NormalizedImageEnv + + return NormalizedImageEnv( + resize_v1( # resize to 64x64 and normalize images + gym.make("FlappyBird-rgb-v0", audio_on=False), x_size=64, y_size=64 + ) + ) + + +# Register the FlappyBird-rgb-v0 env including necessary wrappers via the +# `tune.register_env()` API. +tune.register_env("flappy-bird", _env_creator) + +# Further specify the DreamerV3 config object to use. +( + config.environment("flappy-bird") + .resources( + num_cpus_for_main_process=1, + ) + .learners( + num_learners=0 if num_gpus == 1 else num_gpus, + num_gpus_per_learner=1 if num_gpus else 0, + ) + .env_runners( + # If we use >1 GPU and increase the batch size accordingly, we should also + # increase the number of envs per worker. + num_envs_per_env_runner=8 * (num_gpus or 1), + remote_worker_envs=True, + ) + .reporting( + metrics_num_episodes_for_smoothing=(num_gpus or 1), + report_images_and_videos=False, + report_dream_data=False, + report_individual_batch_item_stats=False, + ) + # See Appendix A. + .training( + model_size="M", + training_ratio=64, + batch_size_B=16 * (num_gpus or 1), + # Use a well established 4-GPU lr scheduling recipe: + # ~ 1000 training updates with 0.4x[default rates], then over a few hundred + # steps, increase to 4x[default rates]. + world_model_lr=[[0, 0.4 * w], [8000, 0.4 * w], [10000, 3 * w]], + critic_lr=[[0, 0.4 * c], [8000, 0.4 * c], [10000, 3 * c]], + actor_lr=[[0, 0.4 * c], [8000, 0.4 * c], [10000, 3 * c]], + ) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/frozenlake_2x2_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/frozenlake_2x2_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..05e1509dc3262226fa4d8e4ce96d9358265915ed --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/frozenlake_2x2_dreamerv3.py @@ -0,0 +1,34 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config + +# Run with: +# python [this script name].py + +# To see all available options: +# python [this script name].py --help + +config = ( + DreamerV3Config() + .environment( + "FrozenLake-v1", + env_config={ + "desc": [ + "SF", + "HG", + ], + "is_slippery": False, + }, + ) + .training( + model_size="XS", + training_ratio=1024, + ) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/frozenlake_4x4_deterministic_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/frozenlake_4x4_deterministic_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0a9108e93d7e68c938d8b43d36b754e82b5f15 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/frozenlake_4x4_deterministic_dreamerv3.py @@ -0,0 +1,31 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config + +# Run with: +# python [this script name].py + +# To see all available options: +# python [this script name].py --help + +config = ( + DreamerV3Config() + .environment( + "FrozenLake-v1", + env_config={ + "map_name": "4x4", + "is_slippery": False, + }, + ) + .training( + model_size="nano", + training_ratio=1024, + ) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/gymnasium_robotics_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/gymnasium_robotics_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..87986793b2cbb863135bbb403486ef364ac07935 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/gymnasium_robotics_dreamerv3.py @@ -0,0 +1,69 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" + +# Run with: +# python [this script name].py + +# To see all available options: +# python [this script name].py --help + +try: + import gymnasium_robotics # noqa +except (ImportError, ModuleNotFoundError): + print("You have to `pip install gymnasium_robotics` in order to run this example!") + +import gymnasium as gym + +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config +from ray import tune + + +# Number of GPUs to run on. +num_gpus = 4 + +# Register the gymnasium robotics env (including necessary wrappers and options) via the +# `tune.register_env()` API. +# Create the specific gymnasium robotics env. +# e.g. AdroitHandHammerSparse-v1 or FrankaKitchen-v1. +# return gym.make("FrankaKitchen-v1", tasks_to_complete=["microwave", "kettle"]) +tune.register_env("flappy-bird", lambda ctx: gym.make("AdroitHandHammer-v1")) + +# Define the DreamerV3 config object to use. +config = DreamerV3Config() +w = config.world_model_lr +c = config.critic_lr +# Further specify the details of our config object. +( + config.resources( + num_cpus_for_main_process=8 * (num_gpus or 1), + ) + .learners( + num_learners=0 if num_gpus == 1 else num_gpus, + num_gpus_per_learner=1 if num_gpus else 0, + ) + # If we use >1 GPU and increase the batch size accordingly, we should also + # increase the number of envs per worker. + .env_runners(num_envs_per_env_runner=8 * (num_gpus or 1), remote_worker_envs=True) + .reporting( + metrics_num_episodes_for_smoothing=(num_gpus or 1), + report_images_and_videos=False, + report_dream_data=False, + report_individual_batch_item_stats=False, + ) + # See Appendix A. + .training( + model_size="XL", + training_ratio=64, + batch_size_B=16 * (num_gpus or 1), + world_model_lr=[[0, 0.4 * w], [50000, 0.4 * w], [100000, 3 * w]], + critic_lr=[[0, 0.4 * c], [50000, 0.4 * c], [100000, 3 * c]], + actor_lr=[[0, 0.4 * c], [50000, 0.4 * c], [100000, 3 * c]], + ) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/highway_env_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/highway_env_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..beeb0d4370a15a28556a4b86bbdd907ec4e025b8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/highway_env_dreamerv3.py @@ -0,0 +1,74 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" + +# Run with: +# python [this script name].py + +# To see all available options: +# python [this script name].py --help + +try: + import highway_env # noqa +except (ImportError, ModuleNotFoundError): + print("You have to `pip install highway_env` in order to run this example!") + +import gymnasium as gym + +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config +from ray import tune + + +# Number of GPUs to run on. +num_gpus = 4 + +# Register the highway env (including necessary wrappers and options) via the +# `tune.register_env()` API. +# Create the specific env. +# e.g. roundabout-v0 or racetrack-v0 +tune.register_env("flappy-bird", lambda ctx: gym.make("intersection-v0", policy_freq=5)) + +# Define the DreamerV3 config object to use. +config = DreamerV3Config() +w = config.world_model_lr +c = config.critic_lr + +( + config.resources( + num_cpus_for_main_process=1, + ) + .learners( + num_learners=0 if num_gpus == 1 else num_gpus, + num_gpus_per_learner=1 if num_gpus else 0, + ) + .env_runners( + # If we use >1 GPU and increase the batch size accordingly, we should also + # increase the number of envs per worker. + num_envs_per_env_runner=8 * (num_gpus or 1), + remote_worker_envs=True, + ) + .reporting( + metrics_num_episodes_for_smoothing=(num_gpus or 1), + report_images_and_videos=False, + report_dream_data=False, + report_individual_batch_item_stats=False, + ) + # See Appendix A. + .training( + model_size="M", + training_ratio=64, + batch_size_B=16 * (num_gpus or 1), + # Use a well established 4-GPU lr scheduling recipe: + # ~ 1000 training updates with 0.4x[default rates], then over a few hundred + # steps, increase to 4x[default rates]. + world_model_lr=[[0, 0.4 * w], [8000, 0.4 * w], [10000, 3 * w]], + critic_lr=[[0, 0.4 * c], [8000, 0.4 * c], [10000, 3 * c]], + actor_lr=[[0, 0.4 * c], [8000, 0.4 * c], [10000, 3 * c]], + ) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/pendulum_dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/pendulum_dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..5caf05cf99905b35dcd4ad3340057a10867e0c3e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/dreamerv3/pendulum_dreamerv3.py @@ -0,0 +1,63 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config +from ray.rllib.utils.test_utils import add_rllib_example_script_args + +parser = add_rllib_example_script_args( + default_iters=10000, + default_reward=-200.0, + default_timesteps=100000, +) +# Use `parser` to add your own custom command line options to this script +# and (if needed) use their values to set up `config` below. +args = parser.parse_args() +# If we use >1 GPU and increase the batch size accordingly, we should also +# increase the number of envs per worker. +if args.num_envs_per_env_runner is None: + args.num_envs_per_env_runner = args.num_learners or 1 + +# Run with: +# python [this script name].py + +# To see all available options: +# python [this script name].py --help + +default_config = DreamerV3Config() +lr_multiplier = args.num_learners or 1 + + +config = ( + DreamerV3Config() + .environment("Pendulum-v1") + .env_runners( + remote_worker_envs=(args.num_learners and args.num_learners > 1), + ) + .reporting( + metrics_num_episodes_for_smoothing=(args.num_learners or 1), + report_images_and_videos=False, + report_dream_data=False, + report_individual_batch_item_stats=False, + ) + # See Appendix A. + .training( + model_size="S", + training_ratio=1024, + batch_size_B=16 * (args.num_learners or 1), + world_model_lr=default_config.world_model_lr * lr_multiplier, + actor_lr=default_config.actor_lr * lr_multiplier, + critic_lr=default_config.critic_lr * lr_multiplier, + ) +) + + +if __name__ == "__main__": + from ray.rllib.utils.test_utils import run_rllib_example_script_experiment + + run_rllib_example_script_experiment(config, args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a883872e20a8cedb1c521e38e767468e259c0236 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/actor_manager.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/actor_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eae6e5a97d7c58807b9ffab0ac479a119cda2aa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/actor_manager.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/actors.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/actors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57e4c9388b136d429b014c82b55c3716b25e786e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/actors.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/annotations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/annotations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b18d78cdeaa4baa54c9374ffc06025b29be6d9ee Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/annotations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9637060bca48e99873378c5f8946597d5eb85aa6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/compression.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/compression.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bb9cc06945e70e21869ecd0c64a45d202e7cd9d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/compression.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef44b74ee8fa50658a49eeb585e81caf08fdb7d4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d75030b4652601e5bd5bda00a7ed935e33312f1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/error.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/filter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e1905d62564737c738b32750face5d7e50f8acf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/filter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/filter_manager.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/filter_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49b091982a90341ce6194f35e1c206f7915665ee Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/filter_manager.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/framework.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/framework.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..486f4f9d835f076948573597f8d4380c03be883d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/framework.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..006c9261fc6d26a7469926730805498b7a4cdf0b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/images.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/images.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19c1de2b2cf8a990b6d72f9d74b6d66a7c9d25ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/images.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a53e6d54b70839cdbf55902fe26080b95f01b6f2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/memory.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83d4c0b81165208b45a804b6e97f6cd5dcc7bff1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/memory.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/minibatch_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/minibatch_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac5fe22ac3fd45495d54e96287fc337776ff9bb2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/minibatch_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/numpy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/numpy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed269b6ad3f0a7a675598bd9e8eea0b4e1ea4540 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/numpy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d711fee4dc75853acfa3ce6cd27197e17d1645c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5ddcf73587893a6afce3a0b9c6f79f02bd74fee Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/sgd.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/sgd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c8533ad1d8e820ab7b464a738959bcfdac97eeb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/sgd.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c269a30e29d6f04d5c1206d45394f95742c87d96 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/test_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/test_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca2899879d2852d2a0d5f99aa4f063832468cdad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/test_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e928920a16e552aa513b4b86c3f4f0b7abd45591 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tf_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tf_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeab0dc45788b9fe437a3d798b40e252453a0888 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/tf_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/threading.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/threading.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b45444662893206dcbaa6fe0596fe47b47d490ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/threading.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6240de16700b9eef05d75350985c35d35747018 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/typing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c7b576107e2ece5257bd3117e666fff8e2e1da1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__pycache__/typing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..140323eef76fdb9bedbe67d5c2dd05f0a26b5750 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__init__.py @@ -0,0 +1,10 @@ +from ray.rllib.utils.debug.deterministic import update_global_seed_if_necessary +from ray.rllib.utils.debug.memory import check_memory_leaks +from ray.rllib.utils.debug.summary import summarize + + +__all__ = [ + "check_memory_leaks", + "summarize", + "update_global_seed_if_necessary", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be5a2a656ba7067d4991ff89fb84f89998df8fbc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/deterministic.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/deterministic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b30d2a0825d813e9d8f651bb8898a4df33543c4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/deterministic.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/memory.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf7dbb709583357b738d1bcffed9a50ba1e2f013 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/memory.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/summary.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/summary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..578b44378608625fe8d1a56c71bfb98b25ee9fbd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/__pycache__/summary.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/deterministic.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/deterministic.py new file mode 100644 index 0000000000000000000000000000000000000000..c9506551cac9eb3fb7f04cf8192de3720d6ebe6d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/deterministic.py @@ -0,0 +1,41 @@ +import numpy as np +import random +from typing import Optional + +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.torch_utils import set_torch_seed + + +@DeveloperAPI +def update_global_seed_if_necessary( + framework: Optional[str] = None, seed: Optional[int] = None +) -> None: + """Seed global modules such as random, numpy, torch, or tf. + + This is useful for debugging and testing. + + Args: + framework: The framework specifier (may be None). + seed: An optional int seed. If None, will not do + anything. + """ + if seed is None: + return + + # Python random module. + random.seed(seed) + # Numpy. + np.random.seed(seed) + + # Torch. + if framework == "torch": + set_torch_seed(seed=seed) + elif framework == "tf2": + tf1, tf, tfv = try_import_tf() + # Tf2.x. + if tfv == 2: + tf.random.set_seed(seed) + # Tf1.x. + else: + tf1.set_random_seed(seed) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/memory.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..f09de72b71dd8a38fb35d4b9e7a67a4ec24540d4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/memory.py @@ -0,0 +1,211 @@ +from collections import defaultdict +import numpy as np +import tree # pip install dm_tree +from typing import DefaultDict, List, Optional, Set + +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID, SampleBatch +from ray.util.debug import _test_some_code_for_memory_leaks, Suspect + + +@DeveloperAPI +def check_memory_leaks( + algorithm, + to_check: Optional[Set[str]] = None, + repeats: Optional[int] = None, + max_num_trials: int = 3, +) -> DefaultDict[str, List[Suspect]]: + """Diagnoses the given Algorithm for possible memory leaks. + + Isolates single components inside the Algorithm's local worker, e.g. the env, + policy, etc.. and calls some of their methods repeatedly, while checking + the memory footprints and keeping track of which lines in the code add + un-GC'd items to memory. + + Args: + algorithm: The Algorithm instance to test. + to_check: Set of strings to indentify components to test. Allowed strings + are: "env", "policy", "model", "rollout_worker". By default, check all + of these. + repeats: Number of times the test code block should get executed (per trial). + If a trial fails, a new trial may get started with a larger number of + repeats: actual_repeats = `repeats` * (trial + 1) (1st trial == 0). + max_num_trials: The maximum number of trials to run each check for. + + Raises: + A defaultdict(list) with keys being the `to_check` strings and values being + lists of Suspect instances that were found. + """ + local_worker = algorithm.env_runner + + # Which components should we test? + to_check = to_check or {"env", "model", "policy", "rollout_worker"} + + results_per_category = defaultdict(list) + + # Test a single sub-env (first in the VectorEnv)? + if "env" in to_check: + assert local_worker.async_env is not None, ( + "ERROR: Cannot test 'env' since given Algorithm does not have one " + "in its local worker. Try setting `create_local_env_runner=True`." + ) + + # Isolate the first sub-env in the vectorized setup and test it. + env = local_worker.async_env.get_sub_environments()[0] + action_space = env.action_space + # Always use same action to avoid numpy random caused memory leaks. + action_sample = action_space.sample() + + def code(): + ts = 0 + env.reset() + while True: + # If masking is used, try something like this: + # np.random.choice( + # action_space.n, p=(obs["action_mask"] / sum(obs["action_mask"]))) + _, _, done, _, _ = env.step(action_sample) + ts += 1 + if done: + break + + test = _test_some_code_for_memory_leaks( + desc="Looking for leaks in env, running through episodes.", + init=None, + code=code, + # How many times to repeat the function call? + repeats=repeats or 200, + max_num_trials=max_num_trials, + ) + if test: + results_per_category["env"].extend(test) + + # Test the policy (single-agent case only so far). + if "policy" in to_check: + policy = local_worker.policy_map[DEFAULT_POLICY_ID] + + # Get a fixed obs (B=10). + obs = tree.map_structure( + lambda s: np.stack([s] * 10, axis=0), policy.observation_space.sample() + ) + + print("Looking for leaks in Policy") + + def code(): + policy.compute_actions_from_input_dict( + { + "obs": obs, + } + ) + + # Call `compute_actions_from_input_dict()` n times. + test = _test_some_code_for_memory_leaks( + desc="Calling `compute_actions_from_input_dict()`.", + init=None, + code=code, + # How many times to repeat the function call? + repeats=repeats or 400, + # How many times to re-try if we find a suspicious memory + # allocation? + max_num_trials=max_num_trials, + ) + if test: + results_per_category["policy"].extend(test) + + # Testing this only makes sense if the learner API is disabled. + if not policy.config.get("enable_rl_module_and_learner", False): + # Call `learn_on_batch()` n times. + dummy_batch = policy._get_dummy_batch_from_view_requirements(batch_size=16) + + test = _test_some_code_for_memory_leaks( + desc="Calling `learn_on_batch()`.", + init=None, + code=lambda: policy.learn_on_batch(dummy_batch), + # How many times to repeat the function call? + repeats=repeats or 100, + max_num_trials=max_num_trials, + ) + if test: + results_per_category["policy"].extend(test) + + # Test only the model. + if "model" in to_check: + policy = local_worker.policy_map[DEFAULT_POLICY_ID] + + # Get a fixed obs. + obs = tree.map_structure(lambda s: s[None], policy.observation_space.sample()) + + print("Looking for leaks in Model") + + # Call `compute_actions_from_input_dict()` n times. + test = _test_some_code_for_memory_leaks( + desc="Calling `[model]()`.", + init=None, + code=lambda: policy.model({SampleBatch.OBS: obs}), + # How many times to repeat the function call? + repeats=repeats or 400, + # How many times to re-try if we find a suspicious memory + # allocation? + max_num_trials=max_num_trials, + ) + if test: + results_per_category["model"].extend(test) + + # Test the RolloutWorker. + if "rollout_worker" in to_check: + print("Looking for leaks in local RolloutWorker") + + def code(): + local_worker.sample() + local_worker.get_metrics() + + # Call `compute_actions_from_input_dict()` n times. + test = _test_some_code_for_memory_leaks( + desc="Calling `sample()` and `get_metrics()`.", + init=None, + code=code, + # How many times to repeat the function call? + repeats=repeats or 50, + # How many times to re-try if we find a suspicious memory + # allocation? + max_num_trials=max_num_trials, + ) + if test: + results_per_category["rollout_worker"].extend(test) + + if "learner" in to_check and algorithm.config.get( + "enable_rl_module_and_learner", False + ): + learner_group = algorithm.learner_group + assert learner_group._is_local, ( + "This test will miss leaks hidden in remote " + "workers. Please make sure that there is a " + "local learner inside the learner group for " + "this test." + ) + + dummy_batch = ( + algorithm.get_policy() + ._get_dummy_batch_from_view_requirements(batch_size=16) + .as_multi_agent() + ) + + print("Looking for leaks in Learner") + + def code(): + learner_group.update(dummy_batch) + + # Call `compute_actions_from_input_dict()` n times. + test = _test_some_code_for_memory_leaks( + desc="Calling `LearnerGroup.update()`.", + init=None, + code=code, + # How many times to repeat the function call? + repeats=repeats or 400, + # How many times to re-try if we find a suspicious memory + # allocation? + max_num_trials=max_num_trials, + ) + if test: + results_per_category["learner"].extend(test) + + return results_per_category diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/summary.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..57ff0f06e98225f34043b3743e08ab3013affc43 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/debug/summary.py @@ -0,0 +1,79 @@ +import numpy as np +import pprint +from typing import Any + +from ray.rllib.policy.sample_batch import SampleBatch, MultiAgentBatch +from ray.rllib.utils.annotations import DeveloperAPI + +_printer = pprint.PrettyPrinter(indent=2, width=60) + + +@DeveloperAPI +def summarize(obj: Any) -> Any: + """Return a pretty-formatted string for an object. + + This has special handling for pretty-formatting of commonly used data types + in RLlib, such as SampleBatch, numpy arrays, etc. + + Args: + obj: The object to format. + + Returns: + The summarized object. + """ + + return _printer.pformat(_summarize(obj)) + + +def _summarize(obj): + if isinstance(obj, dict): + return {k: _summarize(v) for k, v in obj.items()} + elif hasattr(obj, "_asdict"): + return { + "type": obj.__class__.__name__, + "data": _summarize(obj._asdict()), + } + elif isinstance(obj, list): + return [_summarize(x) for x in obj] + elif isinstance(obj, tuple): + return tuple(_summarize(x) for x in obj) + elif isinstance(obj, np.ndarray): + if obj.size == 0: + return _StringValue("np.ndarray({}, dtype={})".format(obj.shape, obj.dtype)) + elif obj.dtype == object or obj.dtype.type is np.str_: + return _StringValue( + "np.ndarray({}, dtype={}, head={})".format( + obj.shape, obj.dtype, _summarize(obj[0]) + ) + ) + else: + return _StringValue( + "np.ndarray({}, dtype={}, min={}, max={}, mean={})".format( + obj.shape, + obj.dtype, + round(float(np.min(obj)), 3), + round(float(np.max(obj)), 3), + round(float(np.mean(obj)), 3), + ) + ) + elif isinstance(obj, MultiAgentBatch): + return { + "type": "MultiAgentBatch", + "policy_batches": _summarize(obj.policy_batches), + "count": obj.count, + } + elif isinstance(obj, SampleBatch): + return { + "type": "SampleBatch", + "data": {k: _summarize(v) for k, v in obj.items()}, + } + else: + return obj + + +class _StringValue: + def __init__(self, value): + self.value = value + + def __repr__(self): + return self.value diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c04d70f83ce956e6b0ab3ab2e649d8cc6850780 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__init__.py @@ -0,0 +1,39 @@ +from ray.rllib.utils.exploration.curiosity import Curiosity +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.exploration.epsilon_greedy import EpsilonGreedy +from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise +from ray.rllib.utils.exploration.ornstein_uhlenbeck_noise import OrnsteinUhlenbeckNoise +from ray.rllib.utils.exploration.parameter_noise import ParameterNoise +from ray.rllib.utils.exploration.per_worker_epsilon_greedy import PerWorkerEpsilonGreedy +from ray.rllib.utils.exploration.per_worker_gaussian_noise import PerWorkerGaussianNoise +from ray.rllib.utils.exploration.per_worker_ornstein_uhlenbeck_noise import ( + PerWorkerOrnsteinUhlenbeckNoise, +) +from ray.rllib.utils.exploration.random import Random +from ray.rllib.utils.exploration.random_encoder import RE3 +from ray.rllib.utils.exploration.slate_epsilon_greedy import SlateEpsilonGreedy +from ray.rllib.utils.exploration.slate_soft_q import SlateSoftQ +from ray.rllib.utils.exploration.soft_q import SoftQ +from ray.rllib.utils.exploration.stochastic_sampling import StochasticSampling +from ray.rllib.utils.exploration.thompson_sampling import ThompsonSampling +from ray.rllib.utils.exploration.upper_confidence_bound import UpperConfidenceBound + +__all__ = [ + "Curiosity", + "Exploration", + "EpsilonGreedy", + "GaussianNoise", + "OrnsteinUhlenbeckNoise", + "ParameterNoise", + "PerWorkerEpsilonGreedy", + "PerWorkerGaussianNoise", + "PerWorkerOrnsteinUhlenbeckNoise", + "Random", + "RE3", + "SlateEpsilonGreedy", + "SlateSoftQ", + "SoftQ", + "StochasticSampling", + "ThompsonSampling", + "UpperConfidenceBound", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..378fc94acc120d2d5c9ee812d5352c60c707a467 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/curiosity.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/curiosity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3accb8be99535b9f4e008348dcebb22b40359cb4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/curiosity.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/epsilon_greedy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/epsilon_greedy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a053ae37015d502c0f70ccb0b85a0d98fd2ec121 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/epsilon_greedy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/exploration.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/exploration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc31c48c8075d2b02a157c8f5ba6e5501ba188d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/exploration.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/gaussian_noise.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/gaussian_noise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..275e3e57c37d0c9b39fa574e19f41857b958a15d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/gaussian_noise.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/ornstein_uhlenbeck_noise.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/ornstein_uhlenbeck_noise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ea30705aac1b2ada7190830a15c88e917b41ac6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/ornstein_uhlenbeck_noise.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/parameter_noise.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/parameter_noise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..165707dc67964f92dcffc8484bd4453eddc72d0d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/parameter_noise.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_epsilon_greedy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_epsilon_greedy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5019c338686a0871da5e94760adf888dfb4050f7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_epsilon_greedy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_gaussian_noise.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_gaussian_noise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b20de584478f3a13992c12a20c67df52448ee23d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_gaussian_noise.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_ornstein_uhlenbeck_noise.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_ornstein_uhlenbeck_noise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f3451b0fba200f69a38671ea7cf246d86238d6b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/per_worker_ornstein_uhlenbeck_noise.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/random.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/random.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b785cc2367b7b20dd5831159731efbb81d7fc53f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/random.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/random_encoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/random_encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6b372eded3e31bec1c8dd7b26d438fc6983788e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/random_encoder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/slate_epsilon_greedy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/slate_epsilon_greedy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97ec0e5f068063b4707c22512a0acae454589f7f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/slate_epsilon_greedy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/slate_soft_q.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/slate_soft_q.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e08220386a3e1b3179947c96fe2069971ed28c3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/slate_soft_q.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/soft_q.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/soft_q.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab412564d311fe1fa87248731867cb952bc20d9f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/soft_q.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/stochastic_sampling.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/stochastic_sampling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cb406e3a38282ea6035f39be5174192aff4f5b0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/stochastic_sampling.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/thompson_sampling.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/thompson_sampling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9e147177a75370e7ea04d9b62596bc710d1edf4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/thompson_sampling.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/upper_confidence_bound.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/upper_confidence_bound.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feb9286c4ea61ff0ccf00d87f9cb6404c920aff7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/__pycache__/upper_confidence_bound.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/curiosity.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..7980bd2927381e50bbab5f13e6b894fe9c93fb85 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/curiosity.py @@ -0,0 +1,444 @@ +from gymnasium.spaces import Discrete, MultiDiscrete, Space +import numpy as np +from typing import Optional, Tuple, Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import Categorical, MultiCategorical +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.torch_action_dist import ( + TorchCategorical, + TorchMultiCategorical, +) +from ray.rllib.models.utils import get_activation_fn +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils import NullContextManager +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.tf_utils import get_placeholder, one_hot as tf_one_hot +from ray.rllib.utils.torch_utils import one_hot +from ray.rllib.utils.typing import FromConfigSpec, ModelConfigDict, TensorType + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() +F = None +if nn is not None: + F = nn.functional + + +@OldAPIStack +class Curiosity(Exploration): + """Implementation of: + [1] Curiosity-driven Exploration by Self-supervised Prediction + Pathak, Agrawal, Efros, and Darrell - UC Berkeley - ICML 2017. + https://arxiv.org/pdf/1705.05363.pdf + + Learns a simplified model of the environment based on three networks: + 1) Embedding observations into latent space ("feature" network). + 2) Predicting the action, given two consecutive embedded observations + ("inverse" network). + 3) Predicting the next embedded obs, given an obs and action + ("forward" network). + + The less the agent is able to predict the actually observed next feature + vector, given obs and action (through the forwards network), the larger the + "intrinsic reward", which will be added to the extrinsic reward. + Therefore, if a state transition was unexpected, the agent becomes + "curious" and will further explore this transition leading to better + exploration in sparse rewards environments. + """ + + def __init__( + self, + action_space: Space, + *, + framework: str, + model: ModelV2, + feature_dim: int = 288, + feature_net_config: Optional[ModelConfigDict] = None, + inverse_net_hiddens: Tuple[int] = (256,), + inverse_net_activation: str = "relu", + forward_net_hiddens: Tuple[int] = (256,), + forward_net_activation: str = "relu", + beta: float = 0.2, + eta: float = 1.0, + lr: float = 1e-3, + sub_exploration: Optional[FromConfigSpec] = None, + **kwargs + ): + """Initializes a Curiosity object. + + Uses as defaults the hyperparameters described in [1]. + + Args: + feature_dim: The dimensionality of the feature (phi) + vectors. + feature_net_config: Optional model + configuration for the feature network, producing feature + vectors (phi) from observations. This can be used to configure + fcnet- or conv_net setups to properly process any observation + space. + inverse_net_hiddens: Tuple of the layer sizes of the + inverse (action predicting) NN head (on top of the feature + outputs for phi and phi'). + inverse_net_activation: Activation specifier for the inverse + net. + forward_net_hiddens: Tuple of the layer sizes of the + forward (phi' predicting) NN head. + forward_net_activation: Activation specifier for the forward + net. + beta: Weight for the forward loss (over the inverse loss, + which gets weight=1.0-beta) in the common loss term. + eta: Weight for intrinsic rewards before being added to + extrinsic ones. + lr: The learning rate for the curiosity-specific + optimizer, optimizing feature-, inverse-, and forward nets. + sub_exploration: The config dict for + the underlying Exploration to use (e.g. epsilon-greedy for + DQN). If None, uses the FromSpecDict provided in the Policy's + default config. + """ + if not isinstance(action_space, (Discrete, MultiDiscrete)): + raise ValueError( + "Only (Multi)Discrete action spaces supported for Curiosity so far!" + ) + + super().__init__(action_space, model=model, framework=framework, **kwargs) + + if self.policy_config["num_env_runners"] != 0: + raise ValueError( + "Curiosity exploration currently does not support parallelism." + " `num_workers` must be 0!" + ) + + self.feature_dim = feature_dim + if feature_net_config is None: + feature_net_config = self.policy_config["model"].copy() + self.feature_net_config = feature_net_config + self.inverse_net_hiddens = inverse_net_hiddens + self.inverse_net_activation = inverse_net_activation + self.forward_net_hiddens = forward_net_hiddens + self.forward_net_activation = forward_net_activation + + self.action_dim = ( + self.action_space.n + if isinstance(self.action_space, Discrete) + else np.sum(self.action_space.nvec) + ) + + self.beta = beta + self.eta = eta + self.lr = lr + # TODO: (sven) if sub_exploration is None, use Algorithm's default + # Exploration config. + if sub_exploration is None: + raise NotImplementedError + self.sub_exploration = sub_exploration + + # Creates modules/layers inside the actual ModelV2. + self._curiosity_feature_net = ModelCatalog.get_model_v2( + self.model.obs_space, + self.action_space, + self.feature_dim, + model_config=self.feature_net_config, + framework=self.framework, + name="feature_net", + ) + + self._curiosity_inverse_fcnet = self._create_fc_net( + [2 * self.feature_dim] + list(self.inverse_net_hiddens) + [self.action_dim], + self.inverse_net_activation, + name="inverse_net", + ) + + self._curiosity_forward_fcnet = self._create_fc_net( + [self.feature_dim + self.action_dim] + + list(self.forward_net_hiddens) + + [self.feature_dim], + self.forward_net_activation, + name="forward_net", + ) + + # This is only used to select the correct action + self.exploration_submodule = from_config( + cls=Exploration, + config=self.sub_exploration, + action_space=self.action_space, + framework=self.framework, + policy_config=self.policy_config, + model=self.model, + num_workers=self.num_workers, + worker_index=self.worker_index, + ) + + @override(Exploration) + def get_exploration_action( + self, + *, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True + ): + # Simply delegate to sub-Exploration module. + return self.exploration_submodule.get_exploration_action( + action_distribution=action_distribution, timestep=timestep, explore=explore + ) + + @override(Exploration) + def get_exploration_optimizer(self, optimizers): + # Create, but don't add Adam for curiosity NN updating to the policy. + # If we added and returned it here, it would be used in the policy's + # update loop, which we don't want (curiosity updating happens inside + # `postprocess_trajectory`). + if self.framework == "torch": + feature_params = list(self._curiosity_feature_net.parameters()) + inverse_params = list(self._curiosity_inverse_fcnet.parameters()) + forward_params = list(self._curiosity_forward_fcnet.parameters()) + + # Now that the Policy's own optimizer(s) have been created (from + # the Model parameters (IMPORTANT: w/o(!) the curiosity params), + # we can add our curiosity sub-modules to the Policy's Model. + self.model._curiosity_feature_net = self._curiosity_feature_net.to( + self.device + ) + self.model._curiosity_inverse_fcnet = self._curiosity_inverse_fcnet.to( + self.device + ) + self.model._curiosity_forward_fcnet = self._curiosity_forward_fcnet.to( + self.device + ) + self._optimizer = torch.optim.Adam( + forward_params + inverse_params + feature_params, lr=self.lr + ) + else: + self.model._curiosity_feature_net = self._curiosity_feature_net + self.model._curiosity_inverse_fcnet = self._curiosity_inverse_fcnet + self.model._curiosity_forward_fcnet = self._curiosity_forward_fcnet + # Feature net is a RLlib ModelV2, the other 2 are keras Models. + self._optimizer_var_list = ( + self._curiosity_feature_net.base_model.variables + + self._curiosity_inverse_fcnet.variables + + self._curiosity_forward_fcnet.variables + ) + self._optimizer = tf1.train.AdamOptimizer(learning_rate=self.lr) + # Create placeholders and initialize the loss. + if self.framework == "tf": + self._obs_ph = get_placeholder( + space=self.model.obs_space, name="_curiosity_obs" + ) + self._next_obs_ph = get_placeholder( + space=self.model.obs_space, name="_curiosity_next_obs" + ) + self._action_ph = get_placeholder( + space=self.model.action_space, name="_curiosity_action" + ) + ( + self._forward_l2_norm_sqared, + self._update_op, + ) = self._postprocess_helper_tf( + self._obs_ph, self._next_obs_ph, self._action_ph + ) + + return optimizers + + @override(Exploration) + def postprocess_trajectory(self, policy, sample_batch, tf_sess=None): + """Calculates phi values (obs, obs', and predicted obs') and ri. + + Also calculates forward and inverse losses and updates the curiosity + module on the provided batch using our optimizer. + """ + if self.framework != "torch": + self._postprocess_tf(policy, sample_batch, tf_sess) + else: + self._postprocess_torch(policy, sample_batch) + + def _postprocess_tf(self, policy, sample_batch, tf_sess): + # tf1 static-graph: Perform session call on our loss and update ops. + if self.framework == "tf": + forward_l2_norm_sqared, _ = tf_sess.run( + [self._forward_l2_norm_sqared, self._update_op], + feed_dict={ + self._obs_ph: sample_batch[SampleBatch.OBS], + self._next_obs_ph: sample_batch[SampleBatch.NEXT_OBS], + self._action_ph: sample_batch[SampleBatch.ACTIONS], + }, + ) + # tf-eager: Perform model calls, loss calculations, and optimizer + # stepping on the fly. + else: + forward_l2_norm_sqared, _ = self._postprocess_helper_tf( + sample_batch[SampleBatch.OBS], + sample_batch[SampleBatch.NEXT_OBS], + sample_batch[SampleBatch.ACTIONS], + ) + # Scale intrinsic reward by eta hyper-parameter. + sample_batch[SampleBatch.REWARDS] = ( + sample_batch[SampleBatch.REWARDS] + self.eta * forward_l2_norm_sqared + ) + + return sample_batch + + def _postprocess_helper_tf(self, obs, next_obs, actions): + with ( + tf.GradientTape() if self.framework != "tf" else NullContextManager() + ) as tape: + # Push both observations through feature net to get both phis. + phis, _ = self.model._curiosity_feature_net( + {SampleBatch.OBS: tf.concat([obs, next_obs], axis=0)} + ) + phi, next_phi = tf.split(phis, 2) + + # Predict next phi with forward model. + predicted_next_phi = self.model._curiosity_forward_fcnet( + tf.concat([phi, tf_one_hot(actions, self.action_space)], axis=-1) + ) + + # Forward loss term (predicted phi', given phi and action vs + # actually observed phi'). + forward_l2_norm_sqared = 0.5 * tf.reduce_sum( + tf.square(predicted_next_phi - next_phi), axis=-1 + ) + forward_loss = tf.reduce_mean(forward_l2_norm_sqared) + + # Inverse loss term (prediced action that led from phi to phi' vs + # actual action taken). + phi_cat_next_phi = tf.concat([phi, next_phi], axis=-1) + dist_inputs = self.model._curiosity_inverse_fcnet(phi_cat_next_phi) + action_dist = ( + Categorical(dist_inputs, self.model) + if isinstance(self.action_space, Discrete) + else MultiCategorical(dist_inputs, self.model, self.action_space.nvec) + ) + # Neg log(p); p=probability of observed action given the inverse-NN + # predicted action distribution. + inverse_loss = -action_dist.logp(tf.convert_to_tensor(actions)) + inverse_loss = tf.reduce_mean(inverse_loss) + + # Calculate the ICM loss. + loss = (1.0 - self.beta) * inverse_loss + self.beta * forward_loss + + # Step the optimizer. + if self.framework != "tf": + grads = tape.gradient(loss, self._optimizer_var_list) + grads_and_vars = [ + (g, v) for g, v in zip(grads, self._optimizer_var_list) if g is not None + ] + update_op = self._optimizer.apply_gradients(grads_and_vars) + else: + update_op = self._optimizer.minimize( + loss, var_list=self._optimizer_var_list + ) + + # Return the squared l2 norm and the optimizer update op. + return forward_l2_norm_sqared, update_op + + def _postprocess_torch(self, policy, sample_batch): + # Push both observations through feature net to get both phis. + phis, _ = self.model._curiosity_feature_net( + { + SampleBatch.OBS: torch.cat( + [ + torch.from_numpy(sample_batch[SampleBatch.OBS]).to( + policy.device + ), + torch.from_numpy(sample_batch[SampleBatch.NEXT_OBS]).to( + policy.device + ), + ] + ) + } + ) + phi, next_phi = torch.chunk(phis, 2) + actions_tensor = ( + torch.from_numpy(sample_batch[SampleBatch.ACTIONS]).long().to(policy.device) + ) + + # Predict next phi with forward model. + predicted_next_phi = self.model._curiosity_forward_fcnet( + torch.cat([phi, one_hot(actions_tensor, self.action_space).float()], dim=-1) + ) + + # Forward loss term (predicted phi', given phi and action vs actually + # observed phi'). + forward_l2_norm_sqared = 0.5 * torch.sum( + torch.pow(predicted_next_phi - next_phi, 2.0), dim=-1 + ) + forward_loss = torch.mean(forward_l2_norm_sqared) + + # Scale intrinsic reward by eta hyper-parameter. + sample_batch[SampleBatch.REWARDS] = ( + sample_batch[SampleBatch.REWARDS] + + self.eta * forward_l2_norm_sqared.detach().cpu().numpy() + ) + + # Inverse loss term (prediced action that led from phi to phi' vs + # actual action taken). + phi_cat_next_phi = torch.cat([phi, next_phi], dim=-1) + dist_inputs = self.model._curiosity_inverse_fcnet(phi_cat_next_phi) + action_dist = ( + TorchCategorical(dist_inputs, self.model) + if isinstance(self.action_space, Discrete) + else TorchMultiCategorical(dist_inputs, self.model, self.action_space.nvec) + ) + # Neg log(p); p=probability of observed action given the inverse-NN + # predicted action distribution. + inverse_loss = -action_dist.logp(actions_tensor) + inverse_loss = torch.mean(inverse_loss) + + # Calculate the ICM loss. + loss = (1.0 - self.beta) * inverse_loss + self.beta * forward_loss + # Perform an optimizer step. + self._optimizer.zero_grad() + loss.backward() + self._optimizer.step() + + # Return the postprocessed sample batch (with the corrected rewards). + return sample_batch + + def _create_fc_net(self, layer_dims, activation, name=None): + """Given a list of layer dimensions (incl. input-dim), creates FC-net. + + Args: + layer_dims (Tuple[int]): Tuple of layer dims, including the input + dimension. + activation: An activation specifier string (e.g. "relu"). + + Examples: + If layer_dims is [4,8,6] we'll have a two layer net: 4->8 (8 nodes) + and 8->6 (6 nodes), where the second layer (6 nodes) does not have + an activation anymore. 4 is the input dimension. + """ + layers = ( + [tf.keras.layers.Input(shape=(layer_dims[0],), name="{}_in".format(name))] + if self.framework != "torch" + else [] + ) + + for i in range(len(layer_dims) - 1): + act = activation if i < len(layer_dims) - 2 else None + if self.framework == "torch": + layers.append( + SlimFC( + in_size=layer_dims[i], + out_size=layer_dims[i + 1], + initializer=torch.nn.init.xavier_uniform_, + activation_fn=act, + ) + ) + else: + layers.append( + tf.keras.layers.Dense( + units=layer_dims[i + 1], + activation=get_activation_fn(act), + name="{}_{}".format(name, i), + ) + ) + + if self.framework == "torch": + return nn.Sequential(*layers) + else: + return tf.keras.Sequential(layers) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/epsilon_greedy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/epsilon_greedy.py new file mode 100644 index 0000000000000000000000000000000000000000..40a307bfbb324cc098bba8649de6b1df096c9ad7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/epsilon_greedy.py @@ -0,0 +1,246 @@ +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree +import random +from typing import Union, Optional + +from ray.rllib.models.torch.torch_action_dist import TorchMultiActionDistribution +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import override, OldAPIStack +from ray.rllib.utils.exploration.exploration import Exploration, TensorType +from ray.rllib.utils.framework import try_import_tf, try_import_torch, get_variable +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.schedules import Schedule, PiecewiseSchedule +from ray.rllib.utils.torch_utils import FLOAT_MIN + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class EpsilonGreedy(Exploration): + """Epsilon-greedy Exploration class that produces exploration actions. + + When given a Model's output and a current epsilon value (based on some + Schedule), it produces a random action (if rand(1) < eps) or + uses the model-computed one (if rand(1) >= eps). + """ + + def __init__( + self, + action_space: gym.spaces.Space, + *, + framework: str, + initial_epsilon: float = 1.0, + final_epsilon: float = 0.05, + warmup_timesteps: int = 0, + epsilon_timesteps: int = int(1e5), + epsilon_schedule: Optional[Schedule] = None, + **kwargs, + ): + """Create an EpsilonGreedy exploration class. + + Args: + action_space: The action space the exploration should occur in. + framework: The framework specifier. + initial_epsilon: The initial epsilon value to use. + final_epsilon: The final epsilon value to use. + warmup_timesteps: The timesteps over which to not change epsilon in the + beginning. + epsilon_timesteps: The timesteps (additional to `warmup_timesteps`) + after which epsilon should always be `final_epsilon`. + E.g.: warmup_timesteps=20k epsilon_timesteps=50k -> After 70k timesteps, + epsilon will reach its final value. + epsilon_schedule: An optional Schedule object + to use (instead of constructing one from the given parameters). + """ + assert framework is not None + super().__init__(action_space=action_space, framework=framework, **kwargs) + + self.epsilon_schedule = from_config( + Schedule, epsilon_schedule, framework=framework + ) or PiecewiseSchedule( + endpoints=[ + (0, initial_epsilon), + (warmup_timesteps, initial_epsilon), + (warmup_timesteps + epsilon_timesteps, final_epsilon), + ], + outside_value=final_epsilon, + framework=self.framework, + ) + + # The current timestep value (tf-var or python int). + self.last_timestep = get_variable( + np.array(0, np.int64), + framework=framework, + tf_name="timestep", + dtype=np.int64, + ) + + # Build the tf-info-op. + if self.framework == "tf": + self._tf_state_op = self.get_state() + + @override(Exploration) + def get_exploration_action( + self, + *, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: Optional[Union[bool, TensorType]] = True, + ): + + if self.framework in ["tf2", "tf"]: + return self._get_tf_exploration_action_op( + action_distribution, explore, timestep + ) + else: + return self._get_torch_exploration_action( + action_distribution, explore, timestep + ) + + def _get_tf_exploration_action_op( + self, + action_distribution: ActionDistribution, + explore: Union[bool, TensorType], + timestep: Union[int, TensorType], + ) -> "tf.Tensor": + """TF method to produce the tf op for an epsilon exploration action. + + Args: + action_distribution: The instantiated ActionDistribution object + to work with when creating exploration actions. + + Returns: + The tf exploration-action op. + """ + # TODO: Support MultiActionDistr for tf. + q_values = action_distribution.inputs + epsilon = self.epsilon_schedule( + timestep if timestep is not None else self.last_timestep + ) + + # Get the exploit action as the one with the highest logit value. + exploit_action = tf.argmax(q_values, axis=1) + + batch_size = tf.shape(q_values)[0] + # Mask out actions with q-value=-inf so that we don't even consider + # them for exploration. + random_valid_action_logits = tf.where( + tf.equal(q_values, tf.float32.min), + tf.ones_like(q_values) * tf.float32.min, + tf.ones_like(q_values), + ) + random_actions = tf.squeeze( + tf.random.categorical(random_valid_action_logits, 1), axis=1 + ) + + chose_random = ( + tf.random.uniform( + tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32 + ) + < epsilon + ) + + action = tf.cond( + pred=tf.constant(explore, dtype=tf.bool) + if isinstance(explore, bool) + else explore, + true_fn=(lambda: tf.where(chose_random, random_actions, exploit_action)), + false_fn=lambda: exploit_action, + ) + + if self.framework == "tf2" and not self.policy_config["eager_tracing"]: + self.last_timestep = timestep + return action, tf.zeros_like(action, dtype=tf.float32) + else: + assign_op = tf1.assign(self.last_timestep, tf.cast(timestep, tf.int64)) + with tf1.control_dependencies([assign_op]): + return action, tf.zeros_like(action, dtype=tf.float32) + + def _get_torch_exploration_action( + self, + action_distribution: ActionDistribution, + explore: bool, + timestep: Union[int, TensorType], + ) -> "torch.Tensor": + """Torch method to produce an epsilon exploration action. + + Args: + action_distribution: The instantiated + ActionDistribution object to work with when creating + exploration actions. + + Returns: + The exploration-action. + """ + q_values = action_distribution.inputs + self.last_timestep = timestep + exploit_action = action_distribution.deterministic_sample() + batch_size = q_values.size()[0] + action_logp = torch.zeros(batch_size, dtype=torch.float) + + # Explore. + if explore: + # Get the current epsilon. + epsilon = self.epsilon_schedule(self.last_timestep) + if isinstance(action_distribution, TorchMultiActionDistribution): + exploit_action = tree.flatten(exploit_action) + for i in range(batch_size): + if random.random() < epsilon: + # TODO: (bcahlit) Mask out actions + random_action = tree.flatten(self.action_space.sample()) + for j in range(len(exploit_action)): + exploit_action[j][i] = torch.tensor(random_action[j]) + exploit_action = tree.unflatten_as( + action_distribution.action_space_struct, exploit_action + ) + + return exploit_action, action_logp + + else: + # Mask out actions, whose Q-values are -inf, so that we don't + # even consider them for exploration. + random_valid_action_logits = torch.where( + q_values <= FLOAT_MIN, + torch.ones_like(q_values) * 0.0, + torch.ones_like(q_values), + ) + # A random action. + random_actions = torch.squeeze( + torch.multinomial(random_valid_action_logits, 1), axis=1 + ) + + # Pick either random or greedy. + action = torch.where( + torch.empty((batch_size,)).uniform_().to(self.device) < epsilon, + random_actions, + exploit_action, + ) + + return action, action_logp + # Return the deterministic "sample" (argmax) over the logits. + else: + return exploit_action, action_logp + + @override(Exploration) + def get_state(self, sess: Optional["tf.Session"] = None): + if sess: + return sess.run(self._tf_state_op) + eps = self.epsilon_schedule(self.last_timestep) + return { + "cur_epsilon": convert_to_numpy(eps) if self.framework != "tf" else eps, + "last_timestep": convert_to_numpy(self.last_timestep) + if self.framework != "tf" + else self.last_timestep, + } + + @override(Exploration) + def set_state(self, state: dict, sess: Optional["tf.Session"] = None) -> None: + if self.framework == "tf": + self.last_timestep.load(state["last_timestep"], session=sess) + elif isinstance(self.last_timestep, int): + self.last_timestep = state["last_timestep"] + else: + self.last_timestep.assign(state["last_timestep"]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/exploration.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/exploration.py new file mode 100644 index 0000000000000000000000000000000000000000..9cbb494ef30f63802ef8654f7275021bce3a11f3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/exploration.py @@ -0,0 +1,209 @@ +from gymnasium.spaces import Space +from typing import Dict, List, Optional, Union, TYPE_CHECKING + +from ray.rllib.env.base_env import BaseEnv +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_torch, TensorType +from ray.rllib.utils.typing import LocalOptimizer, AlgorithmConfigDict + +if TYPE_CHECKING: + from ray.rllib.policy.policy import Policy + from ray.rllib.utils import try_import_tf + + _, tf, _ = try_import_tf() + +_, nn = try_import_torch() + + +@OldAPIStack +class Exploration: + """Implements an exploration strategy for Policies. + + An Exploration takes model outputs, a distribution, and a timestep from + the agent and computes an action to apply to the environment using an + implemented exploration schema. + """ + + def __init__( + self, + action_space: Space, + *, + framework: str, + policy_config: AlgorithmConfigDict, + model: ModelV2, + num_workers: int, + worker_index: int + ): + """ + Args: + action_space: The action space in which to explore. + framework: One of "tf" or "torch". + policy_config: The Policy's config dict. + model: The Policy's model. + num_workers: The overall number of workers used. + worker_index: The index of the worker using this class. + """ + self.action_space = action_space + self.policy_config = policy_config + self.model = model + self.num_workers = num_workers + self.worker_index = worker_index + self.framework = framework + # The device on which the Model has been placed. + # This Exploration will be on the same device. + self.device = None + if isinstance(self.model, nn.Module): + params = list(self.model.parameters()) + if params: + self.device = params[0].device + + def before_compute_actions( + self, + *, + timestep: Optional[Union[TensorType, int]] = None, + explore: Optional[Union[TensorType, bool]] = None, + tf_sess: Optional["tf.Session"] = None, + **kwargs + ): + """Hook for preparations before policy.compute_actions() is called. + + Args: + timestep: An optional timestep tensor. + explore: An optional explore boolean flag. + tf_sess: The tf-session object to use. + **kwargs: Forward compatibility kwargs. + """ + pass + + # fmt: off + # __sphinx_doc_begin_get_exploration_action__ + + def get_exploration_action(self, + *, + action_distribution: ActionDistribution, + timestep: Union[TensorType, int], + explore: bool = True): + """Returns a (possibly) exploratory action and its log-likelihood. + + Given the Model's logits outputs and action distribution, returns an + exploratory action. + + Args: + action_distribution: The instantiated + ActionDistribution object to work with when creating + exploration actions. + timestep: The current sampling time step. It can be a tensor + for TF graph mode, otherwise an integer. + explore: True: "Normal" exploration behavior. + False: Suppress all exploratory behavior and return + a deterministic action. + + Returns: + A tuple consisting of 1) the chosen exploration action or a + tf-op to fetch the exploration action from the graph and + 2) the log-likelihood of the exploration action. + """ + pass + + # __sphinx_doc_end_get_exploration_action__ + # fmt: on + + def on_episode_start( + self, + policy: "Policy", + *, + environment: BaseEnv = None, + episode: int = None, + tf_sess: Optional["tf.Session"] = None + ): + """Handles necessary exploration logic at the beginning of an episode. + + Args: + policy: The Policy object that holds this Exploration. + environment: The environment object we are acting in. + episode: The number of the episode that is starting. + tf_sess: In case of tf, the session object. + """ + pass + + def on_episode_end( + self, + policy: "Policy", + *, + environment: BaseEnv = None, + episode: int = None, + tf_sess: Optional["tf.Session"] = None + ): + """Handles necessary exploration logic at the end of an episode. + + Args: + policy: The Policy object that holds this Exploration. + environment: The environment object we are acting in. + episode: The number of the episode that is starting. + tf_sess: In case of tf, the session object. + """ + pass + + def postprocess_trajectory( + self, + policy: "Policy", + sample_batch: SampleBatch, + tf_sess: Optional["tf.Session"] = None, + ): + """Handles post-processing of done episode trajectories. + + Changes the given batch in place. This callback is invoked by the + sampler after policy.postprocess_trajectory() is called. + + Args: + policy: The owning policy object. + sample_batch: The SampleBatch object to post-process. + tf_sess: An optional tf.Session object. + """ + return sample_batch + + def get_exploration_optimizer( + self, optimizers: List[LocalOptimizer] + ) -> List[LocalOptimizer]: + """May add optimizer(s) to the Policy's own `optimizers`. + + The number of optimizers (Policy's plus Exploration's optimizers) must + match the number of loss terms produced by the Policy's loss function + and the Exploration component's loss terms. + + Args: + optimizers: The list of the Policy's local optimizers. + + Returns: + The updated list of local optimizers to use on the different + loss terms. + """ + return optimizers + + def get_state(self, sess: Optional["tf.Session"] = None) -> Dict[str, TensorType]: + """Returns the current exploration state. + + Args: + sess: An optional tf Session object to use. + + Returns: + The Exploration object's current state. + """ + return {} + + def set_state(self, state: object, sess: Optional["tf.Session"] = None) -> None: + """Sets the Exploration object's state to the given values. + + Note that some exploration components are stateless, even though they + decay some values over time (e.g. EpsilonGreedy). However the decay is + only dependent on the current global timestep of the policy and we + therefore don't need to keep track of it. + + Args: + state: The state to set this Exploration to. + sess: An optional tf Session object to use. + """ + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/gaussian_noise.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/gaussian_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..385ac377d84e7955a076c2bbcbd1b595fb83071d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/gaussian_noise.py @@ -0,0 +1,247 @@ +from gymnasium.spaces import Space +import numpy as np +from typing import Union, Optional + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.exploration.random import Random +from ray.rllib.utils.framework import ( + try_import_tf, + try_import_torch, + get_variable, + TensorType, +) +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.schedules import Schedule +from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule +from ray.rllib.utils.tf_utils import zero_logps_from_actions + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class GaussianNoise(Exploration): + """An exploration that adds white noise to continuous actions. + + If explore=True, returns actions plus scale (annealed over time) x + Gaussian noise. Also, some completely random period is possible at the + beginning. + + If explore=False, returns the deterministic action. + """ + + def __init__( + self, + action_space: Space, + *, + framework: str, + model: ModelV2, + random_timesteps: int = 1000, + stddev: float = 0.1, + initial_scale: float = 1.0, + final_scale: float = 0.02, + scale_timesteps: int = 10000, + scale_schedule: Optional[Schedule] = None, + **kwargs + ): + """Initializes a GaussianNoise instance. + + Args: + random_timesteps: The number of timesteps for which to act + completely randomly. Only after this number of timesteps, the + `self.scale` annealing process will start (see below). + stddev: The stddev (sigma) to use for the + Gaussian noise to be added to the actions. + initial_scale: The initial scaling weight to multiply + the noise with. + final_scale: The final scaling weight to multiply + the noise with. + scale_timesteps: The timesteps over which to linearly anneal + the scaling factor (after(!) having used random actions for + `random_timesteps` steps). + scale_schedule: An optional Schedule object + to use (instead of constructing one from the given parameters). + """ + assert framework is not None + super().__init__(action_space, model=model, framework=framework, **kwargs) + + # Create the Random exploration module (used for the first n + # timesteps). + self.random_timesteps = random_timesteps + self.random_exploration = Random( + action_space, model=self.model, framework=self.framework, **kwargs + ) + + self.stddev = stddev + # The `scale` annealing schedule. + self.scale_schedule = scale_schedule or PiecewiseSchedule( + endpoints=[ + (random_timesteps, initial_scale), + (random_timesteps + scale_timesteps, final_scale), + ], + outside_value=final_scale, + framework=self.framework, + ) + + # The current timestep value (tf-var or python int). + self.last_timestep = get_variable( + np.array(0, np.int64), + framework=self.framework, + tf_name="timestep", + dtype=np.int64, + ) + + # Build the tf-info-op. + if self.framework == "tf": + self._tf_state_op = self.get_state() + + @override(Exploration) + def get_exploration_action( + self, + *, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True + ): + # Adds IID Gaussian noise for exploration, TD3-style. + if self.framework == "torch": + return self._get_torch_exploration_action( + action_distribution, explore, timestep + ) + else: + return self._get_tf_exploration_action_op( + action_distribution, explore, timestep + ) + + def _get_tf_exploration_action_op( + self, + action_dist: ActionDistribution, + explore: bool, + timestep: Union[int, TensorType], + ): + ts = timestep if timestep is not None else self.last_timestep + + # The deterministic actions (if explore=False). + deterministic_actions = action_dist.deterministic_sample() + + # Take a Gaussian sample with our stddev (mean=0.0) and scale it. + gaussian_sample = self.scale_schedule(ts) * tf.random.normal( + tf.shape(deterministic_actions), stddev=self.stddev + ) + + # Stochastic actions could either be: random OR action + noise. + random_actions, _ = self.random_exploration.get_tf_exploration_action_op( + action_dist, explore + ) + stochastic_actions = tf.cond( + pred=tf.convert_to_tensor(ts < self.random_timesteps), + true_fn=lambda: random_actions, + false_fn=lambda: tf.clip_by_value( + deterministic_actions + gaussian_sample, + self.action_space.low * tf.ones_like(deterministic_actions), + self.action_space.high * tf.ones_like(deterministic_actions), + ), + ) + + # Chose by `explore` (main exploration switch). + action = tf.cond( + pred=tf.constant(explore, dtype=tf.bool) + if isinstance(explore, bool) + else explore, + true_fn=lambda: stochastic_actions, + false_fn=lambda: deterministic_actions, + ) + # Logp=always zero. + logp = zero_logps_from_actions(deterministic_actions) + + # Increment `last_timestep` by 1 (or set to `timestep`). + if self.framework == "tf2": + if timestep is None: + self.last_timestep.assign_add(1) + else: + self.last_timestep.assign(tf.cast(timestep, tf.int64)) + return action, logp + else: + assign_op = ( + tf1.assign_add(self.last_timestep, 1) + if timestep is None + else tf1.assign(self.last_timestep, timestep) + ) + with tf1.control_dependencies([assign_op]): + return action, logp + + def _get_torch_exploration_action( + self, + action_dist: ActionDistribution, + explore: bool, + timestep: Union[int, TensorType], + ): + # Set last timestep or (if not given) increase by one. + self.last_timestep = ( + timestep if timestep is not None else self.last_timestep + 1 + ) + + # Apply exploration. + if explore: + # Random exploration phase. + if self.last_timestep < self.random_timesteps: + action, _ = self.random_exploration.get_torch_exploration_action( + action_dist, explore=True + ) + # Take a Gaussian sample with our stddev (mean=0.0) and scale it. + else: + det_actions = action_dist.deterministic_sample() + scale = self.scale_schedule(self.last_timestep) + gaussian_sample = scale * torch.normal( + mean=torch.zeros(det_actions.size()), std=self.stddev + ).to(self.device) + action = torch.min( + torch.max( + det_actions + gaussian_sample, + torch.tensor( + self.action_space.low, + dtype=torch.float32, + device=self.device, + ), + ), + torch.tensor( + self.action_space.high, dtype=torch.float32, device=self.device + ), + ) + # No exploration -> Return deterministic actions. + else: + action = action_dist.deterministic_sample() + + # Logp=always zero. + logp = torch.zeros((action.size()[0],), dtype=torch.float32, device=self.device) + + return action, logp + + @override(Exploration) + def get_state(self, sess: Optional["tf.Session"] = None): + """Returns the current scale value. + + Returns: + Union[float,tf.Tensor[float]]: The current scale value. + """ + if sess: + return sess.run(self._tf_state_op) + scale = self.scale_schedule(self.last_timestep) + return { + "cur_scale": convert_to_numpy(scale) if self.framework != "tf" else scale, + "last_timestep": convert_to_numpy(self.last_timestep) + if self.framework != "tf" + else self.last_timestep, + } + + @override(Exploration) + def set_state(self, state: dict, sess: Optional["tf.Session"] = None) -> None: + if self.framework == "tf": + self.last_timestep.load(state["last_timestep"], session=sess) + elif isinstance(self.last_timestep, int): + self.last_timestep = state["last_timestep"] + else: + self.last_timestep.assign(state["last_timestep"]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/ornstein_uhlenbeck_noise.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/ornstein_uhlenbeck_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..4bf1bce7108d604716f442c739de1771624515b2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/ornstein_uhlenbeck_noise.py @@ -0,0 +1,273 @@ +import numpy as np +from typing import Optional, Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise +from ray.rllib.utils.framework import ( + try_import_tf, + try_import_torch, + get_variable, + TensorType, +) +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.schedules import Schedule +from ray.rllib.utils.tf_utils import zero_logps_from_actions + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class OrnsteinUhlenbeckNoise(GaussianNoise): + """An exploration that adds Ornstein-Uhlenbeck noise to continuous actions. + + If explore=True, returns sampled actions plus a noise term X, + which changes according to this formula: + Xt+1 = -theta*Xt + sigma*N[0,stddev], where theta, sigma and stddev are + constants. Also, some completely random period is possible at the + beginning. + If explore=False, returns the deterministic action. + """ + + def __init__( + self, + action_space, + *, + framework: str, + ou_theta: float = 0.15, + ou_sigma: float = 0.2, + ou_base_scale: float = 0.1, + random_timesteps: int = 1000, + initial_scale: float = 1.0, + final_scale: float = 0.02, + scale_timesteps: int = 10000, + scale_schedule: Optional[Schedule] = None, + **kwargs + ): + """Initializes an Ornstein-Uhlenbeck Exploration object. + + Args: + action_space: The gym action space used by the environment. + ou_theta: The theta parameter of the Ornstein-Uhlenbeck process. + ou_sigma: The sigma parameter of the Ornstein-Uhlenbeck process. + ou_base_scale: A fixed scaling factor, by which all OU- + noise is multiplied. NOTE: This is on top of the parent + GaussianNoise's scaling. + random_timesteps: The number of timesteps for which to act + completely randomly. Only after this number of timesteps, the + `self.scale` annealing process will start (see below). + initial_scale: The initial scaling weight to multiply the + noise with. + final_scale: The final scaling weight to multiply the noise with. + scale_timesteps: The timesteps over which to linearly anneal the + scaling factor (after(!) having used random actions for + `random_timesteps` steps. + scale_schedule: An optional Schedule object to use (instead + of constructing one from the given parameters). + framework: One of None, "tf", "torch". + """ + # The current OU-state value (gets updated each time, an eploration + # action is computed). + self.ou_state = get_variable( + np.array(action_space.low.size * [0.0], dtype=np.float32), + framework=framework, + tf_name="ou_state", + torch_tensor=True, + device=None, + ) + + super().__init__( + action_space, + framework=framework, + random_timesteps=random_timesteps, + initial_scale=initial_scale, + final_scale=final_scale, + scale_timesteps=scale_timesteps, + scale_schedule=scale_schedule, + stddev=1.0, # Force `self.stddev` to 1.0. + **kwargs + ) + self.ou_theta = ou_theta + self.ou_sigma = ou_sigma + self.ou_base_scale = ou_base_scale + # Now that we know the device, move ou_state there, in case of PyTorch. + if self.framework == "torch" and self.device is not None: + self.ou_state = self.ou_state.to(self.device) + + @override(GaussianNoise) + def _get_tf_exploration_action_op( + self, + action_dist: ActionDistribution, + explore: Union[bool, TensorType], + timestep: Union[int, TensorType], + ): + ts = timestep if timestep is not None else self.last_timestep + scale = self.scale_schedule(ts) + + # The deterministic actions (if explore=False). + deterministic_actions = action_dist.deterministic_sample() + + # Apply base-scaled and time-annealed scaled OU-noise to + # deterministic actions. + gaussian_sample = tf.random.normal( + shape=[self.action_space.low.size], stddev=self.stddev + ) + ou_new = self.ou_theta * -self.ou_state + self.ou_sigma * gaussian_sample + if self.framework == "tf2": + self.ou_state.assign_add(ou_new) + ou_state_new = self.ou_state + else: + ou_state_new = tf1.assign_add(self.ou_state, ou_new) + high_m_low = self.action_space.high - self.action_space.low + high_m_low = tf.where( + tf.math.is_inf(high_m_low), tf.ones_like(high_m_low), high_m_low + ) + noise = scale * self.ou_base_scale * ou_state_new * high_m_low + stochastic_actions = tf.clip_by_value( + deterministic_actions + noise, + self.action_space.low * tf.ones_like(deterministic_actions), + self.action_space.high * tf.ones_like(deterministic_actions), + ) + + # Stochastic actions could either be: random OR action + noise. + random_actions, _ = self.random_exploration.get_tf_exploration_action_op( + action_dist, explore + ) + exploration_actions = tf.cond( + pred=tf.convert_to_tensor(ts < self.random_timesteps), + true_fn=lambda: random_actions, + false_fn=lambda: stochastic_actions, + ) + + # Chose by `explore` (main exploration switch). + action = tf.cond( + pred=tf.constant(explore, dtype=tf.bool) + if isinstance(explore, bool) + else explore, + true_fn=lambda: exploration_actions, + false_fn=lambda: deterministic_actions, + ) + # Logp=always zero. + logp = zero_logps_from_actions(deterministic_actions) + + # Increment `last_timestep` by 1 (or set to `timestep`). + if self.framework == "tf2": + if timestep is None: + self.last_timestep.assign_add(1) + else: + self.last_timestep.assign(tf.cast(timestep, tf.int64)) + else: + assign_op = ( + tf1.assign_add(self.last_timestep, 1) + if timestep is None + else tf1.assign(self.last_timestep, timestep) + ) + with tf1.control_dependencies([assign_op, ou_state_new]): + action = tf.identity(action) + logp = tf.identity(logp) + + return action, logp + + @override(GaussianNoise) + def _get_torch_exploration_action( + self, + action_dist: ActionDistribution, + explore: bool, + timestep: Union[int, TensorType], + ): + # Set last timestep or (if not given) increase by one. + self.last_timestep = ( + timestep if timestep is not None else self.last_timestep + 1 + ) + + # Apply exploration. + if explore: + # Random exploration phase. + if self.last_timestep < self.random_timesteps: + action, _ = self.random_exploration.get_torch_exploration_action( + action_dist, explore=True + ) + # Apply base-scaled and time-annealed scaled OU-noise to + # deterministic actions. + else: + det_actions = action_dist.deterministic_sample() + scale = self.scale_schedule(self.last_timestep) + gaussian_sample = scale * torch.normal( + mean=torch.zeros(self.ou_state.size()), std=1.0 + ).to(self.device) + ou_new = ( + self.ou_theta * -self.ou_state + self.ou_sigma * gaussian_sample + ) + self.ou_state += ou_new + high_m_low = torch.from_numpy( + self.action_space.high - self.action_space.low + ).to(self.device) + high_m_low = torch.where( + torch.isinf(high_m_low), + torch.ones_like(high_m_low).to(self.device), + high_m_low, + ) + noise = scale * self.ou_base_scale * self.ou_state * high_m_low + + action = torch.min( + torch.max( + det_actions + noise, + torch.tensor( + self.action_space.low, + dtype=torch.float32, + device=self.device, + ), + ), + torch.tensor( + self.action_space.high, dtype=torch.float32, device=self.device + ), + ) + + # No exploration -> Return deterministic actions. + else: + action = action_dist.deterministic_sample() + + # Logp=always zero. + logp = torch.zeros((action.size()[0],), dtype=torch.float32, device=self.device) + + return action, logp + + @override(GaussianNoise) + def get_state(self, sess: Optional["tf.Session"] = None): + """Returns the current scale value. + + Returns: + Union[float,tf.Tensor[float]]: The current scale value. + """ + if sess: + return sess.run( + dict( + self._tf_state_op, + **{ + "ou_state": self.ou_state, + } + ) + ) + + state = super().get_state() + return dict( + state, + **{ + "ou_state": convert_to_numpy(self.ou_state) + if self.framework != "tf" + else self.ou_state, + } + ) + + @override(GaussianNoise) + def set_state(self, state: dict, sess: Optional["tf.Session"] = None) -> None: + if self.framework == "tf": + self.ou_state.load(state["ou_state"], session=sess) + elif isinstance(self.ou_state, np.ndarray): + self.ou_state = state["ou_state"] + elif torch and torch.is_tensor(self.ou_state): + self.ou_state = torch.from_numpy(state["ou_state"]) + else: + self.ou_state.assign(state["ou_state"]) + super().set_state(state, sess=sess) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/parameter_noise.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/parameter_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..94f1d978f72b260330fab35801767d7da2d59a53 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/parameter_noise.py @@ -0,0 +1,440 @@ +from gymnasium.spaces import Box, Discrete +import numpy as np +from typing import Optional, TYPE_CHECKING, Union + +from ray.rllib.env.base_env import BaseEnv +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import Categorical, Deterministic +from ray.rllib.models.torch.torch_action_dist import ( + TorchCategorical, + TorchDeterministic, +) +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.framework import get_variable, try_import_tf, try_import_torch +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.numpy import softmax, SMALL_NUMBER +from ray.rllib.utils.typing import TensorType + +if TYPE_CHECKING: + from ray.rllib.policy.policy import Policy + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class ParameterNoise(Exploration): + """An exploration that changes a Model's parameters. + + Implemented based on: + [1] https://openai.com/research/better-exploration-with-parameter-noise + [2] https://arxiv.org/pdf/1706.01905.pdf + + At the beginning of an episode, Gaussian noise is added to all weights + of the model. At the end of the episode, the noise is undone and an action + diff (pi-delta) is calculated, from which we determine the changes in the + noise's stddev for the next episode. + """ + + def __init__( + self, + action_space, + *, + framework: str, + policy_config: dict, + model: ModelV2, + initial_stddev: float = 1.0, + random_timesteps: int = 10000, + sub_exploration: Optional[dict] = None, + **kwargs + ): + """Initializes a ParameterNoise Exploration object. + + Args: + initial_stddev: The initial stddev to use for the noise. + random_timesteps: The number of timesteps to act completely + randomly (see [1]). + sub_exploration: Optional sub-exploration config. + None for auto-detection/setup. + """ + assert framework is not None + super().__init__( + action_space, + policy_config=policy_config, + model=model, + framework=framework, + **kwargs + ) + + self.stddev = get_variable( + initial_stddev, framework=self.framework, tf_name="stddev" + ) + self.stddev_val = initial_stddev # Out-of-graph tf value holder. + + # The weight variables of the Model where noise should be applied to. + # This excludes any variable, whose name contains "LayerNorm" (those + # are BatchNormalization layers, which should not be perturbed). + self.model_variables = [ + v + for k, v in self.model.trainable_variables(as_dict=True).items() + if "LayerNorm" not in k + ] + # Our noise to be added to the weights. Each item in `self.noise` + # corresponds to one Model variable and holding the Gaussian noise to + # be added to that variable (weight). + self.noise = [] + for var in self.model_variables: + name_ = var.name.split(":")[0] + "_noisy" if var.name else "" + self.noise.append( + get_variable( + np.zeros(var.shape, dtype=np.float32), + framework=self.framework, + tf_name=name_, + torch_tensor=True, + device=self.device, + ) + ) + + # tf-specific ops to sample, assign and remove noise. + if self.framework == "tf" and not tf.executing_eagerly(): + self.tf_sample_new_noise_op = self._tf_sample_new_noise_op() + self.tf_add_stored_noise_op = self._tf_add_stored_noise_op() + self.tf_remove_noise_op = self._tf_remove_noise_op() + # Create convenience sample+add op for tf. + with tf1.control_dependencies([self.tf_sample_new_noise_op]): + add_op = self._tf_add_stored_noise_op() + with tf1.control_dependencies([add_op]): + self.tf_sample_new_noise_and_add_op = tf.no_op() + + # Whether the Model's weights currently have noise added or not. + self.weights_are_currently_noisy = False + + # Auto-detection of underlying exploration functionality. + if sub_exploration is None: + # For discrete action spaces, use an underlying EpsilonGreedy with + # a special schedule. + if isinstance(self.action_space, Discrete): + sub_exploration = { + "type": "EpsilonGreedy", + "epsilon_schedule": { + "type": "PiecewiseSchedule", + # Step function (see [2]). + "endpoints": [ + (0, 1.0), + (random_timesteps + 1, 1.0), + (random_timesteps + 2, 0.01), + ], + "outside_value": 0.01, + }, + } + elif isinstance(self.action_space, Box): + sub_exploration = { + "type": "OrnsteinUhlenbeckNoise", + "random_timesteps": random_timesteps, + } + # TODO(sven): Implement for any action space. + else: + raise NotImplementedError + + self.sub_exploration = from_config( + Exploration, + sub_exploration, + framework=self.framework, + action_space=self.action_space, + policy_config=self.policy_config, + model=self.model, + **kwargs + ) + + # Whether we need to call `self._delayed_on_episode_start` before + # the forward pass. + self.episode_started = False + + @override(Exploration) + def before_compute_actions( + self, + *, + timestep: Optional[int] = None, + explore: Optional[bool] = None, + tf_sess: Optional["tf.Session"] = None + ): + explore = explore if explore is not None else self.policy_config["explore"] + + # Is this the first forward pass in the new episode? If yes, do the + # noise re-sampling and add to weights. + if self.episode_started: + self._delayed_on_episode_start(explore, tf_sess) + + # Add noise if necessary. + if explore and not self.weights_are_currently_noisy: + self._add_stored_noise(tf_sess=tf_sess) + # Remove noise if necessary. + elif not explore and self.weights_are_currently_noisy: + self._remove_noise(tf_sess=tf_sess) + + @override(Exploration) + def get_exploration_action( + self, + *, + action_distribution: ActionDistribution, + timestep: Union[TensorType, int], + explore: Union[TensorType, bool] + ): + # Use our sub-exploration object to handle the final exploration + # action (depends on the algo-type/action-space/etc..). + return self.sub_exploration.get_exploration_action( + action_distribution=action_distribution, timestep=timestep, explore=explore + ) + + @override(Exploration) + def on_episode_start( + self, + policy: "Policy", + *, + environment: BaseEnv = None, + episode: int = None, + tf_sess: Optional["tf.Session"] = None + ): + # We have to delay the noise-adding step by one forward call. + # This is due to the fact that the optimizer does it's step right + # after the episode was reset (and hence the noise was already added!). + # We don't want to update into a noisy net. + self.episode_started = True + + def _delayed_on_episode_start(self, explore, tf_sess): + # Sample fresh noise and add to weights. + if explore: + self._sample_new_noise_and_add(tf_sess=tf_sess, override=True) + # Only sample, don't apply anything to the weights. + else: + self._sample_new_noise(tf_sess=tf_sess) + self.episode_started = False + + @override(Exploration) + def on_episode_end(self, policy, *, environment=None, episode=None, tf_sess=None): + # Remove stored noise from weights (only if currently noisy). + if self.weights_are_currently_noisy: + self._remove_noise(tf_sess=tf_sess) + + @override(Exploration) + def postprocess_trajectory( + self, + policy: "Policy", + sample_batch: SampleBatch, + tf_sess: Optional["tf.Session"] = None, + ): + noisy_action_dist = noise_free_action_dist = None + # Adjust the stddev depending on the action (pi)-distance. + # Also see [1] for details. + # TODO(sven): Find out whether this can be scrapped by simply using + # the `sample_batch` to get the noisy/noise-free action dist. + _, _, fetches = policy.compute_actions_from_input_dict( + input_dict=sample_batch, explore=self.weights_are_currently_noisy + ) + + # Categorical case (e.g. DQN). + if issubclass(policy.dist_class, (Categorical, TorchCategorical)): + action_dist = softmax(fetches[SampleBatch.ACTION_DIST_INPUTS]) + # Deterministic (Gaussian actions, e.g. DDPG). + elif issubclass(policy.dist_class, (Deterministic, TorchDeterministic)): + action_dist = fetches[SampleBatch.ACTION_DIST_INPUTS] + else: + raise NotImplementedError # TODO(sven): Other action-dist cases. + + if self.weights_are_currently_noisy: + noisy_action_dist = action_dist + else: + noise_free_action_dist = action_dist + + _, _, fetches = policy.compute_actions_from_input_dict( + input_dict=sample_batch, explore=not self.weights_are_currently_noisy + ) + + # Categorical case (e.g. DQN). + if issubclass(policy.dist_class, (Categorical, TorchCategorical)): + action_dist = softmax(fetches[SampleBatch.ACTION_DIST_INPUTS]) + # Deterministic (Gaussian actions, e.g. DDPG). + elif issubclass(policy.dist_class, (Deterministic, TorchDeterministic)): + action_dist = fetches[SampleBatch.ACTION_DIST_INPUTS] + + if noisy_action_dist is None: + noisy_action_dist = action_dist + else: + noise_free_action_dist = action_dist + + delta = distance = None + # Categorical case (e.g. DQN). + if issubclass(policy.dist_class, (Categorical, TorchCategorical)): + # Calculate KL-divergence (DKL(clean||noisy)) according to [2]. + # TODO(sven): Allow KL-divergence to be calculated by our + # Distribution classes (don't support off-graph/numpy yet). + distance = np.nanmean( + np.sum( + noise_free_action_dist + * np.log( + noise_free_action_dist / (noisy_action_dist + SMALL_NUMBER) + ), + 1, + ) + ) + current_epsilon = self.sub_exploration.get_state(sess=tf_sess)[ + "cur_epsilon" + ] + delta = -np.log(1 - current_epsilon + current_epsilon / self.action_space.n) + elif issubclass(policy.dist_class, (Deterministic, TorchDeterministic)): + # Calculate MSE between noisy and non-noisy output (see [2]). + distance = np.sqrt( + np.mean(np.square(noise_free_action_dist - noisy_action_dist)) + ) + current_scale = self.sub_exploration.get_state(sess=tf_sess)["cur_scale"] + delta = getattr(self.sub_exploration, "ou_sigma", 0.2) * current_scale + + # Adjust stddev according to the calculated action-distance. + if distance <= delta: + self.stddev_val *= 1.01 + else: + self.stddev_val /= 1.01 + + # Update our state (self.stddev and self.stddev_val). + self.set_state(self.get_state(), sess=tf_sess) + + return sample_batch + + def _sample_new_noise(self, *, tf_sess=None): + """Samples new noise and stores it in `self.noise`.""" + if self.framework == "tf": + tf_sess.run(self.tf_sample_new_noise_op) + elif self.framework == "tf2": + self._tf_sample_new_noise_op() + else: + for i in range(len(self.noise)): + self.noise[i] = torch.normal( + mean=torch.zeros(self.noise[i].size()), std=self.stddev + ).to(self.device) + + def _tf_sample_new_noise_op(self): + added_noises = [] + for noise in self.noise: + added_noises.append( + tf1.assign( + noise, + tf.random.normal( + shape=noise.shape, stddev=self.stddev, dtype=tf.float32 + ), + ) + ) + return tf.group(*added_noises) + + def _sample_new_noise_and_add(self, *, tf_sess=None, override=False): + if self.framework == "tf": + if override and self.weights_are_currently_noisy: + tf_sess.run(self.tf_remove_noise_op) + tf_sess.run(self.tf_sample_new_noise_and_add_op) + else: + if override and self.weights_are_currently_noisy: + self._remove_noise() + self._sample_new_noise() + self._add_stored_noise() + + self.weights_are_currently_noisy = True + + def _add_stored_noise(self, *, tf_sess=None): + """Adds the stored `self.noise` to the model's parameters. + + Note: No new sampling of noise here. + + Args: + tf_sess (Optional[tf.Session]): The tf-session to use to add the + stored noise to the (currently noise-free) weights. + override: If True, undo any currently applied noise first, + then add the currently stored noise. + """ + # Make sure we only add noise to currently noise-free weights. + assert self.weights_are_currently_noisy is False + + # Add stored noise to the model's parameters. + if self.framework == "tf": + tf_sess.run(self.tf_add_stored_noise_op) + elif self.framework == "tf2": + self._tf_add_stored_noise_op() + else: + for var, noise in zip(self.model_variables, self.noise): + # Add noise to weights in-place. + var.requires_grad = False + var.add_(noise) + var.requires_grad = True + + self.weights_are_currently_noisy = True + + def _tf_add_stored_noise_op(self): + """Generates tf-op that assigns the stored noise to weights. + + Also used by tf-eager. + + Returns: + tf.op: The tf op to apply the already stored noise to the NN. + """ + add_noise_ops = list() + for var, noise in zip(self.model_variables, self.noise): + add_noise_ops.append(tf1.assign_add(var, noise)) + ret = tf.group(*tuple(add_noise_ops)) + with tf1.control_dependencies([ret]): + return tf.no_op() + + def _remove_noise(self, *, tf_sess=None): + """ + Removes the current action noise from the model parameters. + + Args: + tf_sess (Optional[tf.Session]): The tf-session to use to remove + the noise from the (currently noisy) weights. + """ + # Make sure we only remove noise iff currently noisy. + assert self.weights_are_currently_noisy is True + + # Removes the stored noise from the model's parameters. + if self.framework == "tf": + tf_sess.run(self.tf_remove_noise_op) + elif self.framework == "tf2": + self._tf_remove_noise_op() + else: + for var, noise in zip(self.model_variables, self.noise): + # Remove noise from weights in-place. + var.requires_grad = False + var.add_(-noise) + var.requires_grad = True + + self.weights_are_currently_noisy = False + + def _tf_remove_noise_op(self): + """Generates a tf-op for removing noise from the model's weights. + + Also used by tf-eager. + + Returns: + tf.op: The tf op to remve the currently stored noise from the NN. + """ + remove_noise_ops = list() + for var, noise in zip(self.model_variables, self.noise): + remove_noise_ops.append(tf1.assign_add(var, -noise)) + ret = tf.group(*tuple(remove_noise_ops)) + with tf1.control_dependencies([ret]): + return tf.no_op() + + @override(Exploration) + def get_state(self, sess=None): + return {"cur_stddev": self.stddev_val} + + @override(Exploration) + def set_state(self, state: dict, sess: Optional["tf.Session"] = None) -> None: + self.stddev_val = state["cur_stddev"] + # Set self.stddev to calculated value. + if self.framework == "tf": + self.stddev.load(self.stddev_val, session=sess) + elif isinstance(self.stddev, float): + self.stddev = self.stddev_val + else: + self.stddev.assign(self.stddev_val) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_epsilon_greedy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_epsilon_greedy.py new file mode 100644 index 0000000000000000000000000000000000000000..1acdc124cad9d7ac7639706fcb398c745de9c247 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_epsilon_greedy.py @@ -0,0 +1,58 @@ +from gymnasium.spaces import Space +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.exploration.epsilon_greedy import EpsilonGreedy +from ray.rllib.utils.schedules import ConstantSchedule + + +@OldAPIStack +class PerWorkerEpsilonGreedy(EpsilonGreedy): + """A per-worker epsilon-greedy class for distributed algorithms. + + Sets the epsilon schedules of individual workers to a constant: + 0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7) + See Ape-X paper. + """ + + def __init__( + self, + action_space: Space, + *, + framework: str, + num_workers: Optional[int], + worker_index: Optional[int], + **kwargs + ): + """Create a PerWorkerEpsilonGreedy exploration class. + + Args: + action_space: The gym action space used by the environment. + num_workers: The overall number of workers used. + worker_index: The index of the Worker using this + Exploration. + framework: One of None, "tf", "torch". + """ + epsilon_schedule = None + # Use a fixed, different epsilon per worker. See: Ape-X paper. + assert worker_index <= num_workers, (worker_index, num_workers) + if num_workers > 0: + if worker_index > 0: + # From page 5 of https://arxiv.org/pdf/1803.00933.pdf + alpha, eps, i = 7, 0.4, worker_index - 1 + num_workers_minus_1 = float(num_workers - 1) if num_workers > 1 else 1.0 + constant_eps = eps ** (1 + (i / num_workers_minus_1) * alpha) + epsilon_schedule = ConstantSchedule(constant_eps, framework=framework) + # Local worker should have zero exploration so that eval + # rollouts run properly. + else: + epsilon_schedule = ConstantSchedule(0.0, framework=framework) + + super().__init__( + action_space, + epsilon_schedule=epsilon_schedule, + framework=framework, + num_workers=num_workers, + worker_index=worker_index, + **kwargs + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_gaussian_noise.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_gaussian_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..97efa73e97ee945c6ea1f3c54f1408818080f588 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_gaussian_noise.py @@ -0,0 +1,49 @@ +from gymnasium.spaces import Space +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise +from ray.rllib.utils.schedules import ConstantSchedule + + +@OldAPIStack +class PerWorkerGaussianNoise(GaussianNoise): + """A per-worker Gaussian noise class for distributed algorithms. + + Sets the `scale` schedules of individual workers to a constant: + 0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7) + See Ape-X paper. + """ + + def __init__( + self, + action_space: Space, + *, + framework: Optional[str], + num_workers: Optional[int], + worker_index: Optional[int], + **kwargs + ): + """ + Args: + action_space: The gym action space used by the environment. + num_workers: The overall number of workers used. + worker_index: The index of the Worker using this + Exploration. + framework: One of None, "tf", "torch". + """ + scale_schedule = None + # Use a fixed, different epsilon per worker. See: Ape-X paper. + if num_workers > 0: + if worker_index > 0: + num_workers_minus_1 = float(num_workers - 1) if num_workers > 1 else 1.0 + exponent = 1 + (worker_index / num_workers_minus_1) * 7 + scale_schedule = ConstantSchedule(0.4**exponent, framework=framework) + # Local worker should have zero exploration so that eval + # rollouts run properly. + else: + scale_schedule = ConstantSchedule(0.0, framework=framework) + + super().__init__( + action_space, scale_schedule=scale_schedule, framework=framework, **kwargs + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_ornstein_uhlenbeck_noise.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_ornstein_uhlenbeck_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..87b77aa250352028ef130d9e9d87813ae535be19 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/per_worker_ornstein_uhlenbeck_noise.py @@ -0,0 +1,54 @@ +from gymnasium.spaces import Space +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.exploration.ornstein_uhlenbeck_noise import OrnsteinUhlenbeckNoise +from ray.rllib.utils.schedules import ConstantSchedule + + +@OldAPIStack +class PerWorkerOrnsteinUhlenbeckNoise(OrnsteinUhlenbeckNoise): + """A per-worker Ornstein Uhlenbeck noise class for distributed algorithms. + + Sets the Gaussian `scale` schedules of individual workers to a constant: + 0.4 ^ (1 + [worker-index] / float([num-workers] - 1) * 7) + See Ape-X paper. + """ + + def __init__( + self, + action_space: Space, + *, + framework: Optional[str], + num_workers: Optional[int], + worker_index: Optional[int], + **kwargs + ): + """ + Args: + action_space: The gym action space used by the environment. + num_workers: The overall number of workers used. + worker_index: The index of the Worker using this + Exploration. + framework: One of None, "tf", "torch". + """ + scale_schedule = None + # Use a fixed, different epsilon per worker. See: Ape-X paper. + if num_workers > 0: + if worker_index > 0: + num_workers_minus_1 = float(num_workers - 1) if num_workers > 1 else 1.0 + exponent = 1 + (worker_index / num_workers_minus_1) * 7 + scale_schedule = ConstantSchedule(0.4**exponent, framework=framework) + # Local worker should have zero exploration so that eval + # rollouts run properly. + else: + scale_schedule = ConstantSchedule(0.0, framework=framework) + + super().__init__( + action_space, + scale_schedule=scale_schedule, + num_workers=num_workers, + worker_index=worker_index, + framework=framework, + **kwargs + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/random.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/random.py new file mode 100644 index 0000000000000000000000000000000000000000..34d067990e2ea57335838bb2aca8c06293e80ab2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/random.py @@ -0,0 +1,168 @@ +from gymnasium.spaces import Discrete, Box, MultiDiscrete, Space +import numpy as np +import tree # pip install dm_tree +from typing import Union, Optional + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils import force_tuple +from ray.rllib.utils.framework import try_import_tf, try_import_torch, TensorType +from ray.rllib.utils.spaces.simplex import Simplex +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.tf_utils import zero_logps_from_actions + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class Random(Exploration): + """A random action selector (deterministic/greedy for explore=False). + + If explore=True, returns actions randomly from `self.action_space` (via + Space.sample()). + If explore=False, returns the greedy/max-likelihood action. + """ + + def __init__( + self, action_space: Space, *, model: ModelV2, framework: Optional[str], **kwargs + ): + """Initialize a Random Exploration object. + + Args: + action_space: The gym action space used by the environment. + framework: One of None, "tf", "torch". + """ + super().__init__( + action_space=action_space, model=model, framework=framework, **kwargs + ) + + self.action_space_struct = get_base_struct_from_space(self.action_space) + + @override(Exploration) + def get_exploration_action( + self, + *, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True + ): + # Instantiate the distribution object. + if self.framework in ["tf2", "tf"]: + return self.get_tf_exploration_action_op(action_distribution, explore) + else: + return self.get_torch_exploration_action(action_distribution, explore) + + def get_tf_exploration_action_op( + self, + action_dist: ActionDistribution, + explore: Optional[Union[bool, TensorType]], + ): + def true_fn(): + batch_size = 1 + req = force_tuple( + action_dist.required_model_output_shape( + self.action_space, getattr(self.model, "model_config", None) + ) + ) + # Add a batch dimension? + if len(action_dist.inputs.shape) == len(req) + 1: + batch_size = tf.shape(action_dist.inputs)[0] + + # Function to produce random samples from primitive space + # components: (Multi)Discrete or Box. + def random_component(component): + # Have at least an additional shape of (1,), even if the + # component is Box(-1.0, 1.0, shape=()). + shape = component.shape or (1,) + + if isinstance(component, Discrete): + return tf.random.uniform( + shape=(batch_size,) + component.shape, + maxval=component.n, + dtype=component.dtype, + ) + elif isinstance(component, MultiDiscrete): + return tf.concat( + [ + tf.random.uniform( + shape=(batch_size, 1), maxval=n, dtype=component.dtype + ) + for n in component.nvec + ], + axis=1, + ) + elif isinstance(component, Box): + if component.bounded_above.all() and component.bounded_below.all(): + if component.dtype.name.startswith("int"): + return tf.random.uniform( + shape=(batch_size,) + shape, + minval=component.low.flat[0], + maxval=component.high.flat[0], + dtype=component.dtype, + ) + else: + return tf.random.uniform( + shape=(batch_size,) + shape, + minval=component.low, + maxval=component.high, + dtype=component.dtype, + ) + else: + return tf.random.normal( + shape=(batch_size,) + shape, dtype=component.dtype + ) + else: + assert isinstance(component, Simplex), ( + "Unsupported distribution component '{}' for random " + "sampling!".format(component) + ) + return tf.nn.softmax( + tf.random.uniform( + shape=(batch_size,) + shape, + minval=0.0, + maxval=1.0, + dtype=component.dtype, + ) + ) + + actions = tree.map_structure(random_component, self.action_space_struct) + return actions + + def false_fn(): + return action_dist.deterministic_sample() + + action = tf.cond( + pred=tf.constant(explore, dtype=tf.bool) + if isinstance(explore, bool) + else explore, + true_fn=true_fn, + false_fn=false_fn, + ) + + logp = zero_logps_from_actions(action) + return action, logp + + def get_torch_exploration_action( + self, action_dist: ActionDistribution, explore: bool + ): + if explore: + req = force_tuple( + action_dist.required_model_output_shape( + self.action_space, getattr(self.model, "model_config", None) + ) + ) + # Add a batch dimension? + if len(action_dist.inputs.shape) == len(req) + 1: + batch_size = action_dist.inputs.shape[0] + a = np.stack([self.action_space.sample() for _ in range(batch_size)]) + else: + a = self.action_space.sample() + # Convert action to torch tensor. + action = torch.from_numpy(a).to(self.device) + else: + action = action_dist.deterministic_sample() + logp = torch.zeros((action.size()[0],), dtype=torch.float32, device=self.device) + return action, logp diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/random_encoder.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/random_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..567eb17447d482bb57274da1e9524424f95bb496 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/random_encoder.py @@ -0,0 +1,292 @@ +from gymnasium.spaces import Box, Discrete, Space +import numpy as np +from typing import List, Optional, Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.tf_utils import get_placeholder +from ray.rllib.utils.typing import FromConfigSpec, ModelConfigDict, TensorType + +tf1, tf, tfv = try_import_tf() + + +class _MovingMeanStd: + """Track moving mean, std and count.""" + + def __init__(self, epsilon: float = 1e-4, shape: Optional[List[int]] = None): + """Initialize object. + + Args: + epsilon: Initial count. + shape: Shape of the trackables mean and std. + """ + if not shape: + shape = [] + self.mean = np.zeros(shape, dtype=np.float32) + self.var = np.ones(shape, dtype=np.float32) + self.count = epsilon + + def __call__(self, inputs: np.ndarray) -> np.ndarray: + """Normalize input batch using moving mean and std. + + Args: + inputs: Input batch to normalize. + + Returns: + Logarithmic scaled normalized output. + """ + batch_mean = np.mean(inputs, axis=0) + batch_var = np.var(inputs, axis=0) + batch_count = inputs.shape[0] + self.update_params(batch_mean, batch_var, batch_count) + return np.log(inputs / self.std + 1) + + def update_params( + self, batch_mean: float, batch_var: float, batch_count: float + ) -> None: + """Update moving mean, std and count. + + Args: + batch_mean: Input batch mean. + batch_var: Input batch variance. + batch_count: Number of cases in the batch. + """ + delta = batch_mean - self.mean + tot_count = self.count + batch_count + + # This moving mean calculation is from reference implementation. + self.mean = self.mean + delta + batch_count / tot_count + m_a = self.var * self.count + m_b = batch_var * batch_count + M2 = m_a + m_b + np.power(delta, 2) * self.count * batch_count / tot_count + self.var = M2 / tot_count + self.count = tot_count + + @property + def std(self) -> float: + """Get moving standard deviation. + + Returns: + Returns moving standard deviation. + """ + return np.sqrt(self.var) + + +@OldAPIStack +def update_beta(beta_schedule: str, beta: float, rho: float, step: int) -> float: + """Update beta based on schedule and training step. + + Args: + beta_schedule: Schedule for beta update. + beta: Initial beta. + rho: Schedule decay parameter. + step: Current training iteration. + + Returns: + Updated beta as per input schedule. + """ + if beta_schedule == "linear_decay": + return beta * ((1.0 - rho) ** step) + return beta + + +@OldAPIStack +def compute_states_entropy( + obs_embeds: np.ndarray, embed_dim: int, k_nn: int +) -> np.ndarray: + """Compute states entropy using K nearest neighbour method. + + Args: + obs_embeds: Observation latent representation using + encoder model. + embed_dim: Embedding vector dimension. + k_nn: Number of nearest neighbour for K-NN estimation. + + Returns: + Computed states entropy. + """ + obs_embeds_ = np.reshape(obs_embeds, [-1, embed_dim]) + dist = np.linalg.norm(obs_embeds_[:, None, :] - obs_embeds_[None, :, :], axis=-1) + return dist.argsort(axis=-1)[:, :k_nn][:, -1].astype(np.float32) + + +@OldAPIStack +class RE3(Exploration): + """Random Encoder for Efficient Exploration. + + Implementation of: + [1] State entropy maximization with random encoders for efficient + exploration. Seo, Chen, Shin, Lee, Abbeel, & Lee, (2021). + arXiv preprint arXiv:2102.09430. + + Estimates state entropy using a particle-based k-nearest neighbors (k-NN) + estimator in the latent space. The state's latent representation is + calculated using an encoder with randomly initialized parameters. + + The entropy of a state is considered as intrinsic reward and added to the + environment's extrinsic reward for policy optimization. + Entropy is calculated per batch, it does not take the distribution of + the entire replay buffer into consideration. + """ + + def __init__( + self, + action_space: Space, + *, + framework: str, + model: ModelV2, + embeds_dim: int = 128, + encoder_net_config: Optional[ModelConfigDict] = None, + beta: float = 0.2, + beta_schedule: str = "constant", + rho: float = 0.1, + k_nn: int = 50, + random_timesteps: int = 10000, + sub_exploration: Optional[FromConfigSpec] = None, + **kwargs + ): + """Initialize RE3. + + Args: + action_space: The action space in which to explore. + framework: Supports "tf", this implementation does not + support torch. + model: The policy's model. + embeds_dim: The dimensionality of the observation embedding + vectors in latent space. + encoder_net_config: Optional model + configuration for the encoder network, producing embedding + vectors from observations. This can be used to configure + fcnet- or conv_net setups to properly process any + observation space. + beta: Hyperparameter to choose between exploration and + exploitation. + beta_schedule: Schedule to use for beta decay, one of + "constant" or "linear_decay". + rho: Beta decay factor, used for on-policy algorithm. + k_nn: Number of neighbours to set for K-NN entropy + estimation. + random_timesteps: The number of timesteps to act completely + randomly (see [1]). + sub_exploration: The config dict for the underlying Exploration + to use (e.g. epsilon-greedy for DQN). If None, uses the + FromSpecDict provided in the Policy's default config. + + Raises: + ValueError: If the input framework is Torch. + """ + # TODO(gjoliver): Add supports for Pytorch. + if framework == "torch": + raise ValueError("This RE3 implementation does not support Torch.") + super().__init__(action_space, model=model, framework=framework, **kwargs) + + self.beta = beta + self.rho = rho + self.k_nn = k_nn + self.embeds_dim = embeds_dim + if encoder_net_config is None: + encoder_net_config = self.policy_config["model"].copy() + self.encoder_net_config = encoder_net_config + + # Auto-detection of underlying exploration functionality. + if sub_exploration is None: + # For discrete action spaces, use an underlying EpsilonGreedy with + # a special schedule. + if isinstance(self.action_space, Discrete): + sub_exploration = { + "type": "EpsilonGreedy", + "epsilon_schedule": { + "type": "PiecewiseSchedule", + # Step function (see [2]). + "endpoints": [ + (0, 1.0), + (random_timesteps + 1, 1.0), + (random_timesteps + 2, 0.01), + ], + "outside_value": 0.01, + }, + } + elif isinstance(self.action_space, Box): + sub_exploration = { + "type": "OrnsteinUhlenbeckNoise", + "random_timesteps": random_timesteps, + } + else: + raise NotImplementedError + + self.sub_exploration = sub_exploration + + # Creates ModelV2 embedding module / layers. + self._encoder_net = ModelCatalog.get_model_v2( + self.model.obs_space, + self.action_space, + self.embeds_dim, + model_config=self.encoder_net_config, + framework=self.framework, + name="encoder_net", + ) + if self.framework == "tf": + self._obs_ph = get_placeholder( + space=self.model.obs_space, name="_encoder_obs" + ) + self._obs_embeds = tf.stop_gradient( + self._encoder_net({SampleBatch.OBS: self._obs_ph})[0] + ) + + # This is only used to select the correct action + self.exploration_submodule = from_config( + cls=Exploration, + config=self.sub_exploration, + action_space=self.action_space, + framework=self.framework, + policy_config=self.policy_config, + model=self.model, + num_workers=self.num_workers, + worker_index=self.worker_index, + ) + + @override(Exploration) + def get_exploration_action( + self, + *, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True + ): + # Simply delegate to sub-Exploration module. + return self.exploration_submodule.get_exploration_action( + action_distribution=action_distribution, timestep=timestep, explore=explore + ) + + @override(Exploration) + def postprocess_trajectory(self, policy, sample_batch, tf_sess=None): + """Calculate states' latent representations/embeddings. + + Embeddings are added to the SampleBatch object such that it doesn't + need to be calculated during each training step. + """ + if self.framework != "torch": + sample_batch = self._postprocess_tf(policy, sample_batch, tf_sess) + else: + raise ValueError("Not implemented for Torch.") + return sample_batch + + def _postprocess_tf(self, policy, sample_batch, tf_sess): + """Calculate states' embeddings and add it to SampleBatch.""" + if self.framework == "tf": + obs_embeds = tf_sess.run( + self._obs_embeds, + feed_dict={self._obs_ph: sample_batch[SampleBatch.OBS]}, + ) + else: + obs_embeds = tf.stop_gradient( + self._encoder_net({SampleBatch.OBS: sample_batch[SampleBatch.OBS]})[0] + ).numpy() + sample_batch[SampleBatch.OBS_EMBEDS] = obs_embeds + return sample_batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/slate_epsilon_greedy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/slate_epsilon_greedy.py new file mode 100644 index 0000000000000000000000000000000000000000..30f72dc853f7098e28c7391df75d002e103814c3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/slate_epsilon_greedy.py @@ -0,0 +1,114 @@ +from typing import Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.epsilon_greedy import EpsilonGreedy +from ray.rllib.utils.exploration.exploration import TensorType +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class SlateEpsilonGreedy(EpsilonGreedy): + @override(EpsilonGreedy) + def _get_tf_exploration_action_op( + self, + action_distribution: ActionDistribution, + explore: Union[bool, TensorType], + timestep: Union[int, TensorType], + ) -> "tf.Tensor": + + per_slate_q_values = action_distribution.inputs + all_slates = action_distribution.all_slates + + exploit_action = action_distribution.deterministic_sample() + + batch_size, num_slates = ( + tf.shape(per_slate_q_values)[0], + tf.shape(per_slate_q_values)[1], + ) + action_logp = tf.zeros(batch_size, dtype=tf.float32) + + # Get the current epsilon. + epsilon = self.epsilon_schedule( + timestep if timestep is not None else self.last_timestep + ) + # A random action. + random_indices = tf.random.uniform( + (batch_size,), + minval=0, + maxval=num_slates, + dtype=tf.dtypes.int32, + ) + random_actions = tf.gather(all_slates, random_indices) + + choose_random = ( + tf.random.uniform( + tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32 + ) + < epsilon + ) + + # Pick either random or greedy. + action = tf.cond( + pred=tf.constant(explore, dtype=tf.bool) + if isinstance(explore, bool) + else explore, + true_fn=(lambda: tf.where(choose_random, random_actions, exploit_action)), + false_fn=lambda: exploit_action, + ) + + if self.framework == "tf2" and not self.policy_config["eager_tracing"]: + self.last_timestep = timestep + return action, action_logp + else: + assign_op = tf1.assign(self.last_timestep, tf.cast(timestep, tf.int64)) + with tf1.control_dependencies([assign_op]): + return action, action_logp + + @override(EpsilonGreedy) + def _get_torch_exploration_action( + self, + action_distribution: ActionDistribution, + explore: bool, + timestep: Union[int, TensorType], + ) -> "torch.Tensor": + + per_slate_q_values = action_distribution.inputs + all_slates = self.model.slates + device = all_slates.device + + exploit_indices = action_distribution.deterministic_sample() + exploit_indices = exploit_indices.to(device) + exploit_action = all_slates[exploit_indices] + + batch_size = per_slate_q_values.size()[0] + action_logp = torch.zeros(batch_size, dtype=torch.float) + + self.last_timestep = timestep + + # Explore. + if explore: + # Get the current epsilon. + epsilon = self.epsilon_schedule(self.last_timestep) + # A random action. + random_indices = torch.randint( + 0, + per_slate_q_values.shape[1], + (per_slate_q_values.shape[0],), + device=device, + ) + random_actions = all_slates[random_indices] + + # Pick either random or greedy. + action = torch.where( + torch.empty((batch_size,)).uniform_() < epsilon, + random_actions, + exploit_action, + ) + return action, action_logp + # Return the deterministic "sample" (argmax) over the logits. + else: + return exploit_action, action_logp diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/slate_soft_q.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/slate_soft_q.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed2205482e51890db8d0b069e53643b790e60b5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/slate_soft_q.py @@ -0,0 +1,46 @@ +from typing import Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import TensorType +from ray.rllib.utils.exploration.soft_q import SoftQ +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class SlateSoftQ(SoftQ): + @override(SoftQ) + def get_exploration_action( + self, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True, + ): + assert ( + self.framework == "torch" + ), "ERROR: SlateSoftQ only supports torch so far!" + + cls = type(action_distribution) + + # Re-create the action distribution with the correct temperature + # applied. + action_distribution = cls( + action_distribution.inputs, self.model, temperature=self.temperature + ) + batch_size = action_distribution.inputs.size()[0] + action_logp = torch.zeros(batch_size, dtype=torch.float) + + self.last_timestep = timestep + + # Explore. + if explore: + # Return stochastic sample over (q-value) logits. + action = action_distribution.sample() + # Return the deterministic "sample" (argmax) over (q-value) logits. + else: + action = action_distribution.deterministic_sample() + + return action, action_logp diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/soft_q.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/soft_q.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d6fff533733fcf74ded42ffcbcba2d8eded55a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/soft_q.py @@ -0,0 +1,55 @@ +from gymnasium.spaces import Discrete, MultiDiscrete, Space +from typing import Union, Optional + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.tf.tf_action_dist import Categorical +from ray.rllib.models.torch.torch_action_dist import TorchCategorical +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.stochastic_sampling import StochasticSampling +from ray.rllib.utils.framework import TensorType + + +@OldAPIStack +class SoftQ(StochasticSampling): + """Special case of StochasticSampling w/ Categorical and temperature param. + + Returns a stochastic sample from a Categorical parameterized by the model + output divided by the temperature. Returns the argmax iff explore=False. + """ + + def __init__( + self, + action_space: Space, + *, + framework: Optional[str], + temperature: float = 1.0, + **kwargs + ): + """Initializes a SoftQ Exploration object. + + Args: + action_space: The gym action space used by the environment. + temperature: The temperature to divide model outputs by + before creating the Categorical distribution to sample from. + framework: One of None, "tf", "torch". + """ + assert isinstance(action_space, (Discrete, MultiDiscrete)) + super().__init__(action_space, framework=framework, **kwargs) + self.temperature = temperature + + @override(StochasticSampling) + def get_exploration_action( + self, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True, + ): + cls = type(action_distribution) + assert issubclass(cls, (Categorical, TorchCategorical)) + # Re-create the action distribution with the correct temperature + # applied. + dist = cls(action_distribution.inputs, self.model, temperature=self.temperature) + # Delegate to super method. + return super().get_exploration_action( + action_distribution=dist, timestep=timestep, explore=explore + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/stochastic_sampling.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/stochastic_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..d083d6ddd80770ed4acc4b4a456e70794ec8eab8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/stochastic_sampling.py @@ -0,0 +1,156 @@ +import functools +import gymnasium as gym +import numpy as np +from typing import Optional, Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.exploration.random import Random +from ray.rllib.utils.framework import ( + get_variable, + try_import_tf, + try_import_torch, + TensorType, +) +from ray.rllib.utils.tf_utils import zero_logps_from_actions + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class StochasticSampling(Exploration): + """An exploration that simply samples from a distribution. + + The sampling can be made deterministic by passing explore=False into + the call to `get_exploration_action`. + Also allows for scheduled parameters for the distributions, such as + lowering stddev, temperature, etc.. over time. + """ + + def __init__( + self, + action_space: gym.spaces.Space, + *, + framework: str, + model: ModelV2, + random_timesteps: int = 0, + **kwargs + ): + """Initializes a StochasticSampling Exploration object. + + Args: + action_space: The gym action space used by the environment. + framework: One of None, "tf", "torch". + model: The ModelV2 used by the owning Policy. + random_timesteps: The number of timesteps for which to act + completely randomly. Only after this number of timesteps, + actual samples will be drawn to get exploration actions. + """ + assert framework is not None + super().__init__(action_space, model=model, framework=framework, **kwargs) + + # Create the Random exploration module (used for the first n + # timesteps). + self.random_timesteps = random_timesteps + self.random_exploration = Random( + action_space, model=self.model, framework=self.framework, **kwargs + ) + + # The current timestep value (tf-var or python int). + self.last_timestep = get_variable( + np.array(0, np.int64), + framework=self.framework, + tf_name="timestep", + dtype=np.int64, + ) + + @override(Exploration) + def get_exploration_action( + self, + *, + action_distribution: ActionDistribution, + timestep: Optional[Union[int, TensorType]] = None, + explore: bool = True + ): + if self.framework == "torch": + return self._get_torch_exploration_action( + action_distribution, timestep, explore + ) + else: + return self._get_tf_exploration_action_op( + action_distribution, timestep, explore + ) + + def _get_tf_exploration_action_op(self, action_dist, timestep, explore): + ts = self.last_timestep + 1 + + stochastic_actions = tf.cond( + pred=tf.convert_to_tensor(ts < self.random_timesteps), + true_fn=lambda: ( + self.random_exploration.get_tf_exploration_action_op( + action_dist, explore=True + )[0] + ), + false_fn=lambda: action_dist.sample(), + ) + deterministic_actions = action_dist.deterministic_sample() + + action = tf.cond( + tf.constant(explore) if isinstance(explore, bool) else explore, + true_fn=lambda: stochastic_actions, + false_fn=lambda: deterministic_actions, + ) + + logp = tf.cond( + tf.math.logical_and( + explore, tf.convert_to_tensor(ts >= self.random_timesteps) + ), + true_fn=lambda: action_dist.sampled_action_logp(), + false_fn=functools.partial(zero_logps_from_actions, deterministic_actions), + ) + + # Increment `last_timestep` by 1 (or set to `timestep`). + if self.framework == "tf2": + self.last_timestep.assign_add(1) + return action, logp + else: + assign_op = ( + tf1.assign_add(self.last_timestep, 1) + if timestep is None + else tf1.assign(self.last_timestep, timestep) + ) + with tf1.control_dependencies([assign_op]): + return action, logp + + def _get_torch_exploration_action( + self, + action_dist: ActionDistribution, + timestep: Union[TensorType, int], + explore: Union[TensorType, bool], + ): + # Set last timestep or (if not given) increase by one. + self.last_timestep = ( + timestep if timestep is not None else self.last_timestep + 1 + ) + + # Apply exploration. + if explore: + # Random exploration phase. + if self.last_timestep < self.random_timesteps: + action, logp = self.random_exploration.get_torch_exploration_action( + action_dist, explore=True + ) + # Take a sample from our distribution. + else: + action = action_dist.sample() + logp = action_dist.sampled_action_logp() + + # No exploration -> Return deterministic actions. + else: + action = action_dist.deterministic_sample() + logp = torch.zeros_like(action_dist.sampled_action_logp()) + + return action, logp diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/thompson_sampling.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/thompson_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..3d4700790edb0adb100c28b259f210c231181d80 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/thompson_sampling.py @@ -0,0 +1,46 @@ +from typing import Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.framework import ( + TensorType, + try_import_tf, +) + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class ThompsonSampling(Exploration): + @override(Exploration) + def get_exploration_action( + self, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True, + ): + if self.framework == "torch": + return self._get_torch_exploration_action(action_distribution, explore) + elif self.framework == "tf2": + return self._get_tf_exploration_action(action_distribution, explore) + else: + raise NotImplementedError + + def _get_torch_exploration_action(self, action_dist, explore): + if explore: + return action_dist.inputs.argmax(dim=-1), None + else: + scores = self.model.predict(self.model.current_obs()) + return scores.argmax(dim=-1), None + + def _get_tf_exploration_action(self, action_dist, explore): + action = tf.argmax( + tf.cond( + pred=explore, + true_fn=lambda: action_dist.inputs, + false_fn=lambda: self.model.predict(self.model.current_obs()), + ), + axis=-1, + ) + return action, None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/upper_confidence_bound.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/upper_confidence_bound.py new file mode 100644 index 0000000000000000000000000000000000000000..7e7e71efe187db0b1c42cd875acf03b70d949b6c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/exploration/upper_confidence_bound.py @@ -0,0 +1,44 @@ +from typing import Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.framework import ( + TensorType, + try_import_tf, +) + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class UpperConfidenceBound(Exploration): + @override(Exploration) + def get_exploration_action( + self, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True, + ): + if self.framework == "torch": + return self._get_torch_exploration_action(action_distribution, explore) + elif self.framework == "tf2": + return self._get_tf_exploration_action(action_distribution, explore) + else: + raise NotImplementedError + + def _get_torch_exploration_action(self, action_dist, explore): + if explore: + return action_dist.inputs.argmax(dim=-1), None + else: + scores = self.model.value_function() + return scores.argmax(dim=-1), None + + def _get_tf_exploration_action(self, action_dist, explore): + action = tf.argmax( + tf.cond( + explore, lambda: action_dist.inputs, lambda: self.model.value_function() + ), + axis=-1, + ) + return action, None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2704918e32f0c83feb089c563520e2914620276b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__init__.py @@ -0,0 +1,189 @@ +from ray.rllib.core import ALL_MODULES # noqa + + +# Algorithm ResultDict keys. +AGGREGATOR_ACTOR_RESULTS = "aggregator_actors" +DIFFERENTIABLE_LEARNER_RESULTS = "differentiable_learners" +EVALUATION_RESULTS = "evaluation" +ENV_RUNNER_RESULTS = "env_runners" +OFFLINE_EVAL_RUNNER_RESULTS = "offline_eval_runners" +FAULT_TOLERANCE_STATS = "fault_tolerance" +LEARNER_GROUP = "learner_group" +LEARNER_RESULTS = "learners" +REPLAY_BUFFER_RESULTS = "replay_buffer" +TIMERS = "timers" + +# RLModule metrics. +NUM_TRAINABLE_PARAMETERS = "num_trainable_parameters" +NUM_NON_TRAINABLE_PARAMETERS = "num_non_trainable_parameters" + +# Number of times `training_step()` was called in one iteration. +NUM_TRAINING_STEP_CALLS_PER_ITERATION = "num_training_step_calls_per_iteration" + +# Counters for sampling, sampling (on eval workers) and +# training steps (env- and agent steps). +MEAN_NUM_EPISODE_LISTS_RECEIVED = "mean_num_episode_lists_received" +NUM_AGENT_STEPS_SAMPLED = "num_agent_steps_sampled" +NUM_AGENT_STEPS_SAMPLED_LIFETIME = "num_agent_steps_sampled_lifetime" +NUM_AGENT_STEPS_SAMPLED_THIS_ITER = "num_agent_steps_sampled_this_iter" # @OldAPIStack +NUM_ENV_STEPS_SAMPLED = "num_env_steps_sampled" +NUM_ENV_STEPS_SAMPLED_LIFETIME = "num_env_steps_sampled_lifetime" +NUM_ENV_STEPS_SAMPLED_PER_SECOND = "num_env_steps_sampled_per_second" # Deprecated +NUM_ENV_STEPS_SAMPLED_THIS_ITER = "num_env_steps_sampled_this_iter" # @OldAPIStack +NUM_ENV_STEPS_SAMPLED_FOR_EVALUATION_THIS_ITER = ( + "num_env_steps_sampled_for_evaluation_this_iter" +) +NUM_MODULE_STEPS_SAMPLED = "num_module_steps_sampled" +NUM_MODULE_STEPS_SAMPLED_LIFETIME = "num_module_steps_sampled_lifetime" +ENV_TO_MODULE_SUM_EPISODES_LENGTH_IN = "env_to_module_sum_episodes_length_in" +ENV_TO_MODULE_SUM_EPISODES_LENGTH_OUT = "env_to_module_sum_episodes_length_out" + +# Counters for adding and evicting in replay buffers. +ACTUAL_N_STEP = "actual_n_step" +AGENT_ACTUAL_N_STEP = "agent_actual_n_step" +AGENT_STEP_UTILIZATION = "agent_step_utilization" +MODULE_ACTUAL_N_STEP = "module_actual_n_step" +MODULE_STEP_UTILIZATION = "module_step_utilization" +ENV_STEP_UTILIZATION = "env_step_utilization" +NUM_AGENT_EPISODES_STORED = "num_agent_episodes" +NUM_AGENT_EPISODES_ADDED = "num_agent_episodes_added" +NUM_AGENT_EPISODES_ADDED_LIFETIME = "num_agent_episodes_added_lifetime" +NUM_AGENT_EPISODES_EVICTED = "num_agent_episodes_evicted" +NUM_AGENT_EPISODES_EVICTED_LIFETIME = "num_agent_episodes_evicted_lifetime" +NUM_AGENT_EPISODES_PER_SAMPLE = "num_agent_episodes_per_sample" +NUM_AGENT_RESAMPLES = "num_agent_resamples" +NUM_AGENT_STEPS_ADDED = "num_agent_steps_added" +NUM_AGENT_STEPS_ADDED_LIFETIME = "num_agent_steps_added_lifetime" +NUM_AGENT_STEPS_EVICTED = "num_agent_steps_evicted" +NUM_AGENT_STEPS_EVICTED_LIFETIME = "num_agent_steps_evicted_lifetime" +NUM_AGENT_STEPS_PER_SAMPLE = "num_agent_steps_per_sample" +NUM_AGENT_STEPS_PER_SAMPLE_LIFETIME = "num_agent_steps_per_sample_lifetime" +NUM_AGENT_STEPS_STORED = "num_agent_steps_stored" +NUM_ENV_STEPS_ADDED = "num_env_steps_added" +NUM_ENV_STEPS_ADDED_LIFETIME = "num_env_steps_added_lifetime" +NUM_ENV_STEPS_EVICTED = "num_env_steps_evicted" +NUM_ENV_STEPS_EVICTED_LIFETIME = "num_env_steps_evicted_lifetime" +NUM_ENV_STEPS_PER_SAMPLE = "num_env_steps_per_sample" +NUM_ENV_STEPS_PER_SAMPLE_LIFETIME = "num_env_steps_per_sample_lifetime" +NUM_ENV_STEPS_STORED = "num_env_steps_stored" +NUM_EPISODES_STORED = "num_episodes_stored" +NUM_EPISODES_ADDED = "num_episodes_added" +NUM_EPISODES_ADDED_LIFETIME = "num_episodes_added_lifetime" +NUM_EPISODES_EVICTED = "num_episodes_evicted" +NUM_EPISODES_EVICTED_LIFETIME = "num_episodes_evicted_lifetime" +NUM_EPISODES_PER_SAMPLE = "num_episodes_per_sample" +NUM_RESAMPLES = "num_resamples" +NUM_MODULE_EPISODES_STORED = "num_module_episodes" +NUM_MODULE_EPISODES_ADDED = "num_module_episodes_added" +NUM_MODULE_EPISODES_ADDED_LIFETIME = "num_module_episodes_added_lifetime" +NUM_MODULE_EPISODES_EVICTED = "num_module_episodes_evicted" +NUM_MODULE_EPISODES_EVICTED_LIFETIME = "num_module_episodes_evicted_lifetime" +NUM_MODULE_EPISODES_PER_SAMPLE = "num_module_episodes_per_sample" +NUM_MODULE_RESAMPLES = "num_module_resamples" +NUM_MODULE_STEPS_ADDED = "num_module_steps_added" +NUM_MODULE_STEPS_ADDED_LIFETIME = "num_module_steps_added_lifetime" +NUM_MODULE_STEPS_EVICTED = "num_module_steps_evicted" +NUM_MODULE_STEPS_EVICTED_LIFETIME = "num_module_steps_evicted_lifetime" +NUM_MODULE_STEPS_PER_SAMPLE = "num_module_steps_per_sample" +NUM_MODULE_STEPS_PER_SAMPLE_LIFETIME = "num_module_steps_per_sample_lifetime" +NUM_MODULE_STEPS_STORED = "num_module_steps_stored" + +EPISODE_DURATION_SEC_MEAN = "episode_duration_sec_mean" +EPISODE_LEN_MEAN = "episode_len_mean" +EPISODE_LEN_MAX = "episode_len_max" +EPISODE_LEN_MIN = "episode_len_min" +EPISODE_RETURN_MEAN = "episode_return_mean" +EPISODE_RETURN_MAX = "episode_return_max" +EPISODE_RETURN_MIN = "episode_return_min" +NUM_EPISODES = "num_episodes" +NUM_EPISODES_LIFETIME = "num_episodes_lifetime" +TIME_BETWEEN_SAMPLING = "time_between_sampling" + +DATASET_NUM_ITERS_TRAINED = "dataset_num_iters_trained" +DATASET_NUM_ITERS_TRAINED_LIFETIME = "dataset_num_iters_trained_lifetime" +DATASET_NUM_ITERS_EVALUATED = "dataset_num_iters_evaluated" +DATASET_NUM_ITERS_EVALUATED_LIFETIME = "dataset_num_iters_evaluated_lifetime" +MEAN_NUM_LEARNER_GROUP_UPDATE_CALLED = "mean_num_learner_group_update_called" +MEAN_NUM_LEARNER_RESULTS_RECEIVED = "mean_num_learner_results_received" +NUM_AGENT_STEPS_TRAINED = "num_agent_steps_trained" +NUM_AGENT_STEPS_TRAINED_LIFETIME = "num_agent_steps_trained_lifetime" +NUM_AGENT_STEPS_TRAINED_THIS_ITER = "num_agent_steps_trained_this_iter" # @OldAPIStack +NUM_ENV_STEPS_TRAINED = "num_env_steps_trained" +NUM_ENV_STEPS_TRAINED_LIFETIME = "num_env_steps_trained_lifetime" +NUM_ENV_STEPS_TRAINED_THIS_ITER = "num_env_steps_trained_this_iter" # @OldAPIStack +NUM_MODULE_STEPS_TRAINED = "num_module_steps_trained" +NUM_MODULE_STEPS_TRAINED_LIFETIME = "num_module_steps_trained_lifetime" +MODULE_SAMPLE_BATCH_SIZE_MEAN = "module_sample_batch_size_mean" +MODULE_TRAIN_BATCH_SIZE_MEAN = "module_train_batch_size_mean" +LEARNER_CONNECTOR_SUM_EPISODES_LENGTH_IN = "learner_connector_sum_episodes_length_in" +LEARNER_CONNECTOR_SUM_EPISODES_LENGTH_OUT = "learner_connector_sum_episodes_length_out" + +# Backward compatibility: Replace with num_env_steps_... or num_agent_steps_... +STEPS_TRAINED_THIS_ITER_COUNTER = "num_steps_trained_this_iter" + +# Counters for keeping track of worker weight updates (synchronization +# between local worker and remote workers). +NUM_SYNCH_WORKER_WEIGHTS = "num_weight_broadcasts" +NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS = ( + "num_training_step_calls_since_last_synch_worker_weights" +) +# The running sequence number for a set of NN weights. If a worker's NN has a +# lower sequence number than some weights coming in for an update, the worker +# should perform the update, otherwise ignore the incoming weights (they are older +# or the same) as/than the ones it already has. +WEIGHTS_SEQ_NO = "weights_seq_no" +# Number of total gradient updates that have been performed on a policy. +NUM_GRAD_UPDATES_LIFETIME = "num_grad_updates_lifetime" +# Average difference between the number of grad-updates that the policy/ies had +# that collected the training batch vs the policy that was just updated (trained). +# Good measure for the off-policy'ness of training. Should be 0.0 for PPO and PG, +# small for IMPALA and APPO, and any (larger) value for DQN and other off-policy algos. +DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY = "diff_num_grad_updates_vs_sampler_policy" + +# Counters to track target network updates. +LAST_TARGET_UPDATE_TS = "last_target_update_ts" +NUM_TARGET_UPDATES = "num_target_updates" + +# Performance timers +# ------------------ +# Duration of n `Algorithm.training_step()` calls making up one "iteration". +# Note that n may be >1 if the user has set up a min time (sec) or timesteps per +# iteration. +TRAINING_ITERATION_TIMER = "training_iteration" +# Duration of a `Algorithm.evaluate()` call. +EVALUATION_ITERATION_TIMER = "evaluation_iteration" +OFFLINE_EVALUATION_ITERATION_TIMER = "offline_evaluation_iteration_timer" +# Duration of a single `training_step()` call. +TRAINING_STEP_TIMER = "training_step" +APPLY_GRADS_TIMER = "apply_grad" +COMPUTE_GRADS_TIMER = "compute_grads" +GARBAGE_COLLECTION_TIMER = "garbage_collection" +RESTORE_ENV_RUNNERS_TIMER = "restore_env_runners" +RESTORE_EVAL_ENV_RUNNERS_TIMER = "restore_eval_env_runners" +RESTORE_OFFLINE_EVAL_RUNNERS_TIMER = "restore_offline_eval_runners" +SYNCH_WORKER_WEIGHTS_TIMER = "synch_weights" +SYNCH_ENV_CONNECTOR_STATES_TIMER = "synch_env_connectors" +SYNCH_EVAL_ENV_CONNECTOR_STATES_TIMER = "synch_eval_env_connectors" +GRAD_WAIT_TIMER = "grad_wait" +SAMPLE_TIMER = "sample" # @OldAPIStack +ENV_RUNNER_SAMPLING_TIMER = "env_runner_sampling_timer" +ENV_RESET_TIMER = "env_reset_timer" +ENV_STEP_TIMER = "env_step_timer" +ENV_TO_MODULE_CONNECTOR = "env_to_module_connector" +RLMODULE_INFERENCE_TIMER = "rlmodule_inference_timer" +MODULE_TO_ENV_CONNECTOR = "module_to_env_connector" +OFFLINE_SAMPLING_TIMER = "offline_sampling_timer" +REPLAY_BUFFER_ADD_DATA_TIMER = "replay_buffer_add_data_timer" +REPLAY_BUFFER_SAMPLE_TIMER = "replay_buffer_sampling_timer" +REPLAY_BUFFER_UPDATE_PRIOS_TIMER = "replay_buffer_update_prios_timer" +LEARNER_CONNECTOR = "learner_connector" +LEARNER_UPDATE_TIMER = "learner_update_timer" +LEARN_ON_BATCH_TIMER = "learn" # @OldAPIStack +LOAD_BATCH_TIMER = "load" +TARGET_NET_UPDATE_TIMER = "target_net_update" +CONNECTOR_PIPELINE_TIMER = "connector_pipeline_timer" +CONNECTOR_TIMERS = "connectors" + +# Learner. +LEARNER_STATS_KEY = "learner_stats" +TD_ERROR_KEY = "td_error" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab56ac89766087e8b1fb5b471750842c8a78a650 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/learner_info.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/learner_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19bfdf343fbe9f2de90eaf4bbd4a33fd44854549 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/learner_info.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/metrics_logger.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/metrics_logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f49baad4a8fcc0bce1ffbc8d5f619a2633a25d72 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/metrics_logger.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/stats.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/stats.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd7102908063c39e3275b51b62fd7a3a463dfa1b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/stats.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33640ca3a5c6e1c4f453c83091a34e373af42dd9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/window_stat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/window_stat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b5fb11e6cfca6659a090ca405bffff9549f6828 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/__pycache__/window_stat.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/learner_info.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/learner_info.py new file mode 100644 index 0000000000000000000000000000000000000000..b653607cddf34d9f0cd647eef3d10a62ad67229f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/learner_info.py @@ -0,0 +1,120 @@ +from collections import defaultdict +import numpy as np +import tree # pip install dm_tree +from typing import Dict + +from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import PolicyID + +# Instant metrics (keys for metrics.info). +LEARNER_INFO = "learner" +# By convention, metrics from optimizing the loss can be reported in the +# `grad_info` dict returned by learn_on_batch() / compute_grads() via this key. +LEARNER_STATS_KEY = "learner_stats" + + +@OldAPIStack +class LearnerInfoBuilder: + def __init__(self, num_devices: int = 1): + self.num_devices = num_devices + self.results_all_towers = defaultdict(list) + self.is_finalized = False + + def add_learn_on_batch_results( + self, + results: Dict, + policy_id: PolicyID = DEFAULT_POLICY_ID, + ) -> None: + """Adds a policy.learn_on_(loaded)?_batch() result to this builder. + + Args: + results: The results returned by Policy.learn_on_batch or + Policy.learn_on_loaded_batch. + policy_id: The policy's ID, whose learn_on_(loaded)_batch method + returned `results`. + """ + assert ( + not self.is_finalized + ), "LearnerInfo already finalized! Cannot add more results." + + # No towers: Single CPU. + if "tower_0" not in results: + self.results_all_towers[policy_id].append(results) + # Multi-GPU case: + else: + self.results_all_towers[policy_id].append( + tree.map_structure_with_path( + lambda p, *s: _all_tower_reduce(p, *s), + *( + results.pop("tower_{}".format(tower_num)) + for tower_num in range(self.num_devices) + ) + ) + ) + for k, v in results.items(): + if k == LEARNER_STATS_KEY: + for k1, v1 in results[k].items(): + self.results_all_towers[policy_id][-1][LEARNER_STATS_KEY][ + k1 + ] = v1 + else: + self.results_all_towers[policy_id][-1][k] = v + + def add_learn_on_batch_results_multi_agent( + self, + all_policies_results: Dict, + ) -> None: + """Adds multiple policy.learn_on_(loaded)?_batch() results to this builder. + + Args: + all_policies_results: The results returned by all Policy.learn_on_batch or + Policy.learn_on_loaded_batch wrapped as a dict mapping policy ID to + results. + """ + for pid, result in all_policies_results.items(): + if pid != "batch_count": + self.add_learn_on_batch_results(result, policy_id=pid) + + def finalize(self): + self.is_finalized = True + + info = {} + for policy_id, results_all_towers in self.results_all_towers.items(): + # Reduce mean across all minibatch SGD steps (axis=0 to keep + # all shapes as-is). + info[policy_id] = tree.map_structure_with_path( + _all_tower_reduce, *results_all_towers + ) + + return info + + +@OldAPIStack +def _all_tower_reduce(path, *tower_data): + """Reduces stats across towers based on their stats-dict paths.""" + # TD-errors: Need to stay per batch item in order to be able to update + # each item's weight in a prioritized replay buffer. + if len(path) == 1 and path[0] == "td_error": + return np.concatenate(tower_data, axis=0) + elif tower_data[0] is None: + return None + + if isinstance(path[-1], str): + # TODO(sven): We need to fix this terrible dependency on `str.starts_with` + # for determining, how to aggregate these stats! As "num_..." might + # be a good indicator for summing, it will fail if the stats is e.g. + # `num_samples_per_sec" :) + # Counter stats: Reduce sum. + # if path[-1].startswith("num_"): + # return np.nansum(tower_data) + # Min stats: Reduce min. + if path[-1].startswith("min_"): + return np.nanmin(tower_data) + # Max stats: Reduce max. + elif path[-1].startswith("max_"): + return np.nanmax(tower_data) + if np.isnan(tower_data).all(): + return np.nan + # Everything else: Reduce mean. + return np.nanmean(tower_data) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/metrics_logger.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/metrics_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..627ec5b9d5796a087c56c7d4d7ba7c1538cff24a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/metrics_logger.py @@ -0,0 +1,1365 @@ +import logging +from typing import Any, Dict, List, Optional, Tuple, Union +import tree # pip install dm_tree + +from ray.rllib.utils import force_tuple, deep_update +from ray.rllib.utils.metrics.stats import Stats, merge_stats +from ray.rllib.utils.deprecation import Deprecated, deprecation_warning +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.util.annotations import PublicAPI +from ray.util import log_once + +_, tf, _ = try_import_tf() +torch, _ = try_import_torch() +logger = logging.getLogger("ray.rllib") + + +@PublicAPI(stability="alpha") +class MetricsLogger: + """A generic class collecting and processing metrics in RL training and evaluation. + + This class represents the main API used by all of RLlib's components (internal and + user facing) in order to log, collect, and process (reduce) stats during training + and evaluation/inference. + + It supports: + - Logging of simple float/int values (for example a loss) over time or from + parallel runs (n Learner workers, each one reporting a loss from their respective + data shard). + - Logging of images, videos, or other more complex data structures over time. + - Reducing these collected values using a user specified reduction method (for + example "min" or "mean") and other settings controlling the reduction and internal + data, such as sliding windows or EMA coefficients. + - Optionally clearing all logged values after a `reduce()` call to make space for + new data. + - Tracking throughputs of logged values. + + .. testcode:: + + import time + from ray.rllib.utils.metrics.metrics_logger import MetricsLogger + from ray.rllib.utils.test_utils import check + + logger = MetricsLogger(root=True) + + # 1) Logging float values (mean over window): + # Log some loss under the "loss" key. By default, all logged values + # under that key are averaged and reported back, once `reduce()` is called. + logger.log_value("loss", 0.001, reduce="mean", window=10) + logger.log_value("loss", 0.002, reduce="mean", window=10) + # Peek at the current (reduced) value of "loss": + check(logger.peek("loss"), 0.0015) # <- expect average value + # Actually reduce the underlying Stats object(s). + results = logger.reduce() + check(results["loss"], 0.0015) + + # 2) Logging float values (minimum over window): + # Log the minimum of loss values under the "min_loss" key. + logger.log_value("min_loss", 0.1, reduce="min", window=2) + logger.log_value("min_loss", 0.01, reduce="min", window=2) + logger.log_value("min_loss", 0.1, reduce="min", window=2) + logger.log_value("min_loss", 0.02, reduce="min", window=2) + # Peek at the current (reduced) value of "min_loss": + check(logger.peek("min_loss"), 0.02) # <- expect min value (over window=2) + # Actually reduce the underlying Stats object(s). + results = logger.reduce() + check(results["min_loss"], 0.02) + + # 3) Log n counts in different (remote?) components and merge them on the + # controller side. + remote_logger_1 = MetricsLogger() + remote_logger_2 = MetricsLogger() + main_logger = MetricsLogger() + remote_logger_1.log_value("count", 2, reduce="sum", clear_on_reduce=True) + remote_logger_2.log_value("count", 3, reduce="sum", clear_on_reduce=True) + # Reduce the two remote loggers .. + remote_results_1 = remote_logger_1.reduce() + remote_results_2 = remote_logger_2.reduce() + # .. then merge the two results into the controller logger. + main_logger.aggregate([remote_results_1, remote_results_2]) + check(main_logger.peek("count"), 5) + + # 4) Time blocks of code using EMA (coeff=0.1). Note that the higher the coeff + # (the closer to 1.0), the more short term the EMA turns out. + logger = MetricsLogger() + + # First delta measurement: + with logger.log_time("my_block_to_be_timed", reduce="mean", ema_coeff=0.1): + time.sleep(1.0) + # EMA should be ~1sec. + assert 1.1 > logger.peek("my_block_to_be_timed") > 0.9 + # Second delta measurement (note that we don't have to repeat the args again, as + # the stats under that name have already been created above with the correct + # args). + with logger.log_time("my_block_to_be_timed"): + time.sleep(2.0) + # EMA should be ~1.1sec. + assert 1.15 > logger.peek("my_block_to_be_timed") > 1.05 + + # When calling `reduce()`, the internal values list gets cleaned up (reduced) + # and reduction results are returned. + results = logger.reduce() + # EMA should be ~1.1sec. + assert 1.15 > results["my_block_to_be_timed"] > 1.05 + + # 5) Keeping track of throughputs and compiling all metrics + logger = MetricsLogger() + logger.log_value("samples", 1.0, reduce="sum", with_throughput=True, throughput_ema_coeff=1.0) + time.sleep(1.0) + logger.log_value("samples", 2.0, reduce="sum", with_throughput=True, throughput_ema_coeff=1.0) + results = logger.compile() + check(results["samples"], 3.0) + # Since we have an ema_coeff of 1.0, the throughput should be the same as the last value we logged (after 1 second) + check(results["samples_throughput"], 2.0, rtol=0.1) + + """ + + def __init__(self, root=False): + """Initializes a MetricsLogger instance. + + Args: + root: Whether this logger is a root logger. If True, lifetime stats + (clear_on_reduce=False and reduction="sum") will not be cleared on reduce(). + """ + self.stats = {} + self._tensor_mode = False + # TODO (sven): We use a dummy RLock here for most RLlib algos, however, APPO + # and IMPALA require this to be an actual RLock (b/c of thread safety reasons). + # An actual RLock, however, breaks our current OfflineData and + # OfflinePreLearner logic, in which the Learner (which contains a + # MetricsLogger) is serialized and deserialized. We will have to fix this + # offline RL logic first, then can remove this hack here and return to always + # using the RLock. + self._threading_lock = _DummyRLock() + # Is this a root logger? + self._is_root_logger = root + + def __contains__(self, key: Union[str, Tuple[str, ...]]) -> bool: + """Returns True, if `key` can be found in self.stats. + + Args: + key: The key to find in self.stats. This must be either a str (single, + top-level key) or a tuple of str (nested key). + + Returns: + Whether `key` could be found in self.stats. + """ + return self._key_in_stats(key) + + def peek( + self, + key: Union[str, Tuple[str, ...], None] = None, + default=None, + compile: bool = True, + throughput: bool = False, + ) -> Any: + """Returns the reduced values found in this MetricsLogger. + + Note that calling this method does NOT cause an actual underlying value list + reduction, even though reduced values are being returned. It'll keep all + internal structures as-is. By default, this returns a single reduced value or, if + the Stats object has no reduce method, a list of values. When when compile is False, + the result is a list of one or more values. + + Args: + key: The key/key sequence of the sub-structure of `self`, whose (reduced) + values to return. + default: An optional default value in case `key` cannot be found in `self`. + If default is not provided and `key` cannot be found, throws a KeyError. + compile: If True, the result is compiled into a single value if possible. + throughput: If True, the throughput is returned instead of the + actual (reduced) value. + + .. testcode:: + from ray.rllib.utils.metrics.metrics_logger import MetricsLogger + from ray.rllib.utils.test_utils import check + + logger = MetricsLogger() + ema = 0.01 + + # Log some (EMA reduced) values. + key = ("some", "nested", "key", "sequence") + logger.log_value(key, 2.0, ema_coeff=ema) + logger.log_value(key, 3.0) + + # Expected reduced value: + expected_reduced = (1.0 - ema) * 2.0 + ema * 3.0 + + # Peek at the (reduced) value under `key`. + check(logger.peek(key), expected_reduced) + + # Peek at the (reduced) nested struct under ("some", "nested"). + check( + logger.peek(("some", "nested")), + {"key": {"sequence": expected_reduced}}, + ) + + # Log some more, check again. + logger.log_value(key, 4.0) + expected_reduced = (1.0 - ema) * expected_reduced + ema * 4.0 + check(logger.peek(key=key), expected_reduced) + + Returns: + The (reduced) values of the (possibly nested) sub-structure found under + the given key or key sequence. + """ + if throughput: + return self._get_throughputs(key=key, default=default) + + # Create a reduced view of the entire stats structure. + def _nested_peek(stats): + return tree.map_structure( + # If the Stats object has a reduce method, we need to convert the list to a single value + lambda s: ( + s.peek(compile=compile) + if s._reduce_method is not None + else s.peek(compile=compile)[0] + ) + if isinstance(s, Stats) + else s, + stats.copy(), + ) + + with self._threading_lock: + if key is None: + return _nested_peek(self.stats) + else: + if default is None: + stats = self._get_key(key, key_error=True) + else: + stats = self._get_key(key, key_error=False) + + if isinstance(stats, Stats): + # If the Stats object has a reduce method, we need to convert the list to a single value + return stats.peek(compile=compile) + + elif isinstance(stats, dict) and stats: + return _nested_peek(stats) + else: + return default + + @staticmethod + def peek_results(results: Any, compile: bool = True) -> Any: + """Performs `peek()` on any leaf element of an arbitrarily nested Stats struct. + + Args: + results: The nested structure of Stats-leafs to be peek'd and returned. + compile: If True, the result is compiled into a single value if possible. + + Returns: + A corresponding structure of the peek'd `results` (reduced float/int values; + no Stats objects). + """ + return tree.map_structure( + lambda s: s.peek(compile=compile) if isinstance(s, Stats) else s, results + ) + + def log_value( + self, + key: Union[str, Tuple[str, ...]], + value: Any, + *, + reduce: Optional[str] = "mean", + window: Optional[Union[int, float]] = None, + ema_coeff: Optional[float] = None, + percentiles: Union[List[int], bool] = False, + clear_on_reduce: bool = False, + with_throughput: bool = False, + throughput_ema_coeff: Optional[float] = None, + reduce_per_index_on_aggregate: bool = False, + ) -> None: + """Logs a new value under a (possibly nested) key to the logger. + + .. testcode:: + + from ray.rllib.utils.metrics.metrics_logger import MetricsLogger + from ray.rllib.utils.test_utils import check + + logger = MetricsLogger(root=True) + + # Log n simple float values under the "loss" key. By default, all logged + # values under that key are averaged, once `reduce()` is called. + logger.log_value("loss", 0.01, window=10) + logger.log_value("loss", 0.02, window=10) + logger.log_value("loss", 0.03, window=10) + + # Peek at the current (reduced) value. + # Note that in the underlying structure, the internal values list still + # contains all logged values (0.01, 0.02, and 0.03). + check(logger.peek("loss"), 0.02) + + # Log 10x (window size) the same value. + for _ in range(10): + logger.log_value("loss", 0.05, window=10) + check(logger.peek("loss"), 0.05) + + # Internals check (note that users should not be concerned with accessing + # these). Len should always be 10, since the underlying struct is a + # `deque(max_len=10)`. + check(len(logger.stats["loss"].values), 10) + + # Only, when we call `reduce` does the underlying structure get "cleaned + # up". In this case, the list is shortened to 10 items (window size). + results = logger.reduce() + check(results, {"loss": 0.05}) + check(len(logger.stats["loss"].values), 10) + + # Log a value under a deeper nested key. + logger.log_value(("some", "nested", "key"), -1.0) + check(logger.peek(("some", "nested", "key")), -1.0) + + # Log n values without reducing them (we want to just collect some items). + logger.log_value("some_items", 5.0, reduce=None) + logger.log_value("some_items", 6.0, reduce=None) + logger.log_value("some_items", 7.0, reduce=None) + # Peeking at these returns the full list of items (no reduction set up). + check(logger.peek("some_items"), [5.0, 6.0, 7.0]) + # If you don't want the internal list to grow indefinitely, you should set + # `clear_on_reduce=True`: + logger.log_value("some_more_items", -5.0, reduce=None, clear_on_reduce=True) + logger.log_value("some_more_items", -6.0, reduce=None, clear_on_reduce=True) + logger.log_value("some_more_items", -7.0, reduce=None, clear_on_reduce=True ) + # Peeking at these returns the full list of items (no reduction set up). + check(logger.peek("some_more_items"), [-5.0, -6.0, -7.0]) + # Reducing everything (and return plain values, not `Stats` objects). + results = logger.reduce() + check(results, { + "loss": 0.05, + "some": { + "nested": { + "key": -1.0, + }, + }, + "some_items": [5.0, 6.0, 7.0], # reduce=None; list as-is + "some_more_items": [-5.0, -6.0, -7.0], # reduce=None; list as-is + }) + # However, the `reduce()` call did empty the `some_more_items` list + # (b/c we set `clear_on_reduce=True`). + check(logger.peek("some_more_items"), []) + # ... but not the "some_items" list (b/c `clear_on_reduce=False`). + check(logger.peek("some_items"), []) + + Args: + key: The key (or nested key-tuple) to log the `value` under. + value: The value to log. This should be a numeric value. + reduce: The reduction method to apply, once `self.reduce()` is called. + If None, will collect all logged values under `key` in a list (and + also return that list upon calling `self.reduce()`). + window: An optional window size to reduce over. + If not None, then the reduction operation is only applied to the most + recent `window` items, and - after reduction - the internal values list + under `key` is shortened to hold at most `window` items (the most + recent ones). + Must be None if `ema_coeff` is provided. + If None (and `ema_coeff` is None), reduction must not be "mean". + ema_coeff: An optional EMA coefficient to use if `reduce` is "mean" + and no `window` is provided. Note that if both `window` and `ema_coeff` + are provided, an error is thrown. Also, if `ema_coeff` is provided, + `reduce` must be "mean". + The reduction formula for EMA is: + EMA(t1) = (1.0 - ema_coeff) * EMA(t0) + ema_coeff * new_value + percentiles: If reduce is `None`, we can compute the percentiles of the + values list given by `percentiles`. Defaults to [0, 0.5, 0.75, 0.9, 0.95, + 0.99, 1] if set to True. When using percentiles, a window must be provided. + This window should be chosen carefully. RLlib computes exact percentiles and + the computational complexity is O(m*n*log(n/m)) where n is the window size + and m is the number of parallel metrics loggers involved (for example, + m EnvRunners). + clear_on_reduce: If True, all values under `key` will be emptied after + `self.reduce()` is called. Setting this to True is useful for cases, + in which the internal values list would otherwise grow indefinitely, + for example if reduce is None and there is no `window` provided. + with_throughput: Whether to track a throughput estimate together with this + metric. This is only supported for `reduce=sum` and + `clear_on_reduce=False` metrics (aka. "lifetime counts"). The `Stats` + object under the logged key then keeps track of the time passed + between two consecutive calls to `reduce()` and update its throughput + estimate. The current throughput estimate of a key can be obtained + through: .peek(key, throughput=True). + throughput_ema_coeff: The EMA coefficient to use for throughput tracking. + Only used if with_throughput=True. Defaults to 0.05 if with_throughput is True. + reduce_per_index_on_aggregate: If True, when merging Stats objects in parallel, we reduce + incoming values per index such that the new value at index `n` will be + the reduced value of all incoming values at index `n`. + If False, when reducing `n` Stats, the first `n` merged values will be + the reduced value of all incoming values at index `0`, the next `n` merged + values will be the reduced values of all incoming values at index `1`, etc. + """ + # No reduction (continue appending to list) AND no window. + # -> We'll force-reset our values upon `reduce()`. + if reduce is None and (window is None or window == float("inf")): + clear_on_reduce = True + + # Set default ema_coeff to 0.01 if reduce is "mean" and no window is provided + if reduce == "mean" and window is None and ema_coeff is None: + ema_coeff = 0.01 + + if with_throughput and throughput_ema_coeff is None: + throughput_ema_coeff = 0.05 + + value = self._detach_tensor_if_necessary(value) + + with self._threading_lock: + # `key` doesn't exist -> Automatically create it. + if not self._key_in_stats(key): + self._set_key( + key, + ( + Stats( + value, + reduce=reduce, + percentiles=percentiles, + window=window, + ema_coeff=ema_coeff, + clear_on_reduce=clear_on_reduce, + throughput=with_throughput, + throughput_ema_coeff=throughput_ema_coeff, + reduce_per_index_on_aggregate=reduce_per_index_on_aggregate, + ) + ), + ) + else: + stats = self._get_key(key) + if reduce != stats._reduce_method and log_once(f"reduce_warning_{key}"): + logger.warning( + f"reduce should be the same for all logged values under the same key, " + f"but got argument reduce={reduce} while the existing Stats object {key} " + f"has reduce={stats._reduce_method}." + ) + if clear_on_reduce != stats._clear_on_reduce and log_once( + f"clear_on_reduce_warning_{key}" + ): + logger.warning( + f"clear_on_reduce should be the same for all logged values under the same key, " + f"but got argument clear_on_reduce={clear_on_reduce} while the existing Stats object {key} " + f"has clear_on_reduce={stats._clear_on_reduce}." + ) + if with_throughput != bool(stats.has_throughput) and log_once( + f"with_throughput_warning_{key}" + ): + logger.warning( + f"with_throughput should be the same for all logged values under the same key, " + f"but got argument with_throughput={with_throughput} while the existing Stats object {key} " + f"has has_throughput={stats.has_throughput}. This warning will always be shown if you are using an older checkpoint." + ) + if throughput_ema_coeff != stats._throughput_ema_coeff and log_once( + f"throughput_ema_coeff_warning_{key}" + ): + logger.warning( + f"throughput_ema_coeff should be the same for all logged values under the same key, " + f"but got argument throughput_ema_coeff={throughput_ema_coeff} while the existing Stats object {key} " + f"has throughput_ema_coeff={stats._throughput_ema_coeff}. This warning will always be shown if you are using an older checkpoint." + ) + if window != stats._window and log_once(f"window_warning_{key}"): + logger.warning( + f"window should be the same for all logged values under the same key, " + f"but got argument window={window} while the existing Stats object {key} " + f"has window={stats._window}." + ) + if percentiles != getattr(stats, "_percentiles", False) and log_once( + f"percentiles_warning_{key}" + ): + logger.warning( + "percentiles should be the same for all logged values under the same key, " + f"but got argument percentiles={percentiles} while the existing Stats object {key} " + f"has percentiles={getattr(stats, '_percentiles', False)}." + ) + + if ( + reduce_per_index_on_aggregate + != stats._reduce_per_index_on_aggregate + and log_once(f"reduce_per_index_on_aggregate_warning_{key}") + ): + logger.warning( + f"reduce_per_index_on_aggregate should be the same for all logged values under the same key, " + f"but got argument reduce_per_index_on_aggregate={reduce_per_index_on_aggregate} while the existing Stats object {key} " + f"has reduce_per_index_on_aggregate={stats._reduce_per_index_on_aggregate}." + ) + + stats.push(value) + + def log_dict( + self, + value_dict, + *, + key: Optional[Union[str, Tuple[str, ...]]] = None, + reduce: Optional[str] = "mean", + window: Optional[Union[int, float]] = None, + ema_coeff: Optional[float] = None, + percentiles: Union[List[int], bool] = False, + clear_on_reduce: bool = False, + with_throughput: bool = False, + throughput_ema_coeff: Optional[float] = None, + reduce_per_index_on_aggregate: bool = False, + ) -> None: + """Logs all leafs of a possibly nested dict of values to this logger. + + To aggregate logs from upstream components, use `aggregate`. + + This is a convinience function that is equivalent to: + ``` + tree.map_structure_with_path(lambda path, value: logger.log_value(path, value, ...), value_dict) + ``` + + Traverses through all leafs of `stats_dict` and - if a path cannot be found in + this logger yet, will add the `Stats` found at the leaf under that new key. + If a path already exists, will merge the found leaf (`Stats`) with the ones + already logged before. This way, `stats_dict` does NOT have to have + the same structure as what has already been logged to `self`, but can be used to + log values under new keys or nested key paths. + + .. testcode:: + from ray.rllib.utils.metrics.metrics_logger import MetricsLogger + from ray.rllib.utils.test_utils import check + + logger = MetricsLogger() + + # Log n dicts with keys "a" and (some) "b". By default, all logged values + # under that key are averaged, once `reduce()` is called. + logger.log_dict( + { + "a": 0.1, + "b": -0.1, + }, + window=10, + ) + logger.log_dict({ + "b": -0.2, + }) # don't have to repeat `window` arg if key already exists + logger.log_dict({ + "a": 0.2, + "c": {"d": 5.0}, # can also introduce an entirely new (nested) key + }) + + # Peek at the current (reduced) values under "a" and "b". + check(logger.peek("a"), 0.15) + check(logger.peek("b"), -0.15) + check(logger.peek(("c", "d")), 5.0) + + # Reduced all stats. + results = logger.reduce() + check(results, { + "a": 0.15, + "b": -0.15, + "c": {"d": 5.0}, + }) + + Args: + value_dict: The (possibly nested) dict with individual values as + leafs to be logged to this logger. + key: An additional key (or tuple of keys) to prepend to all the keys + (or tuples of keys in case of nesting) found inside `stats_dict`. + Useful to log the entire contents of `stats_dict` in a more organized + fashion under one new key, for example logging the results returned by + an EnvRunner under key + reduce: The reduction method to apply, once `self.reduce()` is called. + If None, will collect all logged values under `key` in a list (and + also return that list upon calling `self.reduce()`). + window: An optional window size to reduce over. + If not None, then the reduction operation is only applied to the most + recent `window` items, and - after reduction - the internal values list + under `key` is shortened to hold at most `window` items (the most + recent ones). + Must be None if `ema_coeff` is provided. + If None (and `ema_coeff` is None), reduction must not be "mean". + ema_coeff: An optional EMA coefficient to use if `reduce` is "mean" + and no `window` is provided. Note that if both `window` and `ema_coeff` + are provided, an error is thrown. Also, if `ema_coeff` is provided, + `reduce` must be "mean". + The reduction formula for EMA is: + EMA(t1) = (1.0 - ema_coeff) * EMA(t0) + ema_coeff * new_value + percentiles: If reduce is `None`, we can compute the percentiles of the + values list given by `percentiles`. Defaults to [0, 0.5, 0.75, 0.9, 0.95, + 0.99, 1] if set to True. When using percentiles, a window must be provided. + This window should be chosen carefully. RLlib computes exact percentiles and + the computational complexity is O(m*n*log(n/m)) where n is the window size + and m is the number of parallel metrics loggers involved (for example, + m EnvRunners). + clear_on_reduce: If True, all values under `key` will be emptied after + `self.reduce()` is called. Setting this to True is useful for cases, + in which the internal values list would otherwise grow indefinitely, + for example if reduce is None and there is no `window` provided. + with_throughput: Whether to track a throughput estimate together with this + metric. This is only supported for `reduce=sum` and + `clear_on_reduce=False` metrics (aka. "lifetime counts"). The `Stats` + object under the logged key then keeps track of the time passed + between two consecutive calls to `reduce()` and update its throughput + estimate. The current throughput estimate of a key can be obtained + through: .peek(key, throughput=True). + throughput_ema_coeff: The EMA coefficient to use for throughput tracking. + Only used if with_throughput=True. Defaults to 0.05 if with_throughput is True. + reduce_per_index_on_aggregate: If True, when merging Stats objects, we reduce + incoming values per index such that the new value at index `n` will be + the reduced value of all incoming values at index `n`. + If False, when reducing `n` Stats, the first `n` merged values will be + the reduced value of all incoming values at index `0`, the next `n` merged + values will be the reduced values of all incoming values at index `1`, etc. + """ + assert isinstance( + value_dict, dict + ), f"`stats_dict` ({value_dict}) must be dict!" + + prefix_key = force_tuple(key) + + def _map(path, stat_or_value): + extended_key = prefix_key + force_tuple(tree.flatten(path)) + + if isinstance(stat_or_value, Stats): + deprecation_warning( + old="MetricsLogger.log_dict() for Stats objects", + new="MetricsLogger.aggregate()", + error=True, + ) + + self.log_value( + extended_key, + value=stat_or_value, + reduce=reduce, + window=window, + ema_coeff=ema_coeff, + percentiles=percentiles, + clear_on_reduce=clear_on_reduce, + with_throughput=with_throughput, + throughput_ema_coeff=throughput_ema_coeff, + reduce_per_index_on_aggregate=reduce_per_index_on_aggregate, + ) + + with self._threading_lock: + tree.map_structure_with_path(_map, value_dict) + + @Deprecated(new="aggregate", error=False) + def merge_and_log_n_dicts(self, *args, **kwargs): + return self.aggregate(*args, **kwargs) + + def aggregate( + self, + stats_dicts: List[Dict[str, Any]], + *, + key: Optional[Union[str, Tuple[str, ...]]] = None, + ) -> None: + """Merges n stats_dicts and logs result by merging on the time axis with existing stats. + + The n stats_dicts should be generated by n parallel components such that merging their + respective stats in parallel is meaningful. This lets us aggregate stats in a tree structure of + MetricsLoggers. + + If you want to log a dictionary of values (not Stats objects), use `log_dict`. + + .. testcode:: + + from ray.rllib.utils.metrics.metrics_logger import MetricsLogger + from ray.rllib.utils.test_utils import check + + # Example: n Learners logging loss stats to be merged. + # Note that losses should usually be logged with a window=1 so they don't + # get smeared over time and instead provide an accurate picture of the + # current situation. + main_logger = MetricsLogger() + + logger_learner1 = MetricsLogger() + logger_learner1.log_value("loss", 0.1, window=1) + learner1_results = logger_learner1.reduce() + + logger_learner2 = MetricsLogger() + logger_learner2.log_value("loss", 0.2, window=1) + learner2_results = logger_learner2.reduce() + + # Merge the stats from both Learners. + main_logger.aggregate( + [learner1_results, learner2_results], + key="learners", + ) + check(main_logger.peek(("learners", "loss")), 0.15) + + # Example: m EnvRunners logging episode returns to be merged. + main_logger = MetricsLogger() + + logger_env_runner1 = MetricsLogger() + logger_env_runner1.log_value("mean_ret", 100.0, window=3) + logger_env_runner1.log_value("mean_ret", 200.0, window=3) + logger_env_runner1.log_value("mean_ret", 300.0, window=3) + logger_env_runner1.log_value("mean_ret", 400.0, window=3) + env_runner1_results = logger_env_runner1.reduce() + + logger_env_runner2 = MetricsLogger() + logger_env_runner2.log_value("mean_ret", 150.0, window=3) + logger_env_runner2.log_value("mean_ret", 250.0, window=3) + logger_env_runner2.log_value("mean_ret", 350.0, window=3) + logger_env_runner2.log_value("mean_ret", 450.0, window=3) + env_runner2_results = logger_env_runner2.reduce() + + # Merge the stats from both EnvRunners. + main_logger.aggregate( + [env_runner1_results, env_runner2_results], + key="env_runners", + ) + # The expected procedure is as follows: + # The individual internal values lists of the two loggers are as follows: + # env runner 1: [200, 300, 400] + # env runner 2: [250, 350, 450] + # Move backwards from index=-1 (each time, loop through both env runners) + # index=-1 -> [400, 450] -> mean -> [425] -> repeat 2 times (number + # of env runners) -> [425, 425] + # index=-2 -> [300, 350] -> mean -> [325] -> repeat 2 times + # -> append -> [425, 425, 325, 325] -> STOP b/c we have reached >= window. + # reverse the list -> [325, 325, 425, 425] + # deque(max_len=3) -> [325, 425, 425] + check( + main_logger.stats["env_runners"]["mean_ret"].values, + [325, 425, 425], + ) + check(main_logger.peek(("env_runners", "mean_ret")), (325 + 425 + 425) / 3) + + # Example: Lifetime sum over n parallel components' stats. + main_logger = MetricsLogger() + + logger1 = MetricsLogger() + logger1.log_value("some_stat", 50, reduce="sum", window=None) + logger1.log_value("some_stat", 25, reduce="sum", window=None) + logger1_results = logger1.reduce() + + logger2 = MetricsLogger() + logger2.log_value("some_stat", 75, reduce="sum", window=None) + logger2_results = logger2.reduce() + + # Merge the stats from both Learners. + main_logger.aggregate([logger1_results, logger2_results]) + check(main_logger.peek("some_stat"), 150) + + # Example: Sum over n parallel components' stats with a window of 3. + main_logger = MetricsLogger() + + logger1 = MetricsLogger() + logger1.log_value("some_stat", 50, reduce="sum", window=3) + logger1.log_value("some_stat", 25, reduce="sum", window=3) + logger1.log_value("some_stat", 10, reduce="sum", window=3) + logger1.log_value("some_stat", 5, reduce="sum", window=3) + logger1_results = logger1.reduce() + + logger2 = MetricsLogger() + logger2.log_value("some_stat", 75, reduce="sum", window=3) + logger2.log_value("some_stat", 100, reduce="sum", window=3) + logger2_results = logger2.reduce() + + # Merge the stats from both Learners. + main_logger.aggregate([logger1_results, logger2_results]) + # The expected procedure is as follows: + # The individual internal values lists of the two loggers are as follows: + # env runner 1: [50, 25, 10, 5] + # env runner 2: [75, 100] + # Move backwards from index=-1 (each time, loop through both loggers) + # index=-1 -> [5, 100] -> reduce over both two indices -> [(5 + 100) / 2, (5 + 100) / 2] = [52.5, 52.5] + # Result = [52.5, 52.5] + # len() = 2 < window = 3 + # index=-2 -> [10, 75] -> reduce over both two indices -> [(10 + 75) / 2, (10 + 75) / 2] = [42.5, 42.5] + # result = [42.5, 42.5, 52.5, 52.5] + # len() = 4 >= window = 3 + check(main_logger.peek("some_stat"), 147.5) # last 3 items (window) get sum'd + + Args: + stats_dicts: List of n stats dicts to be merged and then logged. + key: Optional top-level key under which to log all keys/key sequences + found in the n `stats_dicts`. + """ + assert isinstance(stats_dicts, list), "stats_dicts must be a list" + all_keys = set() + + def traverse_and_add_paths(d, path=()): + if isinstance(d, dict): + new_dict = {} + for key, value in d.items(): + new_dict[key] = traverse_and_add_paths(value, path + (key,)) + return new_dict + elif isinstance(d, list): + all_keys.add(path) + if len(d) == 1: + return d[0] + return d + else: + # For lists and values, we add the path to the set of all keys + all_keys.add(path) + return d + + def build_nested_dict(stats_dict, key): + if isinstance(key, str): + return {key: stats_dict} + elif len(key) > 1: + # Key is tuple of keys so we build a nested dict recursively + return {key[0]: build_nested_dict(stats_dict, key[1:])} + else: + return {key[0]: stats_dict} + + # We do one pass over all the stats_dicts_or_loggers to 1. prepend the key if provided and 2. collect all the keys that lead to leaves (which may be lists or values). + incoming_stats_dicts_with_key = [] + for stats_dict in stats_dicts: + if key is not None: + stats_dict = build_nested_dict(stats_dict, key) + stats_dict = traverse_and_add_paths(stats_dict) + incoming_stats_dicts_with_key.append(stats_dict) + + tree.map_structure_with_path( + lambda path, _: all_keys.add(force_tuple(path)), + self.stats, + ) + + for key in all_keys: + # Get all incoming Stats objects for this key + incoming_stats = [ + self._get_key(key, stats=s) + for s in incoming_stats_dicts_with_key + if self._key_in_stats(key, stats=s) + ] + + structure_under_key = self._get_key(key, stats=self.stats, key_error=False) + # self._get_key returns {} if the key is not found + own_stats = ( + None if isinstance(structure_under_key, dict) else structure_under_key + ) + + merged_stats = merge_stats( + base_stats=own_stats, incoming_stats=incoming_stats + ) + + self._set_key(key, merged_stats) + + def log_time( + self, + key: Union[str, Tuple[str, ...]], + *, + reduce: str = "mean", + window: Optional[Union[int, float]] = None, + ema_coeff: Optional[float] = None, + percentiles: Union[List[int], bool] = False, + clear_on_reduce: bool = False, + with_throughput: bool = False, + throughput_ema_coeff: float = 0.05, + reduce_per_index_on_aggregate: bool = False, + ) -> Stats: + """Measures and logs a time delta value under `key` when used with a with-block. + + .. testcode:: + + import time + from ray.rllib.utils.metrics.metrics_logger import MetricsLogger + + logger = MetricsLogger() + + # First delta measurement: + with logger.log_time("my_block_to_be_timed", ema_coeff=0.1): + time.sleep(1.0) + + # EMA should be ~1sec. + assert 1.1 > logger.peek("my_block_to_be_timed") > 0.9 + + # Second delta measurement (note that we don't have to repeat the args + # again, as the stats under that name have already been created above with + # the correct args). + with logger.log_time("my_block_to_be_timed"): + time.sleep(2.0) + + # EMA should be ~1.1sec. + assert 1.15 > logger.peek("my_block_to_be_timed") > 1.05 + + # When calling `reduce()`, the latest, reduced value is returned. + results = logger.reduce() + # EMA should be ~1.1sec. + assert 1.15 > results["my_block_to_be_timed"] > 1.05 + + Args: + key: The key (or tuple of keys) to log the measured time delta under. + reduce: The reduction method to apply, once `self.reduce()` is called. + If None, will collect all logged values under `key` in a list (and + also return that list upon calling `self.reduce()`). + window: An optional window size to reduce over. + If not None, then the reduction operation is only applied to the most + recent `window` items, and - after reduction - the internal values list + under `key` is shortened to hold at most `window` items (the most + recent ones). + Must be None if `ema_coeff` is provided. + If None (and `ema_coeff` is None), reduction must not be "mean". + ema_coeff: An optional EMA coefficient to use if `reduce` is "mean" + and no `window` is provided. Note that if both `window` and `ema_coeff` + are provided, an error is thrown. Also, if `ema_coeff` is provided, + `reduce` must be "mean". + The reduction formula for EMA is: + EMA(t1) = (1.0 - ema_coeff) * EMA(t0) + ema_coeff * new_value + percentiles: If reduce is `None`, we can compute the percentiles of the + values list given by `percentiles`. Defaults to [0, 0.5, 0.75, 0.9, 0.95, + 0.99, 1] if set to True. When using percentiles, a window must be provided. + This window should be chosen carefully. RLlib computes exact percentiles and + the computational complexity is O(m*n*log(n/m)) where n is the window size + and m is the number of parallel metrics loggers involved (for example, + m EnvRunners). + clear_on_reduce: If True, all values under `key` will be emptied after + `self.reduce()` is called. Setting this to True is useful for cases, + in which the internal values list would otherwise grow indefinitely, + for example if reduce is None and there is no `window` provided. + with_throughput: Whether to track a throughput estimate together with this + metric. This is only supported for `reduce=sum` and + `clear_on_reduce=False` metrics (aka. "lifetime counts"). The `Stats` + object under the logged key then keeps track of the time passed + between two consecutive calls to `reduce()` and update its throughput + estimate. The current throughput estimate of a key can be obtained + through: .peek(key, throughput=True). + throughput_ema_coeff: The EMA coefficient to use for throughput tracking. + Only used if with_throughput=True. Defaults to 0.05. + reduce_per_index_on_aggregate: If True, when merging Stats objects, we reduce + incoming values per index such that the new value at index `n` will be + the reduced value of all incoming values at index `n`. + If False, when reducing `n` Stats, the first `n` merged values will be + the reduced value of all incoming values at index `0`, the next `n` merged + values will be the reduced values of all incoming values at index `1`, etc. + """ + # No reduction (continue appending to list) AND no window. + # -> We'll force-reset our values upon `reduce()`. + if reduce is None and (window is None or window == float("inf")): + clear_on_reduce = True + + # Set default ema_coeff to 0.01 if reduce is "mean" and no window is provided + if reduce == "mean" and window is None and ema_coeff is None: + ema_coeff = 0.01 + + if not self._key_in_stats(key): + self._set_key( + key, + Stats( + init_values=None, + reduce=reduce, + percentiles=percentiles, + window=window, + ema_coeff=ema_coeff, + clear_on_reduce=clear_on_reduce, + throughput=with_throughput, + throughput_ema_coeff=throughput_ema_coeff, + reduce_per_index_on_aggregate=reduce_per_index_on_aggregate, + ), + ) + + # Return the Stats object, so a `with` clause can enter and exit it. + return self._get_key(key) + + def reduce(self) -> Dict: + """Reduces all logged values based on their settings and returns a result dict. + + DO NOT CALL THIS METHOD under normal circumstances! RLlib's components call it + right before a distinct step has been completed and the (MetricsLogger-based) + results of that step need to be passed upstream to other components for further + processing. + + The returned result dict has the exact same structure as the logged keys (or + nested key sequences) combined. Values are Stats objects if this MetricsLogger + is not a root logger. If this MetricsLogger is a root logger, the values are + the actual reduced values. + + For example, imagine component A (e.g. an Algorithm) containing a MetricsLogger + and n remote components (e.g. n EnvRunners), each with their own + MetricsLogger object. Component A calls its n remote components, each of + which returns an equivalent, reduced dict with values at the leafs. + Component A can then further log these n result dicts through its own + MetricsLogger through: + `logger.aggregate([n returned result dicts from n subcomponents])`. + + .. testcode:: + from ray.rllib.utils.metrics.metrics_logger import MetricsLogger + from ray.rllib.utils.test_utils import check + logger = MetricsLogger(root=True) + + # Log some values under different keys. + logger.log_value("loss", 0.1, window=2) + logger.log_value("loss", 0.2, window=2) + logger.log_value("min_loss", 0.3, reduce="min", window=2) + logger.log_value("min_loss", 0.1, reduce="min", window=2) + # reduce() returns the reduced values. + results = logger.reduce() + check(results["loss"], 0.15) # mean of [0.1, 0.2] + check(results["min_loss"], 0.1) # min of [0.3, 0.1] + # We can also reduce a specific key using indexing. + check(logger.reduce()["loss"], 0.15) # mean of [0.1, 0.2] + # Or reduce a nested key structure. + logger.log_value(("nested", "key"), 1.0) + check(logger.reduce()["nested"]["key"], 1.0) + + Returns: + A (nested) dict matching the structure of `self.stats` (contains all ever + logged keys to this MetricsLogger) with the leafs being (reduced) Stats + objects if this MetricsLogger is not a root logger. If this MetricsLogger + is a root logger, the leafs are the actual (reduced) values. + """ + # For better error message, catch the last key-path (reducing of which might + # throw an error). + PATH = None + + def _reduce(path, stats: Stats): + nonlocal PATH + PATH = path + return stats.reduce(compile=self._is_root_logger) + + try: + with self._threading_lock: + reduced_stats_to_return = tree.map_structure_with_path( + _reduce, self.stats + ) + # Provide proper error message if reduction fails due to bad data. + except Exception as e: + raise ValueError( + "There was an error while reducing the Stats object under key=" + f"{PATH}! Check, whether you logged invalid or incompatible " + "values into this key over time in your custom code." + f"\nThe values under this key are: {self._get_key(PATH).values}." + f"\nThe original error was {str(e)}" + ) + + return reduced_stats_to_return + + def activate_tensor_mode(self): + self._tensor_mode = True + + def deactivate_tensor_mode(self): + self._tensor_mode = False + + @property + def tensor_mode(self): + return self._tensor_mode + + def _detach_tensor_if_necessary(self, value): + if self.tensor_mode: + if torch and torch.is_tensor(value): + return value.detach() + elif tf and tf.is_tensor(value): + return tf.stop_gradient(value) + return value + + def set_value( + self, + key: Union[str, Tuple[str, ...]], + value: Any, + *, + reduce: Optional[str] = "mean", + window: Optional[Union[int, float]] = None, + ema_coeff: Optional[float] = None, + percentiles: Union[List[int], bool] = False, + clear_on_reduce: bool = False, + with_throughput: bool = False, + throughput_ema_coeff: float = 0.05, + reduce_per_index_on_aggregate: bool = False, + ) -> None: + """Overrides the logged values under `key` with `value`. + + The internal values list under `key` is cleared and reset to [`value`]. If + `key` already exists, this method will NOT alter the reduce settings. Otherwise, + it will apply the provided reduce settings (`reduce`, `window`, `ema_coeff`, + and `clear_on_reduce`). + + Args: + key: The key to override. + value: The new value to set the internal values list to (will be set to + a list containing a single item `value`). + reduce: The reduction method to apply, once `self.reduce()` is called. + If None, will collect all logged values under `key` in a list (and + also return that list upon calling `self.reduce()`). + Note that this is only applied if `key` does not exist in `self` yet. + window: An optional window size to reduce over. + If not None, then the reduction operation is only applied to the most + recent `window` items, and - after reduction - the internal values list + under `key` is shortened to hold at most `window` items (the most + recent ones). + Must be None if `ema_coeff` is provided. + If None (and `ema_coeff` is None), reduction must not be "mean". + Note that this is only applied if `key` does not exist in `self` yet. + ema_coeff: An optional EMA coefficient to use if `reduce` is "mean" + and no `window` is provided. Note that if both `window` and `ema_coeff` + are provided, an error is thrown. Also, if `ema_coeff` is provided, + `reduce` must be "mean". + The reduction formula for EMA is: + EMA(t1) = (1.0 - ema_coeff) * EMA(t0) + ema_coeff * new_value + Note that this is only applied if `key` does not exist in `self` yet. + percentiles: If reduce is `None`, we can compute the percentiles of the + values list given by `percentiles`. Defaults to [0, 0.5, 0.75, 0.9, 0.95, + 0.99, 1] if set to True. When using percentiles, a window must be provided. + This window should be chosen carefully. RLlib computes exact percentiles and + the computational complexity is O(m*n*log(n/m)) where n is the window size + and m is the number of parallel metrics loggers involved (for example, + m EnvRunners). + clear_on_reduce: If True, all values under `key` will be emptied after + `self.reduce()` is called. Setting this to True is useful for cases, + in which the internal values list would otherwise grow indefinitely, + for example if reduce is None and there is no `window` provided. + Note that this is only applied if `key` does not exist in `self` yet. + with_throughput: Whether to track a throughput estimate together with this + metric. This is only supported for `reduce=sum` and + `clear_on_reduce=False` metrics (aka. "lifetime counts"). The `Stats` + object under the logged key then keeps track of the time passed + between two consecutive calls to `reduce()` and update its throughput + estimate. The current throughput estimate of a key can be obtained + through: peeked_value, throuthput_per_sec = + .peek([key], throughput=True). + throughput_ema_coeff: The EMA coefficient to use for throughput tracking. + Only used if with_throughput=True. Defaults to 0.05. + reduce_per_index_on_aggregate: If True, when merging Stats objects, we reduce + incoming values per index such that the new value at index `n` will be + the reduced value of all incoming values at index `n`. + If False, when reducing `n` Stats, the first `n` merged values will be + the reduced value of all incoming values at index `0`, the next `n` merged + values will be the reduced values of all incoming values at index `1`, etc. + Note that this is only applied if `key` does not exist in `self` yet. + """ + # Key already in self -> Erase internal values list with [`value`]. + if self._key_in_stats(key): + with self._threading_lock: + stats = self._get_key(key) + stats.values = [value] + # Key cannot be found in `self` -> Simply log as a (new) value. + else: + # Set default ema_coeff to 0.01 if reduce is "mean" and no window is provided + if reduce == "mean" and window is None and ema_coeff is None: + ema_coeff = 0.01 + self.log_value( + key, + value, + reduce=reduce, + window=window, + ema_coeff=ema_coeff, + percentiles=percentiles, + clear_on_reduce=clear_on_reduce, + with_throughput=with_throughput, + throughput_ema_coeff=throughput_ema_coeff, + reduce_per_index_on_aggregate=reduce_per_index_on_aggregate, + ) + + def reset(self) -> None: + """Resets all data stored in this MetricsLogger.""" + with self._threading_lock: + self.stats = {} + + def delete(self, *key: Tuple[str, ...], key_error: bool = True) -> None: + """Deletes the given `key` from this metrics logger's stats. + + Args: + key: The key or key sequence (for nested location within self.stats), + to delete from this MetricsLogger's stats. + key_error: Whether to throw a KeyError if `key` cannot be found in `self`. + + Raises: + KeyError: If `key` cannot be found in `self` AND `key_error` is True. + """ + self._del_key(key, key_error) + + def get_state(self) -> Dict[str, Any]: + """Returns the current state of `self` as a dict. + + Note that the state is merely the combination of all states of the individual + `Stats` objects stored under `self.stats`. + """ + stats_dict = {} + + def _map(path, stats): + # Convert keys to strings for msgpack-friendliness. + stats_dict["--".join(path)] = stats.get_state() + + with self._threading_lock: + tree.map_structure_with_path(_map, self.stats) + + return {"stats": stats_dict} + + def set_state(self, state: Dict[str, Any]) -> None: + """Sets the state of `self` to the given `state`. + + Args: + state: The state to set `self` to. + """ + with self._threading_lock: + for flat_key, stats_state in state["stats"].items(): + self._set_key(flat_key.split("--"), Stats.from_state(stats_state)) + + def _key_in_stats(self, flat_key, *, stats=None): + flat_key = force_tuple(tree.flatten(flat_key)) + _dict = stats if stats is not None else self.stats + for key in flat_key: + if key not in _dict: + return False + _dict = _dict[key] + return True + + def _get_key(self, flat_key, *, stats=None, key_error=True): + flat_key = force_tuple(tree.flatten(flat_key)) + _dict = stats if stats is not None else self.stats + for key in flat_key: + try: + _dict = _dict[key] + except KeyError as e: + if key_error: + raise e + else: + return {} + return _dict + + def _set_key(self, flat_key, stats): + flat_key = force_tuple(tree.flatten(flat_key)) + + with self._threading_lock: + _dict = self.stats + for i, key in enumerate(flat_key): + # If we are at the end of the key sequence, set + # the key, no matter, whether it already exists or not. + if i == len(flat_key) - 1: + _dict[key] = stats + return + # If an intermediary key in the sequence is missing, + # add a sub-dict under this key. + if key not in _dict: + _dict[key] = {} + _dict = _dict[key] + + def _del_key(self, flat_key, key_error=False): + flat_key = force_tuple(tree.flatten(flat_key)) + + with self._threading_lock: + # Erase the key from the (nested) `self.stats` dict. + _dict = self.stats + try: + for i, key in enumerate(flat_key): + if i == len(flat_key) - 1: + del _dict[key] + return + _dict = _dict[key] + except KeyError as e: + if key_error: + raise e + + def _get_throughputs( + self, key: Optional[Union[str, Tuple[str, ...]]] = None, default=None + ) -> Union[Dict, float]: + """Returns throughput values for Stats that have throughput tracking enabled. + + If no key is provided, returns a nested dict containing throughput values for all Stats + that have throughput tracking enabled. If a key is provided, returns the throughput value + for that specific key or nested structure. + + The throughput values represent the rate of change of the corresponding metrics per second. + For example, if a metric represents the number of steps taken, its throughput value would + represent steps per second. + + Args: + key: Optional key or nested key path to get throughput for. If provided, returns just + the throughput value for that key or nested structure. If None, returns a nested dict + with throughputs for all metrics. + default: Default value to return if no throughput values are found. + Returns: + If key is None: A nested dict with the same structure as self.stats but with "_throughput" + appended to leaf keys and throughput values as leaf values. Only includes entries for + Stats objects that have throughput tracking enabled. + + If key is provided: The throughput value for that specific key or nested structure. + """ + + def _nested_throughputs(stats): + """Helper function to calculate throughputs for a nested structure.""" + + def _transform(path, value): + if isinstance(value, Stats) and value.has_throughput: + # Convert path to tuple for consistent key handling + key = force_tuple(path) + # Add "_throughput" to the last key in the path + return key[:-1] + (key[-1] + "_throughput",), value.throughput + return path, value + + result = {} + for path, value in tree.flatten_with_path(stats): + new_path, new_value = _transform(path, value) + if isinstance(new_value, float): # Only include throughput values + _dict = result + for k in new_path[:-1]: + if k not in _dict: + _dict[k] = {} + _dict = _dict[k] + _dict[new_path[-1]] = new_value + return result + + with self._threading_lock: + if key is not None: + # Get the Stats object or nested structure for the key + stats = self._get_key(key, key_error=False) + + if isinstance(stats, Stats): + if not stats.has_throughput: + raise ValueError( + f"Key '{key}' does not have throughput tracking enabled" + ) + return stats.throughput + elif stats == {}: + # If the key is not found, return the default value + return default + else: + # stats is a non-empty dictionary + return _nested_throughputs(stats) + + throughputs = {} + + def _map(path, stats): + if isinstance(stats, Stats) and stats.has_throughput: + # Convert path to tuple for consistent key handling + key = force_tuple(path) + # Add "_throughput" to the last key in the path + key = key[:-1] + (key[-1] + "_throughput",) + # Set the throughput value in the nested structure + _dict = throughputs + for k in key[:-1]: + if k not in _dict: + _dict[k] = {} + _dict = _dict[k] + _dict[key[-1]] = stats.throughput + + tree.map_structure_with_path(_map, self.stats) + + return throughputs if throughputs else default + + def compile(self) -> Dict: + """Compiles all current values and throughputs into a single dictionary. + + This method combines the results of all stats and throughputs into a single + dictionary, with throughput values having a "_throughput" suffix. This is useful + for getting a complete snapshot of all metrics and their throughputs in one call. + + Returns: + A nested dictionary containing both the current values and throughputs for all + metrics. The structure matches self.stats, with throughput values having + "_throughput" suffix in their keys. + """ + # Get all current values + values = self.reduce() + + # Get all throughputs + throughputs = self._get_throughputs() + + deep_update(values, throughputs or {}, new_keys_allowed=True) + + def traverse_dict(d): + if isinstance(d, dict): + new_dict = {} + for key, value in d.items(): + new_dict[key] = traverse_dict(value) + return new_dict + elif isinstance(d, list): + if len(d) == 1: + return d[0] + # If value is a longer list, we should just return the list because there is no reduction method applied + return d + else: + # If the value is not a list, it is a single value and we can yield it + return d + + return traverse_dict(values) + + +class _DummyRLock: + def acquire(self, blocking=True, timeout=-1): + return True + + def release(self): + pass + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/stats.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..a764639effdd39899e691607b877fb612c9141cc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/stats.py @@ -0,0 +1,1024 @@ +from collections import defaultdict, deque +import time +import copy +import threading +import heapq +from typing import Any, Dict, List, Union, Optional, Tuple + +import numpy as np + +from ray.rllib.utils import force_list +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.numpy import convert_to_numpy +from ray.util.annotations import DeveloperAPI + +_, tf, _ = try_import_tf() +torch, _ = try_import_torch() + + +@DeveloperAPI +def compute_percentiles(sorted_list, percentiles): + """Compute percentiles from an already sorted list. + + Note that this will not raise an error if the list is not sorted to avoid overhead. + + Args: + sorted_list: A list of numbers sorted in ascending order + percentiles: A list of percentile values (0-100) + + Returns: + A dictionary mapping percentile values to their corresponding data values + """ + n = len(sorted_list) + + if n == 0: + return {p: None for p in percentiles} + + results = {} + + for p in percentiles: + index = (p / 100) * (n - 1) + + if index.is_integer(): + results[p] = sorted_list[int(index)] + else: + lower_index = int(index) + upper_index = lower_index + 1 + weight = index - lower_index + results[p] = ( + sorted_list[lower_index] * (1 - weight) + + sorted_list[upper_index] * weight + ) + + return results + + +@DeveloperAPI +class Stats: + """A container class holding a number of values and executing reductions over them. + + The individual values in a Stats object may be of any type, for example python int + or float, numpy arrays, or more complex structured (tuple, dict) and are stored in + a list under `self.values`. This class is not meant to be interfaced with directly + from application code. Instead, use `MetricsLogger` to log and manipulate Stats. + + Stats can be used to store metrics of the same type over time, for example a loss + or a learning rate, and to reduce all stored values applying a certain reduction + mechanism (for example "mean" or "sum"). + + Available reduction mechanisms are: + - "mean" using EMA with a configurable EMA coefficient. + - "mean" using a sliding window (over the last n stored values). + - "max/min" with an optional sliding window (over the last n stored values). + - "sum" with an optional sliding window (over the last n stored values). + - None: Simply store all logged values to an ever-growing list. + + Through the `reduce()` API, one of the above-mentioned reduction mechanisms will + be executed on `self.values`. + """ + + def __init__( + self, + init_values: Optional[Any] = None, + reduce: Optional[str] = "mean", + percentiles: Union[List[int], bool] = False, + reduce_per_index_on_aggregate: bool = False, + window: Optional[Union[int, float]] = None, + ema_coeff: Optional[float] = None, + clear_on_reduce: bool = False, + throughput: Union[bool, float] = False, + throughput_ema_coeff: Optional[float] = None, + ): + """Initializes a Stats instance. + + Args: + init_values: Optional initial values to be placed into `self.values`. If None, + `self.values` will start empty. If percentiles is True, values must be ordered + if provided. + reduce: The name of the reduce method to be used. Allowed are "mean", "min", + "max", and "sum". Use None to apply no reduction method (leave + `self.values` as-is when reducing, except for shortening it to + `window`). Note that if both `reduce` and `window` are None, the user of + this Stats object needs to apply some caution over the values list not + growing infinitely. + percentiles: If reduce is `None`, we can compute the percentiles of the + values list given by `percentiles`. Defaults to [0, 50, 75, 90, 95, + 99, 100] if set to True. When using percentiles, a window must be provided. + This window should be chosen carfully. RLlib computes exact percentiles and + the computational complexity is O(m*n*log(n/m)) where n is the window size + and m is the number of parallel metrics loggers invovled (for example, + m EnvRunners). To be safe, choose a window < 1M and less than 1000 Stats + objects to aggregate. See #52963 for more details. + window: An optional window size to reduce over. + If `window` is not None, then the reduction operation is only applied to + the most recent `windows` items, and - after reduction - the values list + is shortened to hold at most `window` items (the most recent ones). + Must be None if `ema_coeff` is not None. + If `window` is None (and `ema_coeff` is None), reduction must not be + "mean". + reduce_per_index_on_aggregate: If True, when merging Stats objects, we reduce + incoming values per index such that the new value at index `n` will be + the reduced value of all incoming values at index `n`. + If False, when reducing `n` Stats, the first `n` merged values will be + the reduced value of all incoming values at index `0`, the next `n` merged + values will be the reduced values of all incoming values at index `1`, etc. + ema_coeff: An optional EMA coefficient to use if reduce is "mean" + and no `window` is provided. Note that if both `window` and `ema_coeff` + are provided, an error is thrown. Also, if `ema_coeff` is provided, + `reduce` must be "mean". + The reduction formula for EMA performed by Stats is: + EMA(t1) = (1.0 - ema_coeff) * EMA(t0) + ema_coeff * new_value + clear_on_reduce: If True, the Stats object will reset its entire values list + to an empty one after `self.reduce()` is called. However, it will then + return from the `self.reduce()` call a new Stats object with the + properly reduced (not completely emptied) new values. Setting this + to True is useful for cases, in which the internal values list would + otherwise grow indefinitely, for example if reduce is None and there + is no `window` provided. + throughput: If True, track a throughput estimate together with this + Stats. This is only supported for `reduce=sum` and + `clear_on_reduce=False` metrics (aka. "lifetime counts"). The `Stats` + then keeps track of the time passed between two consecutive calls to + `reduce()` and update its throughput estimate. The current throughput + estimate can be obtained through: + `throughput_per_sec = Stats.peek(throughput=True)`. + If a float, track throughput and also set current throughput estimate + to the given value. + throughput_ema_coeff: An optional EMA coefficient to use for throughput tracking. + Only used if throughput=True. + """ + # Thus far, we only support mean, max, min, and sum. + if reduce not in [None, "mean", "min", "max", "sum", "percentiles"]: + raise ValueError( + "`reduce` must be one of `mean|min|max|sum|percentiles` or None!" + ) + + # One or both window and ema_coeff must be None. + if window is not None and ema_coeff is not None: + raise ValueError("Only one of `window` or `ema_coeff` can be specified!") + # If `ema_coeff` is provided, `reduce` must be "mean". + if ema_coeff is not None and reduce != "mean": + raise ValueError( + "`ema_coeff` arg only allowed (not None) when `reduce=mean`!" + ) + + if percentiles is not False: + if reduce is not None: + raise ValueError( + "`reduce` must be `None` when `percentiles` is not `False`!" + ) + if window in (None, float("inf")): + raise ValueError( + "A window must be specified when reduce is 'percentiles'!" + ) + if reduce_per_index_on_aggregate is not False: + print(reduce_per_index_on_aggregate) + raise ValueError( + "`reduce_per_index_on_aggregate` must be `False` when `percentiles` is not `False`!" + ) + + if percentiles is True: + percentiles = [0, 50, 75, 90, 95, 99, 100] + else: + if type(percentiles) not in (bool, list): + raise ValueError("`percentiles` must be a list or bool!") + if isinstance(percentiles, list): + if not all(isinstance(p, (int, float)) for p in percentiles): + raise ValueError( + "`percentiles` must contain only ints or floats!" + ) + if not all(0 <= p <= 100 for p in percentiles): + raise ValueError( + "`percentiles` must contain only values between 0 and 100!" + ) + + self._percentiles = percentiles + + # If `window` is explicitly set to inf, `clear_on_reduce` must be True. + self._inf_window = window in [None, float("inf")] + + # If `window` is set to inf, `clear_on_reduce` must be True. + # Otherwise, we risk a memory leak. + if self._inf_window and not clear_on_reduce and reduce is None: + raise ValueError( + "When using an infinite window without reduction, `clear_on_reduce` must " + "be set to True!" + ) + + # If reduce=mean AND window=ema_coeff=None, we use EMA by default with a coeff + # of 0.01 (we do NOT support infinite window sizes for mean as that would mean + # to keep data in the cache forever). + if reduce == "mean" and self._inf_window and ema_coeff is None: + ema_coeff = 0.01 + + self._reduce_method = reduce + self._window = window + self._ema_coeff = ema_coeff + + if ( + self._reduce_method not in ["mean", "sum", "min", "max"] + and reduce_per_index_on_aggregate + ): + raise ValueError( + "reduce_per_index_on_aggregate is only supported for mean, sum, min, and max reduction!" + ) + + self._reduce_per_index_on_aggregate = reduce_per_index_on_aggregate + + # Timing functionality (keep start times per thread). + self._start_times = defaultdict(lambda: None) + + # Simply store ths flag for the user of this class. + self._clear_on_reduce = clear_on_reduce + + self._has_returned_zero = False + + # On each `.reduce()` call, we store the result of this call in + # reduce_history[0] and the previous `reduce()` result in reduce_history[1]. + self._reduce_history: deque[List[Any]] = deque( + [[np.nan], [np.nan], [np.nan]], maxlen=3 + ) + + self._throughput_ema_coeff = throughput_ema_coeff + self._throughput_stats = None + if throughput is not False: + self._throughput_stats = Stats( + # We have to check for bool here because in Python, bool is a subclass of int + init_values=[throughput] + if ( + isinstance(throughput, (int, float)) + and not isinstance(throughput, bool) + ) + else None, + reduce="mean", + ema_coeff=throughput_ema_coeff, + window=None, + clear_on_reduce=False, + throughput=False, + throughput_ema_coeff=None, + ) + if init_values is not None: + self._last_push_time = time.perf_counter() + else: + self._last_push_time = ( + -1 + ) # Track last push time for throughput calculation + + # The actual, underlying data in this Stats object. + self.values: Union[List, deque.Deque] = None + self._set_values(force_list(init_values)) + + self._is_tensor = False + + # Track if new values were pushed since last reduce + if init_values is not None: + self._has_new_values = True + else: + self._has_new_values = False + + def check_value(self, value: Any) -> None: + # If we have a reduce method, value should always be a scalar + # If we don't reduce, we can keep track of value as it is + if self._reduce_method is not None: + if isinstance(value, np.ndarray) and value.shape == (): + return + elif (torch and torch.is_tensor(value)) or (tf and tf.is_tensor(value)): + self._is_tensor = True + if tuple(value.shape) == (): + return + elif type(value) not in (list, tuple, deque): + return + raise ValueError( + f"Value ({value}) is required to be a scalar when using a reduce " + "method!" + ) + + def push(self, value: Any) -> None: + """Pushes a value into this Stats object. + + Args: + value: The value to be pushed. Can be of any type. + """ + self.check_value(value) + # If throughput tracking is enabled, calculate it based on time between pushes + if self.has_throughput: + current_time = time.perf_counter() + if self._last_push_time >= 0: + time_diff = current_time - self._last_push_time + if time_diff > 0: # Avoid division by zero + current_throughput = value / time_diff + self._throughput_stats.push(current_throughput) + self._last_push_time = current_time + + # Handle different reduction methods + if self._window is not None: + # For windowed operations, append to values and trim if needed + self.values.append(value) + if len(self.values) > self._window: + self.values.popleft() + else: + # For non-windowed operations, use _reduced_values + if len(self.values) == 0: + self._set_values([value]) + else: + self.values.append(value) + _, values = self._reduced_values() + self._set_values(values) + + # Mark that we have new values + self._has_new_values = True + + def __enter__(self) -> "Stats": + """Called when entering a context (with which users can measure a time delta). + + Returns: + This Stats instance (self), unless another thread has already entered (and + not exited yet), in which case a copy of `self` is returned. This way, the + second thread(s) cannot mess with the original Stat's (self) time-measuring. + This also means that only the first thread to __enter__ actually logs into + `self` and the following threads' measurements are discarded (logged into + a non-referenced shim-Stats object, which will simply be garbage collected). + """ + # In case another thread already is measuring this Stats (timing), simply ignore + # the "enter request" and return a clone of `self`. + thread_id = threading.get_ident() + self._start_times[thread_id] = time.perf_counter() + return self + + def __exit__(self, exc_type, exc_value, tb) -> None: + """Called when exiting a context (with which users can measure a time delta).""" + thread_id = threading.get_ident() + assert self._start_times[thread_id] is not None + time_delta_s = time.perf_counter() - self._start_times[thread_id] + self.push(time_delta_s) + + del self._start_times[thread_id] + + def peek(self, compile: bool = True) -> Union[Any, List[Any]]: + """Returns the result of reducing the internal values list. + + Note that this method does NOT alter the internal values list in this process. + Thus, users can call this method to get an accurate look at the reduced value(s) + given the current internal values list. + + Args: + compile: If True, the result is compiled into a single value if possible. + + Returns: + The result of reducing the internal values list. + """ + if self._has_new_values or (not compile and not self._inf_window): + reduced_value, reduced_values = self._reduced_values() + if not compile and not self._inf_window: + return reduced_values + if compile and self._reduce_method: + return reduced_value[0] + if compile and self._percentiles is not False: + return compute_percentiles(reduced_values, self._percentiles) + return reduced_value + else: + return_value = self.get_reduce_history()[-1].copy() + if compile: + # We don't need to check for self._reduce_method or percentiles here + # because we only store the reduced value if there is a reduce method. + return_value = return_value[0] + return return_value + + def get_reduce_history(self) -> List[Any]: + """Returns the history of reduced values as a list. + + The history contains the most recent reduced values, with the most recent value + at the end of the list. The length of the history is limited by the maxlen of + the internal history deque. + + Returns: + A list containing the history of reduced values. + """ + # Turning the reduce history into a deque avoids mutating the original reduce + # history's elements. + return list(self._reduce_history) + + @property + def throughput(self) -> float: + """Returns the current throughput estimate per second. + + Raises: + ValueError: If throughput tracking is not enabled for this Stats object. + + Returns: + The current throughput estimate per second. + """ + if not self.has_throughput: + raise ValueError("Throughput tracking is not enabled for this Stats object") + # We can always return the first value here because throughput is a single value + return self._throughput_stats.peek() + + @property + def has_throughput(self) -> bool: + """Returns whether this Stats object tracks throughput. + + Returns: + True if this Stats object has throughput tracking enabled, False otherwise. + """ + return self._throughput_stats is not None + + def reduce(self, compile: bool = True) -> Union[Any, List[Any]]: + """Reduces the internal values list according to the constructor settings. + + Thereby, the internal values list is changed (note that this is different from + `peek()`, where the internal list is NOT changed). See the docstring of this + class for details on the reduction logic applied to the values list, based on + the constructor settings, such as `window`, `reduce`, etc.. + + Args: + compile: If True, the result is compiled into a single value if possible. + If it is not possible, the result is a list of values. + If False, the result is a list of one or more values. + + Returns: + The reduced value (can be of any type, depending on the input values and + reduction method). + """ + len_before_reduce = len(self) + if self._has_new_values: + # Only calculate and update history if there were new values pushed since + # last reduce + reduced, reduced_internal_values_list = self._reduced_values() + # `clear_on_reduce` -> Clear the values list. + if self._clear_on_reduce: + self._set_values([]) + # If we clear on reduce, following reduce calls should not return the + # old values. + self._has_new_values = True + else: + self._has_new_values = False + self._set_values(reduced_internal_values_list) + else: + reduced_internal_values_list = None + reduced = self.get_reduce_history()[-1] + + reduced = self._numpy_if_necessary(reduced) + + # Shift historic reduced valued by one in our reduce_history. + if self._reduce_method is not None: + # It only makes sense to extend the history if we are reducing to a single + # value. We need to make a copy here because the new_values_list is a + # reference to the internal values list + self._reduce_history.append(force_list(reduced.copy())) + else: + # If there is a window and no reduce method, we don't want to use the reduce + # history to return reduced values in other methods + self._has_new_values = True + + if compile and self._reduce_method is not None: + assert ( + len(reduced) == 1 + ), f"Reduced values list must contain exactly one value, found {reduced}" + reduced = reduced[0] + + if not compile and not self._inf_window: + if reduced_internal_values_list is None: + _, reduced_internal_values_list = self._reduced_values() + return_values = self._numpy_if_necessary( + reduced_internal_values_list + ).copy() + elif compile and self._percentiles is not False: + if reduced_internal_values_list is None: + _, reduced_internal_values_list = self._reduced_values() + return_values = compute_percentiles( + reduced_internal_values_list, self._percentiles + ) + else: + return_values = reduced + + if compile: + return return_values + else: + if len_before_reduce == 0: + # return_values will be be 0 if we reduce a sum over zero elements + # But we don't want to create such a zero out of nothing for our new + # Stats object that we return here + return Stats.similar_to(self) + + return Stats.similar_to(self, init_values=return_values) + + def merge_on_time_axis(self, other: "Stats") -> None: + """Merges another Stats object's values into this one along the time axis. + + Args: + other: The other Stats object to merge values from. + """ + self.values.extend(other.values) + + # Adopt `other`'s current throughput estimate (it's the newer one). + if self.has_throughput: + self._throughput_stats.merge_on_time_axis(other._throughput_stats) + + # Mark that we have new values since we modified the values list + self._has_new_values = True + + def merge_in_parallel(self, *others: "Stats") -> None: + """Merges all internal values of `others` into `self`'s internal values list. + + Thereby, the newly incoming values of `others` are treated equally with respect + to each other as well as with respect to the internal values of self. + + Use this method to merge other `Stats` objects, which resulted from some + parallelly executed components, into this one. For example: n Learner workers + all returning a loss value in the form of `{"total_loss": [some value]}`. + + The following examples demonstrate the parallel merging logic for different + reduce- and window settings: + + Args: + others: One or more other Stats objects that need to be parallely merged + into `self, meaning with equal weighting as the existing values in + `self`. + """ + win = self._window or float("inf") + + # If any of the value lists have a length of 0 or if there is only one value and + # it is nan, we skip + stats_to_merge = [ + s + for s in [self, *others] + if not ( + len(s) == 0 + or ( + len(s) == 1 and np.all(np.isnan(self._numpy_if_necessary(s.values))) + ) + ) + ] + + # If there is only one stat to merge, and it is the same as self, return. + if len(stats_to_merge) == 0: + # If none of the stats have values, return. + return + elif len(stats_to_merge) == 1: + if stats_to_merge[0] == self: + # If no incoming stats have values, return. + return + else: + # If there is only one stat with values, and it's incoming, copy its + # values. + self.values = stats_to_merge[0].values + return + + # Take turns stepping through `self` and `*others` values, thereby moving + # backwards from last index to beginning and will up the resulting values list. + # Stop as soon as we reach the window size. + new_values = [] + tmp_values = [] + + if self._percentiles is not False: + # Use heapq to sort values (assumes that the values are already sorted) + # and then pick the correct percentiles + lists_to_merge = [list(self.values), *[list(o.values) for o in others]] + merged = list(heapq.merge(*lists_to_merge)) + self._set_values(merged) + else: + # Loop from index=-1 backward to index=start until our new_values list has + # at least a len of `win`. + for i in range(1, max(map(len, stats_to_merge)) + 1): + # Per index, loop through all involved stats, including `self` and add + # to `tmp_values`. + for stats in stats_to_merge: + if len(stats) < i: + continue + tmp_values.append(stats.values[-i]) + + # Now reduce across `tmp_values` based on the reduce-settings of this Stats. + # TODO (sven) : explain why all this + + if self._reduce_per_index_on_aggregate: + n_values = 1 + else: + n_values = len(tmp_values) + + if self._ema_coeff is not None: + new_values.extend([np.nanmean(tmp_values)] * n_values) + elif self._reduce_method is None: + new_values.extend(tmp_values) + elif self._reduce_method == "sum": + # We add [sum(tmp_values) / n_values] * n_values to the new values + # list instead of tmp_values, because every incoming element should + # have the same weight. + reduced_value = ( + self._reduced_values(values=tmp_values)[0][0] / n_values + ) + new_values.extend([reduced_value] * n_values) + else: + new_values.extend( + self._reduced_values(values=tmp_values)[0] * n_values + ) + + tmp_values.clear() + if len(new_values) >= win: + new_values = new_values[:win] + break + + self._set_values(list(reversed(new_values))) + + # Adopt `other`'s current throughput estimate (it's the newer one). + if self.has_throughput: + other_throughput_stats = [ + other._throughput_stats for other in others if other.has_throughput + ] + self._throughput_stats.merge_in_parallel(*other_throughput_stats) + + # Mark that we have new values since we modified the values list + self._has_new_values = True + + @staticmethod + def _numpy_if_necessary(values): + # Torch tensor handling. Convert to CPU/numpy first. + if torch and len(values) > 0 and torch.is_tensor(values[0]): + # Convert all tensors to numpy values. + values = [v.cpu().numpy() for v in values] + return values + + def __len__(self) -> int: + """Returns the length of the internal values list.""" + return len(self.values) + + def __repr__(self) -> str: + win_or_ema = ( + f"; win={self._window}" + if self._window + else f"; ema={self._ema_coeff}" + if self._ema_coeff + else "" + ) + return ( + f"Stats({self.peek()}; len={len(self)}; " + f"reduce={self._reduce_method}{win_or_ema})" + ) + + def __int__(self): + if self._reduce_method is None: + raise ValueError( + "Cannot convert Stats object with reduce method `None` to int because " + "it can not be reduced to a single value." + ) + else: + return int(self.peek()) + + def __float__(self): + if self._reduce_method is None: + raise ValueError( + "Cannot convert Stats object with reduce method `None` to float " + "because it can not be reduced to a single value." + ) + else: + return float(self.peek()) + + def __eq__(self, other): + if self._reduce_method is None: + self._comp_error("__eq__") + else: + return float(self) == float(other) + + def __le__(self, other): + if self._reduce_method is None: + self._comp_error("__le__") + else: + return float(self) <= float(other) + + def __ge__(self, other): + if self._reduce_method is None: + self._comp_error("__ge__") + else: + return float(self) >= float(other) + + def __lt__(self, other): + if self._reduce_method is None: + self._comp_error("__lt__") + else: + return float(self) < float(other) + + def __gt__(self, other): + if self._reduce_method is None: + self._comp_error("__gt__") + else: + return float(self) > float(other) + + def __add__(self, other): + if self._reduce_method is None: + self._comp_error("__add__") + else: + return float(self) + float(other) + + def __sub__(self, other): + if self._reduce_method is None: + self._comp_error("__sub__") + else: + return float(self) - float(other) + + def __mul__(self, other): + if self._reduce_method is None: + self._comp_error("__mul__") + else: + return float(self) * float(other) + + def __format__(self, fmt): + if self._reduce_method is None: + raise ValueError( + "Cannot format Stats object with reduce method `None` because it can " + "not be reduced to a single value." + ) + else: + return f"{float(self):{fmt}}" + + def _comp_error(self, comp): + raise ValueError( + f"Cannot {comp} Stats object with reduce method `None` to other " + "because it can not be reduced to a single value." + ) + + def get_state(self) -> Dict[str, Any]: + state = { + # Make sure we don't return any tensors here. + "values": convert_to_numpy(self.values), + "reduce": self._reduce_method, + "percentiles": self._percentiles, + "reduce_per_index_on_aggregate": self._reduce_per_index_on_aggregate, + "window": self._window, + "ema_coeff": self._ema_coeff, + "clear_on_reduce": self._clear_on_reduce, + "_hist": list(self.get_reduce_history()), + "_is_tensor": self._is_tensor, + } + if self._throughput_stats is not None: + state["throughput_stats"] = self._throughput_stats.get_state() + return state + + @staticmethod + def from_state(state: Dict[str, Any]) -> "Stats": + # If `values` could contain tensors, don't reinstate them (b/c we don't know + # whether we are on a supported device). + values = state["values"] + if "_is_tensor" in state and state["_is_tensor"]: + values = [] + + if "throughput_stats" in state: + throughput_stats = Stats.from_state(state["throughput_stats"]) + stats = Stats( + values, + reduce=state["reduce"], + percentiles=state.get("percentiles", False), + reduce_per_index_on_aggregate=state.get( + "reduce_per_index_on_aggregate", False + ), + window=state["window"], + ema_coeff=state["ema_coeff"], + clear_on_reduce=state["clear_on_reduce"], + throughput=throughput_stats.peek(), + throughput_ema_coeff=throughput_stats._ema_coeff, + ) + elif state.get("_throughput", False): + # Older checkpoints have a _throughput key that is boolean or + # a float (throughput value). They don't have a throughput_ema_coeff + # so we use a default of 0.05. + # TODO(Artur): Remove this after a few Ray releases. + stats = Stats( + values, + reduce=state["reduce"], + percentiles=state.get("percentiles", False), + window=state["window"], + ema_coeff=state["ema_coeff"], + clear_on_reduce=state["clear_on_reduce"], + throughput=state["_throughput"], + throughput_ema_coeff=0.05, + ) + else: + stats = Stats( + values, + reduce=state["reduce"], + percentiles=state.get("percentiles", False), + window=state["window"], + ema_coeff=state["ema_coeff"], + clear_on_reduce=state["clear_on_reduce"], + throughput=False, + throughput_ema_coeff=None, + ) + # Compatibility to old checkpoints where a reduce sometimes resulted in a single + # values instead of a list such that the history would be a list of integers + # instead of a list of lists. + # TODO(Artur): Remove this after a few Ray releases. + if not isinstance(state["_hist"][0], list): + state["_hist"] = list(map(lambda x: [x], state["_hist"])) + + stats._reduce_history = deque( + state["_hist"], maxlen=stats._reduce_history.maxlen + ) + return stats + + @staticmethod + def similar_to( + other: "Stats", + init_values: Optional[Any] = None, + ) -> "Stats": + """Returns a new Stats object that's similar to `other`. + + "Similar" here means it has the exact same settings (reduce, window, ema_coeff, + etc..). The initial values of the returned `Stats` are empty by default, but + can be set as well. + + Args: + other: The other Stats object to return a similar new Stats equivalent for. + init_value: The initial value to already push into the returned Stats. + + Returns: + A new Stats object similar to `other`, with the exact same settings and + maybe a custom initial value (if provided; otherwise empty). + """ + stats = Stats( + init_values=init_values, + reduce=other._reduce_method, + percentiles=other._percentiles, + reduce_per_index_on_aggregate=other._reduce_per_index_on_aggregate, + window=other._window, + ema_coeff=other._ema_coeff, + clear_on_reduce=other._clear_on_reduce, + throughput=other._throughput_stats.peek() + if other.has_throughput + else False, + throughput_ema_coeff=other._throughput_ema_coeff, + ) + stats._reduce_history = other._reduce_history + return stats + + def _set_values(self, new_values): + # For stats with window, use a deque with maxlen=window. + # This way, we never store more values than absolutely necessary. + if not self._inf_window: + self.values = deque(new_values, maxlen=self._window) + # For infinite windows, use `new_values` as-is (a list). + else: + self.values = new_values + + self._has_new_values = True + + def _reduced_values(self, values=None) -> Tuple[Any, Any]: + """Runs a non-committed reduction procedure on given values (or `self.values`). + + Note that this method does NOT alter any state of `self` or the possibly + provided list of `values`. It only returns new values as they should be + adopted after a possible, actual reduction step. + + Args: + values: The list of values to reduce. If not None, use `self.values` + + Returns: + A tuple containing 1) the reduced values and 2) the new internal values list + to be used. If there is no reduciton method, the reduced values will be the same as the values. + """ + values = values if values is not None else self.values + + # No reduction method. Return list as-is OR reduce list to len=window. + if self._reduce_method is None: + if self._percentiles is not False: + # Sort values + values = list(values) + # (Artur): Numpy can sort faster than Python's built-in sort for large lists. Howoever, if we convert to an array here + # and then sort, this only slightly (<2x) improved the runtime of this method, even for an internal values list of 1M values. + values.sort() + return values, values + + # Special case: Internal values list is empty -> return NaN or 0.0 for sum. + elif len(values) == 0: + if self._reduce_method in ["min", "max", "mean"] or self._has_returned_zero: + # We also return np.nan if we have returned zero before. + # This helps with cases where stats are cleared on reduce, but we don't want to log 0's, except for the first time. + return [np.nan], [] + else: + return [0], [] + + # Do EMA (always a "mean" reduction; possibly using a window). + elif self._ema_coeff is not None: + # Perform EMA reduction over all values in internal values list. + mean_value = values[0] + for v in values[1:]: + mean_value = self._ema_coeff * v + (1.0 - self._ema_coeff) * mean_value + if self._inf_window: + return [mean_value], [mean_value] + else: + return [mean_value], values + # Non-EMA reduction (possibly using a window). + else: + # Use the numpy/torch "nan"-prefix to ignore NaN's in our value lists. + if torch and torch.is_tensor(values[0]): + self._is_tensor = True + # Only one item in the + if len(values[0].shape) == 0: + reduced = values[0] + else: + reduce_meth = getattr(torch, "nan" + self._reduce_method) + reduce_in = torch.stack(list(values)) + if self._reduce_method == "mean": + reduce_in = reduce_in.float() + reduced = reduce_meth(reduce_in) + else: + reduce_meth = getattr(np, "nan" + self._reduce_method) + + if np.all(np.isnan(values)): + # This avoids warnings for taking a mean of an empty array. + reduced = np.nan + else: + reduced = reduce_meth(values) + + def safe_isnan(value): + if torch and isinstance(value, torch.Tensor): + return torch.isnan(value) + if tf and tf.is_tensor(value): + return tf.math.is_nan(value) + return np.isnan(value) + + # Convert from numpy to primitive python types, if original `values` are + # python types. + if ( + not safe_isnan(reduced) + and reduced.shape == () + and isinstance(values[0], (int, float)) + ): + if reduced.dtype in [np.int32, np.int64, np.int8, np.int16]: + reduced = int(reduced) + else: + reduced = float(reduced) + + # For window=None|inf (infinite window) and reduce != mean, we don't have to + # keep any values, except the last (reduced) one. + if self._inf_window and self._reduce_method != "mean": + # TODO (sven): What if values are torch tensors? In this case, we + # would have to do reduction using `torch` above (not numpy) and only + # then return the python primitive AND put the reduced new torch + # tensor in the new `self.values`. + return [reduced], [reduced] + else: + # In all other cases, keep the values that were also used for the reduce + # operation. + return [reduced], values + + +@DeveloperAPI +def merge_stats(base_stats: Optional[Stats], incoming_stats: List[Stats]) -> Stats: + """Merges Stats objects. + + If `base_stats` is None, we use the first incoming Stats object as the new base Stats object. + If `base_stats` is not None, we merge all incoming Stats objects into the base Stats object. + + Args: + base_stats: The base Stats object to merge into. + incoming_stats: The list of Stats objects to merge. + + Returns: + The merged Stats object. + """ + if base_stats is None: + new_root_stats = True + else: + new_root_stats = False + + if new_root_stats: + # We need to deepcopy here first because stats from incoming_stats may be altered in the future + base_stats = copy.deepcopy(incoming_stats[0]) + elif len(incoming_stats) > 0: + # Special case: `base_stats` is a lifetime sum (reduce=sum, + # clear_on_reduce=False) -> We subtract the previous value (from 2 + # `reduce()` calls ago) from all to-be-merged stats, so we don't count + # twice the older sum from before. + if ( + base_stats._reduce_method == "sum" + and base_stats._inf_window + and base_stats._clear_on_reduce is False + ): + for stat in incoming_stats: + reduce_by = stat.get_reduce_history()[-2][0] + base_stats.values[-1] -= reduce_by + else: + # Nothing to be merged + return base_stats + + if new_root_stats: + # Note that we may take a mean of means here, which is not the same as a + # mean of all values. In the future, we could implement a weighted mean + # of means here by introducing a new Stats object that counts samples + # for each mean Stats object. + if len(incoming_stats) > 1: + base_stats.merge_in_parallel(*incoming_stats[1:]) + elif len(incoming_stats) > 0: + if len(incoming_stats) > 1: + # There are more than one incoming parallel others -> Merge all of + # them in parallel (equal importance). + incoming_stats[0].merge_in_parallel(*incoming_stats[1:]) + + # Merge incoming Stats object into base Stats object on time axis + # (giving incoming ones priority). + if base_stats._reduce_method == "mean" and not base_stats._clear_on_reduce: + # If we don't clear values, values that are not cleared would contribute + # to the mean multiple times. + base_stats._set_values(incoming_stats[0].values.copy()) + else: + base_stats.merge_on_time_axis(incoming_stats[0]) + + return base_stats diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f14fa8e1e12aa623b34642d73626a25509f9379d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/utils.py @@ -0,0 +1,20 @@ +import re + + +def to_snake_case(class_name: str) -> str: + """Converts class name to snake case. + + This is used to unify metrics names when using class names within. + Args: + class_name: A string defining a class name usually in camel + case. + + Returns: + The class name in snake case. + """ + # Insert _ between a lower- or digit-char and an upper-char + name = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", class_name) + # Insert _ between an upper-char followed by upper+lower (to split + # "ABCReward" into "abc_reward") + name = re.sub(r"(?<=[A-Z])(?=[A-Z][a-z])", "_", name) + return name.lower() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/window_stat.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/window_stat.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea4fe35c956d83ab5cb26a174e2c25af62d148d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/metrics/window_stat.py @@ -0,0 +1,79 @@ +import numpy as np + +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class WindowStat: + """Handles/stores incoming dataset and provides window-based statistics. + + .. testcode:: + :skipif: True + + win_stats = WindowStat("level", 3) + win_stats.push(5.0) + win_stats.push(7.0) + win_stats.push(7.0) + win_stats.push(10.0) + # Expect 8.0 as the mean of the last 3 values: (7+7+10)/3=8.0 + print(win_stats.mean()) + + .. testoutput:: + + 8.0 + """ + + def __init__(self, name: str, n: int): + """Initializes a WindowStat instance. + + Args: + name: The name of the stats to collect and return stats for. + n: The window size. Statistics will be computed for the last n + items received from the stream. + """ + # The window-size. + self.window_size = n + # The name of the data (used for `self.stats()`). + self.name = name + # List of items to do calculations over (len=self.n). + self.items = [None] * self.window_size + # The current index to insert the next item into `self.items`. + self.idx = 0 + # How many items have been added over the lifetime of this object. + self.count = 0 + + def push(self, obj) -> None: + """Pushes a new value/object into the data buffer.""" + # Insert object at current index. + self.items[self.idx] = obj + # Increase insertion index by 1. + self.idx += 1 + # Increase lifetime count by 1. + self.count += 1 + # Fix index in case of rollover. + self.idx %= len(self.items) + + def mean(self) -> float: + """Returns the (NaN-)mean of the last `self.window_size` items.""" + return float(np.nanmean(self.items[: self.count])) + + def std(self) -> float: + """Returns the (NaN)-stddev of the last `self.window_size` items.""" + return float(np.nanstd(self.items[: self.count])) + + def quantiles(self) -> np.ndarray: + """Returns ndarray with 0, 10, 50, 90, and 100 percentiles.""" + if not self.count: + return np.ndarray([], dtype=np.float32) + else: + return np.nanpercentile( + self.items[: self.count], [0, 10, 50, 90, 100] + ).tolist() + + def stats(self): + return { + self.name + "_count": int(self.count), + self.name + "_mean": self.mean(), + self.name + "_std": self.std(), + self.name + "_quantiles": self.quantiles(), + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..053d4b8c985ca34bafd9659d5a7409aa11cb1fbc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/episodes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/episodes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9db031c787c7e762d3903b50e017ec52118de7b4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/episodes.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/value_predictions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/value_predictions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f5952133f13e43367b1dd2fc62f08052d6b4109 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/value_predictions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/zero_padding.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/zero_padding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72dc6a20075bc7e34f4a894a35f054d300a5e6b5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/__pycache__/zero_padding.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/episodes.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/episodes.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc5b1321659366372b985116ad3cddcf8b2f899 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/episodes.py @@ -0,0 +1,144 @@ +from typing import List, Tuple + +import numpy as np + +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +def add_one_ts_to_episodes_and_truncate(episodes: List[SingleAgentEpisode]): + """Adds an artificial timestep to an episode at the end. + + In detail: The last observations, infos, actions, and all `extra_model_outputs` + will be duplicated and appended to each episode's data. An extra 0.0 reward + will be appended to the episode's rewards. The episode's timestep will be + increased by 1. Also, adds the truncated=True flag to each episode if the + episode is not already done (terminated or truncated). + + Useful for value function bootstrapping, where it is required to compute a + forward pass for the very last timestep within the episode, + i.e. using the following input dict: { + obs=[final obs], + state=[final state output], + prev. reward=[final reward], + etc.. + } + + Args: + episodes: The list of SingleAgentEpisode objects to extend by one timestep + and add a truncation flag if necessary. + + Returns: + A list of the original episodes' truncated values (so the episodes can be + properly restored later into their original states). + """ + orig_truncateds = [] + for episode in episodes: + orig_truncateds.append(episode.is_truncated) + + # Add timestep. + episode.t += 1 + # Use the episode API that allows appending (possibly complex) structs + # to the data. + episode.observations.append(episode.observations[-1]) + episode.infos.append(episode.infos[-1]) + episode.actions.append(episode.actions[-1]) + episode.rewards.append(0.0) + for v in episode.extra_model_outputs.values(): + v.append(v[-1]) + # Artificially make this episode truncated for the upcoming GAE + # computations. + if not episode.is_done: + episode.is_truncated = True + # Validate to make sure, everything is in order. + episode.validate() + + return orig_truncateds + + +@DeveloperAPI +def remove_last_ts_from_data( + episode_lens: List[int], + *data: Tuple[np._typing.NDArray], +) -> Tuple[np._typing.NDArray]: + """Removes the last timesteps from each given data item. + + Each item in data is a concatenated sequence of episodes data. + For example if `episode_lens` is [2, 4], then data is a shape=(6,) + ndarray. The returned corresponding value will have shape (4,), meaning + both episodes have been shortened by exactly one timestep to 1 and 3. + + ..testcode:: + + from ray.rllib.algorithms.ppo.ppo_learner import PPOLearner + import numpy as np + + unpadded = PPOLearner._remove_last_ts_from_data( + [5, 3], + np.array([0, 1, 2, 3, 4, 0, 1, 2]), + ) + assert (unpadded[0] == [0, 1, 2, 3, 0, 1]).all() + + unpadded = PPOLearner._remove_last_ts_from_data( + [4, 2, 3], + np.array([0, 1, 2, 3, 0, 1, 0, 1, 2]), + np.array([4, 5, 6, 7, 2, 3, 3, 4, 5]), + ) + assert (unpadded[0] == [0, 1, 2, 0, 0, 1]).all() + assert (unpadded[1] == [4, 5, 6, 2, 3, 4]).all() + + Args: + episode_lens: A list of current episode lengths. The returned + data will have the same lengths minus 1 timestep. + data: A tuple of data items (np.ndarrays) representing concatenated episodes + to be shortened by one timestep per episode. + Note that only arrays with `shape=(n,)` are supported! The + returned data will have `shape=(n-len(episode_lens),)` (each + episode gets shortened by one timestep). + + Returns: + A tuple of new data items shortened by one timestep. + """ + # Figure out the new slices to apply to each data item based on + # the given episode_lens. + slices = [] + sum = 0 + for len_ in episode_lens: + slices.append(slice(sum, sum + len_ - 1)) + sum += len_ + # Compiling return data by slicing off one timestep at the end of + # each episode. + ret = [] + for d in data: + ret.append(np.concatenate([d[s] for s in slices])) + return tuple(ret) if len(ret) > 1 else ret[0] + + +@DeveloperAPI +def remove_last_ts_from_episodes_and_restore_truncateds( + episodes: List[SingleAgentEpisode], + orig_truncateds: List[bool], +) -> None: + """Reverts the effects of `_add_ts_to_episodes_and_truncate`. + + Args: + episodes: The list of SingleAgentEpisode objects to extend by one timestep + and add a truncation flag if necessary. + orig_truncateds: A list of the original episodes' truncated values to be + applied to the `episodes`. + """ + + # Fix all episodes. + for episode, orig_truncated in zip(episodes, orig_truncateds): + # Reduce timesteps by 1. + episode.t -= 1 + # Remove all extra timestep data from the episode's buffers. + episode.observations.pop() + episode.infos.pop() + episode.actions.pop() + episode.rewards.pop() + for v in episode.extra_model_outputs.values(): + v.pop() + # Fix the truncateds flag again. + episode.is_truncated = orig_truncated diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/value_predictions.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/value_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..0c0f88e7f49e9a2969ebdc2fc2887fedcf1f3e32 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/value_predictions.py @@ -0,0 +1,108 @@ +import numpy as np + +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +def compute_value_targets( + values, + rewards, + terminateds, + truncateds, + gamma: float, + lambda_: float, +): + """Computes value function (vf) targets given vf predictions and rewards. + + Note that advantages can then easily be computed via the formula: + advantages = targets - vf_predictions + """ + # Force-set all values at terminals (not at truncations!) to 0.0. + orig_values = flat_values = values * (1.0 - terminateds) + + flat_values = np.append(flat_values, 0.0) + intermediates = rewards + gamma * (1 - lambda_) * flat_values[1:] + continues = 1.0 - terminateds + + Rs = [] + last = flat_values[-1] + for t in reversed(range(intermediates.shape[0])): + last = intermediates[t] + continues[t] * gamma * lambda_ * last + Rs.append(last) + if truncateds[t]: + last = orig_values[t] + + # Reverse back to correct (time) direction. + value_targets = np.stack(list(reversed(Rs)), axis=0) + + return value_targets.astype(np.float32) + + +def extract_bootstrapped_values(vf_preds, episode_lengths, T): + """Returns a bootstrapped value batch given value predictions. + + Note that the incoming value predictions must have happened over (artificially) + elongated episodes (by 1 timestep at the end). This way, we can either extract the + `vf_preds` at these extra timesteps (as "bootstrap values") or skip over them + entirely if they lie in the middle of the T-slices. + + For example, given an episodes structure like this: + 01234a 0123456b 01c 012- 0123e 012- + where each episode is separated by a space and goes from 0 to n and ends in an + artificially elongated timestep (denoted by 'a', 'b', 'c', '-', or 'e'), where '-' + means that the episode was terminated and the bootstrap value at the end should be + zero and 'a', 'b', 'c', etc.. represent truncated episode ends with computed vf + estimates. + The output for the above sequence (and T=4) should then be: + 4 3 b 2 3 - + + Args: + vf_preds: The computed value function predictions over the artificially + elongated episodes (by one timestep at the end). + episode_lengths: The original (correct) episode lengths, NOT counting the + artificially added timestep at the end. + T: The size of the time dimension by which to slice the data. Note that the + sum of all episode lengths (`sum(episode_lengths)`) must be dividable by T. + + Returns: + The batch of bootstrapped values. + """ + bootstrapped_values = [] + if sum(episode_lengths) % T != 0: + raise ValueError( + "Can only extract bootstrapped values if the sum of episode lengths " + f"({sum(episode_lengths)}) is dividable by the given T ({T})!" + ) + + # Loop over all episode lengths and collect bootstrap values. + # Do not alter incoming `episode_lengths` list. + episode_lengths = episode_lengths[:] + i = -1 + while i < len(episode_lengths) - 1: + i += 1 + eps_len = episode_lengths[i] + # We can make another T-stride inside this episode -> + # - Use a vf prediction within the episode as bootstrapped value. + # - "Fix" the episode_lengths array and continue within the same episode. + if T < eps_len: + bootstrapped_values.append(vf_preds[T]) + vf_preds = vf_preds[T:] + episode_lengths[i] -= T + i -= 1 + # We can make another T-stride inside this episode, but will then be at the end + # of it -> + # - Use the value function prediction at the artificially added timestep + # as bootstrapped value. + # - Skip the additional timestep at the end and ,ove on with next episode. + elif T == eps_len: + bootstrapped_values.append(vf_preds[T]) + vf_preds = vf_preds[T + 1 :] + # The episode fits entirely into the T-stride -> + # - Move on to next episode ("fix" its length by make it seemingly longer). + else: + # Skip bootstrap value of current episode (not needed). + vf_preds = vf_preds[1:] + # Make next episode seem longer. + episode_lengths[i + 1] += eps_len + + return np.array(bootstrapped_values) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/zero_padding.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/zero_padding.py new file mode 100644 index 0000000000000000000000000000000000000000..77e459c3c85a6701993ef71be9b8f763521ab8ec --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/postprocessing/zero_padding.py @@ -0,0 +1,270 @@ +from collections import deque +from typing import List, Tuple, Union + +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.utils.spaces.space_utils import batch, BatchedNdArray +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +def create_mask_and_seq_lens(episode_len: int, T: int) -> Tuple[List, List]: + """Creates loss mask and a seq_lens array, given an episode length and T. + + Args: + episode_lens: A list of episode lengths to infer the loss mask and seq_lens + array from. + T: The maximum number of timesteps in each "row", also known as the maximum + sequence length (max_seq_len). Episodes are split into chunks that are at + most `T` long and remaining timesteps will be zero-padded (and masked out). + + Returns: + Tuple consisting of a) list of the loss masks to use (masking out areas that + are past the end of an episode (or rollout), but had to be zero-added due to + the added extra time rank (of length T) and b) the list of sequence lengths + resulting from splitting the given episodes into chunks of at most `T` + timesteps. + """ + mask = [] + seq_lens = [] + + len_ = min(episode_len, T) + seq_lens.append(len_) + row = np.array([1] * len_ + [0] * (T - len_), np.bool_) + mask.append(row) + + # Handle sequence lengths greater than T. + overflow = episode_len - T + while overflow > 0: + len_ = min(overflow, T) + seq_lens.append(len_) + extra_row = np.array([1] * len_ + [0] * (T - len_), np.bool_) + mask.append(extra_row) + overflow -= T + + return mask, seq_lens + + +@DeveloperAPI +def split_and_zero_pad( + item_list: List[Union[BatchedNdArray, np._typing.NDArray, float]], + max_seq_len: int, +) -> List[np._typing.NDArray]: + """Splits the contents of `item_list` into a new list of ndarrays and returns it. + + In the returned list, each item is one ndarray of len (axis=0) `max_seq_len`. + The last item in the returned list may be (right) zero-padded, if necessary, to + reach `max_seq_len`. + + If `item_list` contains one or more `BatchedNdArray` (instead of individual + items), these will be split accordingly along their axis=0 to yield the returned + structure described above. + + .. testcode:: + + from ray.rllib.utils.postprocessing.zero_padding import ( + BatchedNdArray, + split_and_zero_pad, + ) + from ray.rllib.utils.test_utils import check + + # Simple case: `item_list` contains individual floats. + check( + split_and_zero_pad([0, 1, 2, 3, 4, 5, 6, 7], 5), + [[0, 1, 2, 3, 4], [5, 6, 7, 0, 0]], + ) + + # `item_list` contains BatchedNdArray (ndarrays that explicitly declare they + # have a batch axis=0). + check( + split_and_zero_pad([ + BatchedNdArray([0, 1]), + BatchedNdArray([2, 3, 4, 5]), + BatchedNdArray([6, 7, 8]), + ], 5), + [[0, 1, 2, 3, 4], [5, 6, 7, 8, 0]], + ) + + Args: + item_list: A list of individual items or BatchedNdArrays to be split into + `max_seq_len` long pieces (the last of which may be zero-padded). + max_seq_len: The maximum length of each item in the returned list. + + Returns: + A list of np.ndarrays (all of length `max_seq_len`), which contains the same + data as `item_list`, but split into sub-chunks of size `max_seq_len`. + The last item in the returned list may be zero-padded, if necessary. + """ + zero_element = tree.map_structure( + lambda s: np.zeros_like([s[0]] if isinstance(s, BatchedNdArray) else s), + item_list[0], + ) + + # The replacement list (to be returned) for `items_list`. + # Items list contains n individual items. + # -> ret will contain m batched rows, where m == n // T and the last row + # may be zero padded (until T). + ret = [] + + # List of the T-axis item, collected to form the next row. + current_time_row = [] + current_t = 0 + + item_list = deque(item_list) + while len(item_list) > 0: + item = item_list.popleft() + t = max_seq_len - current_t + + # In case `item` is a complex struct. + item_flat = tree.flatten(item) + item_list_append = [] + current_time_row_flat_items = [] + add_to_current_t = 0 + + for itm in item_flat: + # `itm` is already a batched np.array: Split if necessary. + if isinstance(itm, BatchedNdArray): + current_time_row_flat_items.append(itm[:t]) + if len(itm) <= t: + add_to_current_t = len(itm) + else: + add_to_current_t = t + item_list_append.append(itm[t:]) + # `itm` is a single item (no batch axis): Append and continue with next + # item. + else: + current_time_row_flat_items.append(itm) + add_to_current_t = 1 + + current_t += add_to_current_t + current_time_row.append(tree.unflatten_as(item, current_time_row_flat_items)) + if item_list_append: + item_list.appendleft(tree.unflatten_as(item, item_list_append)) + + # `current_time_row` is "full" (max_seq_len): Append as ndarray (with batch + # axis) to `ret`. + if current_t == max_seq_len: + ret.append( + batch( + current_time_row, + individual_items_already_have_batch_dim="auto", + ) + ) + current_time_row = [] + current_t = 0 + + # `current_time_row` is unfinished: Pad, if necessary and append to `ret`. + if current_t > 0 and current_t < max_seq_len: + current_time_row.extend([zero_element] * (max_seq_len - current_t)) + ret.append( + batch(current_time_row, individual_items_already_have_batch_dim="auto") + ) + + return ret + + +@DeveloperAPI +def split_and_zero_pad_n_episodes( + nd_array: np._typing.NDArray, + episode_lens: List[int], + max_seq_len: int, +) -> List[np._typing.NDArray]: + """Splits and zero-pads a single np.ndarray based on episode lens and a maxlen. + + Args: + nd_array: The single np.ndarray to be split into n chunks, based on the given + `episode_lens` and the `max_seq_len` argument. For example, if `nd_array` + has a batch dimension (axis 0) of 21, `episode_lens` is [15, 3, 3], and + `max_seq_len` is 6, then the returned list would have np.ndarrays in it of + batch dimensions (axis 0): [6, 6, 6 (zero-padded), 6 (zero-padded), + 6 (zero-padded)]. + Note that this function doesn't work on nested data, such as dicts of + ndarrays. + episode_lens: A list of episode lengths along which to split and zero-pad the + given `nd_array`. + max_seq_len: The maximum sequence length to split at (and zero-pad). + + Returns: A list of n np.ndarrays, resulting from splitting and zero-padding the + given `nd_array`. + """ + ret = [] + + cursor = 0 + for episode_len in episode_lens: + items = BatchedNdArray(nd_array[cursor : cursor + episode_len]) + ret.extend(split_and_zero_pad([items], max_seq_len)) + cursor += episode_len + + return ret + + +@DeveloperAPI +def unpad_data_if_necessary( + episode_lens: List[int], + data: np._typing.NDArray, +) -> np._typing.NDArray: + """Removes right-side zero-padding from data based on `episode_lens`. + + ..testcode:: + + from ray.rllib.utils.postprocessing.zero_padding import unpad_data_if_necessary + import numpy as np + + unpadded = unpad_data_if_necessary( + episode_lens=[4, 2], + data=np.array([ + [2, 4, 5, 3, 0, 0, 0, 0], + [-1, 3, 0, 0, 0, 0, 0, 0], + ]), + ) + assert (unpadded == [2, 4, 5, 3, -1, 3]).all() + + unpadded = unpad_data_if_necessary( + episode_lens=[1, 5], + data=np.array([ + [2, 0, 0, 0, 0], + [-1, -2, -3, -4, -5], + ]), + ) + assert (unpadded == [2, -1, -2, -3, -4, -5]).all() + + Args: + episode_lens: A list of actual episode lengths. + data: A 2D np.ndarray with right-side zero-padded rows. + + Returns: + A 1D np.ndarray resulting from concatenation of the un-padded + input data along the 0-axis. + """ + # If data des NOT have time dimension, return right away. + if len(data.shape) == 1: + return data + + # Assert we only have B and T dimensions (meaning this function only operates + # on single-float data, such as value function predictions, advantages, or rewards). + assert len(data.shape) == 2 + + new_data = [] + row_idx = 0 + + T = data.shape[1] + for len_ in episode_lens: + # Calculate how many full rows this array occupies and how many elements are + # in the last, potentially partial row. + num_rows, col_idx = divmod(len_, T) + + # If the array spans multiple full rows, fully include these rows. + for i in range(num_rows): + new_data.append(data[row_idx]) + row_idx += 1 + + # If there are elements in the last, potentially partial row, add this + # partial row as well. + if col_idx > 0: + new_data.append(data[row_idx, :col_idx]) + + # Move to the next row for the next array (skip the zero-padding zone). + row_idx += 1 + + return np.concatenate(new_data) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..630234d08ea5b6dc15a82623e1a964f4aafad84b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/__pycache__/env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/__pycache__/env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84180394fe1c371c80992993915a8e5407780fae Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/__pycache__/env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/env.py new file mode 100644 index 0000000000000000000000000000000000000000..7055f08695fb3b9a945def9556d226766baddad3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/pre_checks/env.py @@ -0,0 +1,288 @@ +"""Common pre-checks for all RLlib experiments.""" +import logging +from typing import TYPE_CHECKING, Set + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.error import ERR_MSG_OLD_GYM_API, UnsupportedSpaceException +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.util import log_once + +if TYPE_CHECKING: + from ray.rllib.env import MultiAgentEnv + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +def check_multiagent_environments(env: "MultiAgentEnv") -> None: + """Checking for common errors in RLlib MultiAgentEnvs. + + Args: + env: The env to be checked. + """ + from ray.rllib.env import MultiAgentEnv + + if not isinstance(env, MultiAgentEnv): + raise ValueError("The passed env is not a MultiAgentEnv.") + elif not ( + hasattr(env, "observation_space") + and hasattr(env, "action_space") + and hasattr(env, "_agent_ids") + ): + if log_once("ma_env_super_ctor_called"): + logger.warning( + f"Your MultiAgentEnv {env} does not have some or all of the needed " + "base-class attributes! Make sure you call `super().__init__()` from " + "within your MutiAgentEnv's constructor. " + "This will raise an error in the future." + ) + return + + try: + obs_and_infos = env.reset(seed=42, options={}) + except Exception as e: + raise ValueError( + ERR_MSG_OLD_GYM_API.format( + env, "In particular, the `reset()` method seems to be faulty." + ) + ) from e + reset_obs, reset_infos = obs_and_infos + + _check_if_element_multi_agent_dict(env, reset_obs, "reset()") + + sampled_action = { + aid: env.get_action_space(aid).sample() for aid in reset_obs.keys() + } + _check_if_element_multi_agent_dict( + env, sampled_action, "get_action_space(agent_id=..).sample()" + ) + + try: + results = env.step(sampled_action) + except Exception as e: + raise ValueError( + ERR_MSG_OLD_GYM_API.format( + env, "In particular, the `step()` method seems to be faulty." + ) + ) from e + next_obs, reward, done, truncated, info = results + + _check_if_element_multi_agent_dict(env, next_obs, "step, next_obs") + _check_if_element_multi_agent_dict(env, reward, "step, reward") + _check_if_element_multi_agent_dict(env, done, "step, done") + _check_if_element_multi_agent_dict(env, truncated, "step, truncated") + _check_if_element_multi_agent_dict(env, info, "step, info", allow_common=True) + _check_reward({"dummy_env_id": reward}, base_env=True, agent_ids=env.agents) + _check_done_and_truncated( + {"dummy_env_id": done}, + {"dummy_env_id": truncated}, + base_env=True, + agent_ids=env.agents, + ) + _check_info({"dummy_env_id": info}, base_env=True, agent_ids=env.agents) + + +def _check_reward(reward, base_env=False, agent_ids=None): + if base_env: + for _, multi_agent_dict in reward.items(): + for agent_id, rew in multi_agent_dict.items(): + if not ( + np.isreal(rew) + and not isinstance(rew, bool) + and ( + np.isscalar(rew) + or (isinstance(rew, np.ndarray) and rew.shape == ()) + ) + ): + error = ( + "Your step function must return rewards that are" + f" integer or float. reward: {rew}. Instead it was a " + f"{type(rew)}" + ) + raise ValueError(error) + if not (agent_id in agent_ids or agent_id == "__all__"): + error = ( + f"Your reward dictionary must have agent ids that belong to " + f"the environment. AgentIDs received from " + f"env.agents are: {agent_ids}" + ) + raise ValueError(error) + elif not ( + np.isreal(reward) + and not isinstance(reward, bool) + and ( + np.isscalar(reward) + or (isinstance(reward, np.ndarray) and reward.shape == ()) + ) + ): + error = ( + "Your step function must return a reward that is integer or float. " + "Instead it was a {}".format(type(reward)) + ) + raise ValueError(error) + + +def _check_done_and_truncated(done, truncated, base_env=False, agent_ids=None): + for what in ["done", "truncated"]: + data = done if what == "done" else truncated + if base_env: + for _, multi_agent_dict in data.items(): + for agent_id, done_ in multi_agent_dict.items(): + if not isinstance(done_, (bool, np.bool_)): + raise ValueError( + f"Your step function must return `{what}s` that are " + f"boolean. But instead was a {type(data)}" + ) + if not (agent_id in agent_ids or agent_id == "__all__"): + error = ( + f"Your `{what}s` dictionary must have agent ids that " + f"belong to the environment. AgentIDs received from " + f"env.agents are: {agent_ids}" + ) + raise ValueError(error) + elif not isinstance(data, (bool, np.bool_)): + error = ( + f"Your step function must return a `{what}` that is a boolean. But " + f"instead was a {type(data)}" + ) + raise ValueError(error) + + +def _check_info(info, base_env=False, agent_ids=None): + if base_env: + for _, multi_agent_dict in info.items(): + for agent_id, inf in multi_agent_dict.items(): + if not isinstance(inf, dict): + raise ValueError( + "Your step function must return infos that are a dict. " + f"instead was a {type(inf)}: element: {inf}" + ) + if not ( + agent_id in agent_ids + or agent_id == "__all__" + or agent_id == "__common__" + ): + error = ( + f"Your dones dictionary must have agent ids that belong to " + f"the environment. AgentIDs received from " + f"env.agents are: {agent_ids}" + ) + raise ValueError(error) + elif not isinstance(info, dict): + error = ( + "Your step function must return a info that " + f"is a dict. element type: {type(info)}. element: {info}" + ) + raise ValueError(error) + + +def _not_contained_error(func_name, _type): + _error = ( + f"The {_type} collected from {func_name} was not contained within" + f" your env's {_type} space. Its possible that there was a type" + f"mismatch (for example {_type}s of np.float32 and a space of" + f"np.float64 {_type}s), or that one of the sub-{_type}s was" + f"out of bounds" + ) + return _error + + +def _check_if_element_multi_agent_dict( + env, + element, + function_string, + base_env=False, + allow_common=False, +): + if not isinstance(element, dict): + if base_env: + error = ( + f"The element returned by {function_string} contains values " + f"that are not MultiAgentDicts. Instead, they are of " + f"type: {type(element)}" + ) + else: + error = ( + f"The element returned by {function_string} is not a " + f"MultiAgentDict. Instead, it is of type: " + f" {type(element)}" + ) + raise ValueError(error) + agent_ids: Set = set(env.agents) + agent_ids.add("__all__") + if allow_common: + agent_ids.add("__common__") + + if not all(k in agent_ids for k in element): + if base_env: + error = ( + f"The element returned by {function_string} has agent_ids" + f" that are not the names of the agents in the env." + f"agent_ids in this\nMultiEnvDict:" + f" {list(element.keys())}\nAgentIDs in this env: " + f"{env.agents}" + ) + else: + error = ( + f"The element returned by {function_string} has agent_ids" + f" that are not the names of the agents in the env. " + f"\nAgentIDs in this MultiAgentDict: " + f"{list(element.keys())}\nAgentIDs in this env: " + f"{env.agents}. You likely need to add the attribute `agents` to your " + f"env, which is a list containing the IDs of agents currently in your " + f"env/episode, as well as, `possible_agents`, which is a list of all " + f"possible agents that could ever show up in your env." + ) + raise ValueError(error) + + +def _find_offending_sub_space(space, value): + """Returns error, value, and space when offending `space.contains(value)` fails. + + Returns only the offending sub-value/sub-space in case `space` is a complex Tuple + or Dict space. + + Args: + space: The gym.Space to check. + value: The actual (numpy) value to check for matching `space`. + + Returns: + Tuple consisting of 1) key-sequence of the offending sub-space or the empty + string if `space` is not complex (Tuple or Dict), 2) the offending sub-space, + 3) the offending sub-space's dtype, 4) the offending sub-value, 5) the offending + sub-value's dtype. + + .. testcode:: + :skipif: True + + path, space, space_dtype, value, value_dtype = _find_offending_sub_space( + gym.spaces.Dict({ + -2.0, 1.5, (2, ), np.int8), np.array([-1.5, 3.0]) + ) + + """ + if not isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple)): + return None, space, space.dtype, value, _get_type(value) + + structured_space = get_base_struct_from_space(space) + + def map_fn(p, s, v): + if not s.contains(v): + raise UnsupportedSpaceException((p, s, v)) + + try: + tree.map_structure_with_path(map_fn, structured_space, value) + except UnsupportedSpaceException as e: + space, value = e.args[0][1], e.args[0][2] + return "->".join(e.args[0][0]), space, space.dtype, value, _get_type(value) + + # This is actually an error. + return None, None, None, None, None + + +def _get_type(var): + return var.dtype if hasattr(var, "dtype") else type(var) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e929ab7d59881132e39b5194c0697fa10da944c8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__init__.py @@ -0,0 +1,44 @@ +from ray.rllib.utils.replay_buffers.episode_replay_buffer import EpisodeReplayBuffer +from ray.rllib.utils.replay_buffers.fifo_replay_buffer import FifoReplayBuffer +from ray.rllib.utils.replay_buffers.multi_agent_mixin_replay_buffer import ( + MultiAgentMixInReplayBuffer, +) +from ray.rllib.utils.replay_buffers.multi_agent_episode_buffer import ( + MultiAgentEpisodeReplayBuffer, +) +from ray.rllib.utils.replay_buffers.multi_agent_prioritized_episode_buffer import ( + MultiAgentPrioritizedEpisodeReplayBuffer, +) +from ray.rllib.utils.replay_buffers.multi_agent_prioritized_replay_buffer import ( + MultiAgentPrioritizedReplayBuffer, +) +from ray.rllib.utils.replay_buffers.multi_agent_replay_buffer import ( + MultiAgentReplayBuffer, + ReplayMode, +) +from ray.rllib.utils.replay_buffers.prioritized_episode_buffer import ( + PrioritizedEpisodeReplayBuffer, +) +from ray.rllib.utils.replay_buffers.prioritized_replay_buffer import ( + PrioritizedReplayBuffer, +) +from ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer, StorageUnit +from ray.rllib.utils.replay_buffers.reservoir_replay_buffer import ReservoirReplayBuffer +from ray.rllib.utils.replay_buffers import utils + +__all__ = [ + "EpisodeReplayBuffer", + "FifoReplayBuffer", + "MultiAgentEpisodeReplayBuffer", + "MultiAgentMixInReplayBuffer", + "MultiAgentPrioritizedEpisodeReplayBuffer", + "MultiAgentPrioritizedReplayBuffer", + "MultiAgentReplayBuffer", + "PrioritizedEpisodeReplayBuffer", + "PrioritizedReplayBuffer", + "ReplayMode", + "ReplayBuffer", + "ReservoirReplayBuffer", + "StorageUnit", + "utils", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6462b5d158ea0c4d6d09a02ea6be4ca77111f5e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54f0918516019846d9924500ed9aee109f01ac7e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/episode_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/episode_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d1a0d7a64fea70e949ba0f260e83cdf0c14203f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/episode_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/fifo_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/fifo_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fc9795d6ef315d6447146e124f47acc7a323514 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/fifo_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_episode_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_episode_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..322210147c2a342926241f48b024a0bfa4fa68f0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_episode_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_mixin_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_mixin_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f07a3fae6911ea0949d7d7ebafba6700173ed767 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_mixin_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_episode_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_episode_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee43c2bbd909a8c9fbfa74abb629d2523ef08616 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_episode_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cff44067d1bca82f75599e59cc9e09c8b3927b22 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c076a754f871ddda72bc51ac4f0d341c4dcc1d2c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_episode_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_episode_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2740ee50c68bf03d7e11073ec660391932292a2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_episode_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0da6a426b919709831c76a36fa7ad2934858e3f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3591a14175715c0140854de420bbb6c3b10af15f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/reservoir_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/reservoir_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55b980ca975ed76bf5b5773eb5be714e9b60639d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/reservoir_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/simple_replay_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/simple_replay_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72a696d690ac37124c3fb8a63909fa81abf51aa7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/simple_replay_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b23d6de92bafc1343cfff27b3156c8829518c00f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/base.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..15eefe68cca7c91b4d16a2497d6ffdb8514583c1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/base.py @@ -0,0 +1,76 @@ +from abc import ABCMeta, abstractmethod +import platform +from typing import Any, Dict, Optional + +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class ReplayBufferInterface(metaclass=ABCMeta): + """Abstract base class for all of RLlib's replay buffers. + + Mainly defines the `add()` and `sample()` methods that every buffer class + must implement to be usable by an Algorithm. + Buffers may determine on all the implementation details themselves, e.g. + whether to store single timesteps, episodes, or episode fragments or whether + to return fixed batch sizes or per-call defined ones. + """ + + @abstractmethod + @DeveloperAPI + def __len__(self) -> int: + """Returns the number of items currently stored in this buffer.""" + + @abstractmethod + @DeveloperAPI + def add(self, batch: Any, **kwargs) -> None: + """Adds a batch of experiences or other data to this buffer. + + Args: + batch: Batch or data to add. + ``**kwargs``: Forward compatibility kwargs. + """ + + @abstractmethod + @DeveloperAPI + def sample(self, num_items: Optional[int] = None, **kwargs) -> Any: + """Samples `num_items` items from this buffer. + + The exact shape of the returned data depends on the buffer's implementation. + + Args: + num_items: Number of items to sample from this buffer. + ``**kwargs``: Forward compatibility kwargs. + + Returns: + A batch of items. + """ + + @abstractmethod + @DeveloperAPI + def get_state(self) -> Dict[str, Any]: + """Returns all local state in a dict. + + Returns: + The serializable local state. + """ + + @abstractmethod + @DeveloperAPI + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by calling + `self.get_state()`. + """ + + @DeveloperAPI + def get_host(self) -> str: + """Returns the computer's network name. + + Returns: + The computer's networks name or an empty string, if the network + name could not be determined. + """ + return platform.node() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/episode_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/episode_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..317125265bbf3e1ed693c92f0e8361eb275d0d3e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/episode_replay_buffer.py @@ -0,0 +1,1475 @@ +from collections import deque +import copy +import hashlib +from typing import Any, Dict, List, Optional, Tuple, Union + +import numpy as np +import scipy + +from ray.rllib.core import DEFAULT_AGENT_ID, DEFAULT_MODULE_ID +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.env.utils.infinite_lookback_buffer import InfiniteLookbackBuffer +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.metrics import ( + ACTUAL_N_STEP, + AGENT_ACTUAL_N_STEP, + AGENT_STEP_UTILIZATION, + ENV_STEP_UTILIZATION, + MODULE_STEP_UTILIZATION, + MODULE_ACTUAL_N_STEP, + NUM_AGENT_EPISODES_STORED, + NUM_AGENT_EPISODES_ADDED, + NUM_AGENT_EPISODES_ADDED_LIFETIME, + NUM_AGENT_EPISODES_EVICTED, + NUM_AGENT_EPISODES_EVICTED_LIFETIME, + NUM_AGENT_EPISODES_PER_SAMPLE, + NUM_AGENT_RESAMPLES, + NUM_AGENT_STEPS_STORED, + NUM_AGENT_STEPS_ADDED, + NUM_AGENT_STEPS_ADDED_LIFETIME, + NUM_AGENT_STEPS_EVICTED, + NUM_AGENT_STEPS_EVICTED_LIFETIME, + NUM_AGENT_STEPS_PER_SAMPLE, + NUM_AGENT_STEPS_PER_SAMPLE_LIFETIME, + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_STORED, + NUM_ENV_STEPS_ADDED, + NUM_ENV_STEPS_ADDED_LIFETIME, + NUM_ENV_STEPS_EVICTED, + NUM_ENV_STEPS_EVICTED_LIFETIME, + NUM_ENV_STEPS_PER_SAMPLE, + NUM_ENV_STEPS_PER_SAMPLE_LIFETIME, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_EPISODES_STORED, + NUM_EPISODES_ADDED, + NUM_EPISODES_ADDED_LIFETIME, + NUM_EPISODES_EVICTED, + NUM_EPISODES_EVICTED_LIFETIME, + NUM_EPISODES_PER_SAMPLE, + NUM_MODULE_EPISODES_STORED, + NUM_MODULE_EPISODES_ADDED, + NUM_MODULE_EPISODES_ADDED_LIFETIME, + NUM_MODULE_EPISODES_EVICTED, + NUM_MODULE_EPISODES_EVICTED_LIFETIME, + NUM_MODULE_EPISODES_PER_SAMPLE, + NUM_MODULE_RESAMPLES, + NUM_MODULE_STEPS_ADDED, + NUM_MODULE_STEPS_ADDED_LIFETIME, + NUM_MODULE_STEPS_EVICTED, + NUM_MODULE_STEPS_EVICTED_LIFETIME, + NUM_MODULE_STEPS_PER_SAMPLE, + NUM_MODULE_STEPS_PER_SAMPLE_LIFETIME, + NUM_MODULE_STEPS_SAMPLED, + NUM_MODULE_STEPS_SAMPLED_LIFETIME, + NUM_RESAMPLES, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.replay_buffers.base import ReplayBufferInterface +from ray.rllib.utils.typing import AgentID, ModuleID, SampleBatchType, ResultDict + + +class EpisodeReplayBuffer(ReplayBufferInterface): + """Buffer that stores (completed or truncated) episodes by their ID. + + Each "row" (a slot in a deque) in the buffer is occupied by one episode. If an + incomplete episode is added to the buffer and then another chunk of that episode is + added at a later time, the buffer will automatically concatenate the new fragment to + the original episode. This way, episodes can be completed via subsequent `add` + calls. + + Sampling returns batches of size B (number of "rows"), where each row is a + trajectory of length T. Each trajectory contains consecutive timesteps from an + episode, but might not start at the beginning of that episode. Should an episode end + within such a trajectory, a random next episode (starting from its t0) will be + concatenated to that "row". Example: `sample(B=2, T=4)` -> + + 0 .. 1 .. 2 .. 3 <- T-axis + 0 e5 e6 e7 e8 + 1 f2 f3 h0 h2 + ^ B-axis + + .. where e, f, and h are different (randomly picked) episodes, the 0-index (e.g. h0) + indicates the start of an episode, and `f3` is an episode end (gym environment + returned terminated=True or truncated=True). + + 0-indexed returned timesteps contain the reset observation, a dummy 0.0 reward, as + well as the first action taken in the episode (action picked after observing + obs(0)). + The last index in an episode (e.g. f3 in the example above) contains the final + observation of the episode, the final reward received, a dummy action + (repeat the previous action), as well as either terminated=True or truncated=True. + """ + + __slots__ = ( + "capacity", + "batch_size_B", + "batch_length_T", + "episodes", + "episode_id_to_index", + "num_episodes_evicted", + "_indices", + "_num_timesteps", + "_num_timesteps_added", + "sampled_timesteps", + "rng", + ) + + def __init__( + self, + capacity: int = 10000, + *, + batch_size_B: int = 16, + batch_length_T: int = 64, + metrics_num_episodes_for_smoothing: int = 100, + **kwargs, + ): + """Initializes an EpisodeReplayBuffer instance. + + Args: + capacity: The total number of timesteps to be storable in this buffer. + Will start ejecting old episodes once this limit is reached. + batch_size_B: The number of rows in a SampleBatch returned from `sample()`. + batch_length_T: The length of each row in a SampleBatch returned from + `sample()`. + """ + self.capacity = capacity + self.batch_size_B = batch_size_B + self.batch_length_T = batch_length_T + + # The actual episode buffer. We are using a deque here for faster insertion + # (left side) and eviction (right side) of data. + self.episodes = deque() + # Maps (unique) episode IDs to the index under which to find this episode + # within our `self.episodes` deque. + # Note that even after eviction started, the indices in here will NOT be + # changed. We will therefore need to offset all indices in + # `self.episode_id_to_index` by the number of episodes that have already been + # evicted (self._num_episodes_evicted) in order to get the actual index to use + # on `self.episodes`. + self.episode_id_to_index = {} + # The number of episodes that have already been evicted from the buffer + # due to reaching capacity. + self._num_episodes_evicted = 0 + + # List storing all index tuples: (eps_idx, ts_in_eps_idx), where ... + # `eps_idx - self._num_episodes_evicted' is the index into self.episodes. + # `ts_in_eps_idx` is the timestep index within that episode + # (0 = 1st timestep, etc..). + # We sample uniformly from the set of these indices in a `sample()` + # call. + self._indices = [] + + # The size of the buffer in timesteps. + self._num_timesteps = 0 + # The number of timesteps added thus far. + self._num_timesteps_added = 0 + + # How many timesteps have been sampled from the buffer in total? + self.sampled_timesteps = 0 + + self.rng = np.random.default_rng(seed=None) + + # Initialize the metrics. + self.metrics = MetricsLogger() + self._metrics_num_episodes_for_smoothing = metrics_num_episodes_for_smoothing + + # Initialize the metrics. + self.metrics = MetricsLogger() + self._metrics_num_episodes_for_smoothing = metrics_num_episodes_for_smoothing + + @override(ReplayBufferInterface) + def __len__(self) -> int: + return self.get_num_timesteps() + + @override(ReplayBufferInterface) + def add(self, episodes: Union[List["SingleAgentEpisode"], "SingleAgentEpisode"]): + """Converts incoming SampleBatch into a number of SingleAgentEpisode objects. + + Then adds these episodes to the internal deque. + """ + episodes = force_list(episodes) + + # Set up some counters for metrics. + num_env_steps_added = 0 + agent_to_num_steps_added = {DEFAULT_AGENT_ID: 0} + module_to_num_steps_added = {DEFAULT_MODULE_ID: 0} + num_episodes_added = 0 + agent_to_num_episodes_added = {DEFAULT_AGENT_ID: 0} + module_to_num_episodes_added = {DEFAULT_MODULE_ID: 0} + num_episodes_evicted = 0 + agent_to_num_episodes_evicted = {DEFAULT_AGENT_ID: 0} + module_to_num_episodes_evicted = {DEFAULT_MODULE_ID: 0} + num_env_steps_evicted = 0 + agent_to_num_steps_evicted = {DEFAULT_AGENT_ID: 0} + module_to_num_steps_evicted = {DEFAULT_MODULE_ID: 0} + + for eps in episodes: + # Make sure we don't change what's coming in from the user. + # TODO (sven): It'd probably be better to make sure in the EnvRunner to not + # hold on to episodes (for metrics purposes only) that we are returning + # back to the user from `EnvRunner.sample()`. Then we wouldn't have to + # do any copying. Instead, either compile the metrics right away on the + # EnvRunner OR compile metrics entirely on the Algorithm side (this is + # actually preferred). + eps = copy.deepcopy(eps) + + eps_len = len(eps) + # TODO (simon): Check, if we can deprecate these two + # variables and instead peek into the metrics. + self._num_timesteps += eps_len + self._num_timesteps_added += eps_len + num_env_steps_added += eps_len + agent_to_num_steps_added[DEFAULT_AGENT_ID] += eps_len + module_to_num_steps_added[DEFAULT_MODULE_ID] += eps_len + + # Ongoing episode, concat to existing record. + if eps.id_ in self.episode_id_to_index: + eps_idx = self.episode_id_to_index[eps.id_] + existing_eps = self.episodes[eps_idx - self._num_episodes_evicted] + old_len = len(existing_eps) + self._indices.extend([(eps_idx, old_len + i) for i in range(len(eps))]) + existing_eps.concat_episode(eps) + # New episode. Add to end of our episodes deque. + else: + num_episodes_added += 1 + agent_to_num_episodes_added[DEFAULT_AGENT_ID] += 1 + module_to_num_episodes_added[DEFAULT_MODULE_ID] += 1 + self.episodes.append(eps) + eps_idx = len(self.episodes) - 1 + self._num_episodes_evicted + self.episode_id_to_index[eps.id_] = eps_idx + self._indices.extend([(eps_idx, i) for i in range(len(eps))]) + + # Eject old records from front of deque (only if we have more than 1 episode + # in the buffer). + while self._num_timesteps > self.capacity and self.get_num_episodes() > 1: + # Eject oldest episode. + evicted_eps = self.episodes.popleft() + evicted_eps_len = len(evicted_eps) + num_episodes_evicted += 1 + num_env_steps_evicted += evicted_eps_len + agent_to_num_episodes_evicted[DEFAULT_AGENT_ID] += 1 + module_to_num_episodes_evicted[DEFAULT_MODULE_ID] += 1 + agent_to_num_steps_evicted[ + DEFAULT_AGENT_ID + ] += evicted_eps.agent_steps() + module_to_num_steps_evicted[ + DEFAULT_MODULE_ID + ] += evicted_eps.agent_steps() + # Correct our size. + self._num_timesteps -= evicted_eps_len + + # Erase episode from all our indices: + # 1) Main episode index. + evicted_idx = self.episode_id_to_index[evicted_eps.id_] + del self.episode_id_to_index[evicted_eps.id_] + # 2) All timestep indices that this episode owned. + new_indices = [] # New indices that will replace self._indices. + idx_cursor = 0 + # Loop through all (eps_idx, ts_in_eps_idx)-tuples. + for i, idx_tuple in enumerate(self._indices): + # This tuple is part of the evicted episode -> Add everything + # up until here to `new_indices` (excluding this very index, b/c + # it's already part of the evicted episode). + if idx_cursor is not None and idx_tuple[0] == evicted_idx: + new_indices.extend(self._indices[idx_cursor:i]) + # Set to None to indicate we are in the eviction zone. + idx_cursor = None + # We are/have been in the eviction zone (i pointing/pointed to the + # evicted episode) .. + elif idx_cursor is None: + # ... but are now not anymore (i is now an index into a + # non-evicted episode) -> Set cursor to valid int again. + if idx_tuple[0] != evicted_idx: + idx_cursor = i + # But early-out if evicted episode was only 1 single + # timestep long. + if evicted_eps_len == 1: + break + # Early-out: We reached the end of the to-be-evicted episode. + # We can stop searching further here (all following tuples + # will NOT be in the evicted episode). + elif idx_tuple[1] == evicted_eps_len - 1: + assert self._indices[i + 1][0] != idx_tuple[0] + idx_cursor = i + 1 + break + + # Jump over (splice-out) the evicted episode if we are still in the + # eviction zone. + if idx_cursor is not None: + new_indices.extend(self._indices[idx_cursor:]) + + # Reset our `self._indices` to the newly compiled list. + self._indices = new_indices + + # Increase episode evicted counter. + self._num_episodes_evicted += 1 + + # Update the metrics. + self._update_add_metrics( + num_episodes_added=num_episodes_added, + num_env_steps_added=num_env_steps_added, + num_episodes_evicted=num_episodes_evicted, + num_env_steps_evicted=num_env_steps_evicted, + agent_to_num_episodes_added=agent_to_num_episodes_added, + agent_to_num_steps_added=agent_to_num_steps_added, + agent_to_num_episodes_evicted=agent_to_num_episodes_evicted, + agent_to_num_steps_evicted=agent_to_num_steps_evicted, + module_to_num_episodes_added=module_to_num_steps_added, + module_to_num_steps_added=module_to_num_episodes_added, + module_to_num_episodes_evicted=module_to_num_episodes_evicted, + module_to_num_steps_evicted=module_to_num_steps_evicted, + ) + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def _update_add_metrics( + self, + *, + num_episodes_added: int, + num_env_steps_added: int, + num_episodes_evicted: int, + num_env_steps_evicted: int, + agent_to_num_episodes_added: Dict[AgentID, int], + agent_to_num_steps_added: Dict[AgentID, int], + agent_to_num_episodes_evicted: Dict[AgentID, int], + agent_to_num_steps_evicted: Dict[AgentID, int], + module_to_num_steps_added: Dict[ModuleID, int], + module_to_num_episodes_added: Dict[ModuleID, int], + module_to_num_episodes_evicted: Dict[ModuleID, int], + module_to_num_steps_evicted: Dict[ModuleID, int], + **kwargs, + ) -> None: + """Updates the replay buffer's adding metrics. + + Args: + num_episodes_added: The total number of episodes added to the + buffer in the `EpisodeReplayBuffer.add` call. + num_timesteps_added: The total number of environment steps added to the + buffer in the `EpisodeReplayBuffer.add` call. + num_episodes_evicted: The total number of environment steps evicted from + the buffer in the `EpisodeReplayBuffer.add` call. Note, this + does not include the number of episodes evicted before ever + added to the buffer (i.e. can happen in case a lot of episodes + were added and the buffer's capacity is not large enough). + num_env_steps_evicted: he total number of environment steps evicted from + the buffer in the `EpisodeReplayBuffer.add` call. Note, this + does not include the number of steps evicted before ever + added to the buffer (i.e. can happen in case a lot of episodes + were added and the buffer's capacity is not large enough). + agent_to_num_episodes_added: A dictionary with the number of episodes per + agent ID added to the buffer during the `EpisodeReplayBuffer.add` call. + agent_to_num_steps_added: A dictionary with the number of agent steps per + agent ID added to the buffer during the `EpisodeReplayBuffer.add` call. + agent_to_num_episodes_evicted: A dictionary with the number of episodes per + agent ID evicted to the buffer during the `EpisodeReplayBuffer.add` call. + agent_to_num_steps_evicted: A dictionary with the number of agent steps per + agent ID evicted to the buffer during the `EpisodeReplayBuffer.add` call. + module_to_num_episodes_added: A dictionary with the number of episodes per + module ID added to the buffer during the `EpisodeReplayBuffer.add` call. + module_to_num_steps_added: A dictionary with the number of agent steps per + module ID added to the buffer during the `EpisodeReplayBuffer.add` call. + module_to_num_episodes_evicted: A dictionary with the number of episodes per + module ID evicted to the buffer during the `EpisodeReplayBuffer.add` call. + module_to_num_steps_evicted: A dictionary with the number of agent steps per + module ID evicted to the buffer during the `EpisodeReplayBuffer.add` call. + """ + # Whole buffer episode metrics. + self.metrics.log_value( + NUM_EPISODES_STORED, + self.get_num_episodes(), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + # Number of new episodes added. Note, this metric could + # be zero when ongoing episodes were logged. + self.metrics.log_value( + NUM_EPISODES_ADDED, + num_episodes_added, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_EPISODES_ADDED_LIFETIME, + num_episodes_added, + reduce="sum", + ) + self.metrics.log_value( + NUM_EPISODES_EVICTED, + num_episodes_evicted, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_EPISODES_EVICTED_LIFETIME, + num_episodes_evicted, + reduce="sum", + ) + # Whole buffer step metrics. + self.metrics.log_value( + NUM_ENV_STEPS_STORED, + self.get_num_timesteps(), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + self.metrics.log_value( + NUM_ENV_STEPS_ADDED, + num_env_steps_added, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_ADDED_LIFETIME, + num_env_steps_added, + reduce="sum", + ) + self.metrics.log_value( + NUM_ENV_STEPS_EVICTED, + num_env_steps_evicted, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_EVICTED_LIFETIME, + num_env_steps_evicted, + reduce="sum", + ) + + # Log per-agent metrics. + for aid in agent_to_num_episodes_added: + # Number of new episodes added. Note, this metric could + # be zero. + self.metrics.log_value( + (NUM_AGENT_EPISODES_ADDED, aid), + agent_to_num_episodes_added[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_EPISODES_ADDED_LIFETIME, aid), + agent_to_num_episodes_added[aid], + reduce="sum", + ) + # Number of new agent steps added. Note, this metric could + # be zero, too. + self.metrics.log_value( + (NUM_AGENT_STEPS_ADDED, aid), + agent_to_num_steps_added[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_ADDED_LIFETIME, aid), + agent_to_num_steps_added[aid], + reduce="sum", + ) + for aid in agent_to_num_episodes_evicted: + # Number of agent episodes evicted. Note, values could be zero. + self.metrics.log_value( + (NUM_AGENT_EPISODES_EVICTED, aid), + agent_to_num_episodes_evicted[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_EPISODES_EVICTED_LIFETIME, aid), + agent_to_num_episodes_evicted[aid], + reduce="sum", + ) + # Number of agent steps evicted. Note, values could be zero. + self.metrics.log_value( + (NUM_AGENT_STEPS_EVICTED, aid), + agent_to_num_steps_evicted[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_EVICTED_LIFETIME, aid), + agent_to_num_steps_evicted[aid], + reduce="sum", + ) + # Note, we need to loop through the metrics here to receive + # metrics for all agents (not only the ones that steps). + for aid in self.metrics.stats[NUM_AGENT_STEPS_ADDED_LIFETIME]: + # Add default metrics for evicted episodes if not existent. + if aid not in agent_to_num_episodes_evicted: + self.metrics.log_value( + (NUM_AGENT_EPISODES_EVICTED, aid), + 0, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_EPISODES_EVICTED_LIFETIME, aid), + 0, + reduce="sum", + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_EVICTED, aid), + 0, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_EVICTED_LIFETIME, aid), + 0, + reduce="sum", + ) + # Number of episodes in the buffer. + agent_episodes_stored = self.metrics.peek( + (NUM_AGENT_EPISODES_ADDED_LIFETIME, aid) + ) - self.metrics.peek((NUM_AGENT_EPISODES_EVICTED_LIFETIME, aid)) + self.metrics.log_value( + (NUM_AGENT_EPISODES_STORED, aid), + agent_episodes_stored, + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + # Number of agent steps in the buffer. + agent_steps_stored = self.metrics.peek( + (NUM_AGENT_STEPS_ADDED_LIFETIME, aid) + ) - self.metrics.peek((NUM_AGENT_EPISODES_EVICTED_LIFETIME, aid)) + + self.metrics.log_value( + (NUM_AGENT_STEPS_STORED, aid), + agent_steps_stored, + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + + # Log per-module metrics. + for mid in module_to_num_episodes_added: + # Number of new episodes added. Note, this metric could + # be zero. + self.metrics.log_value( + (NUM_MODULE_EPISODES_ADDED, mid), + module_to_num_episodes_added[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_EPISODES_ADDED_LIFETIME, mid), + module_to_num_episodes_added[mid], + reduce="sum", + ) + # Number of new module steps added. Note, this metric could + # be zero, too. + self.metrics.log_value( + (NUM_MODULE_STEPS_ADDED, mid), + module_to_num_steps_added[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_ADDED_LIFETIME, mid), + module_to_num_steps_added[mid], + reduce="sum", + ) + for mid in module_to_num_episodes_evicted: + # Number of module episodes evicted. Note, values could be zero. + self.metrics.log_value( + (NUM_MODULE_EPISODES_EVICTED, mid), + module_to_num_episodes_evicted[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_EPISODES_EVICTED_LIFETIME, mid), + module_to_num_episodes_evicted[mid], + reduce="sum", + ) + # Number of module steps evicted. Note, values could be zero. + self.metrics.log_value( + (NUM_MODULE_STEPS_EVICTED, mid), + module_to_num_steps_evicted[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_EVICTED_LIFETIME, mid), + module_to_num_steps_evicted[mid], + reduce="sum", + ) + # Note, we need to loop through the metrics here to receive + # metrics for all agents (not only the ones that steps). + for mid in self.metrics.stats[NUM_MODULE_STEPS_ADDED_LIFETIME]: + # Number of episodes in the buffer. + if mid not in module_to_num_episodes_evicted: + self.metrics.log_value( + (NUM_MODULE_EPISODES_EVICTED, mid), + 0, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_EPISODES_EVICTED_LIFETIME, mid), + 0, + reduce="sum", + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_EVICTED, mid), + 0, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_EVICTED_LIFETIME, mid), + 0, + reduce="sum", + ) + module_episodes_stored = self.metrics.peek( + (NUM_MODULE_EPISODES_ADDED_LIFETIME, mid) + ) - self.metrics.peek((NUM_MODULE_EPISODES_EVICTED_LIFETIME, mid)) + self.metrics.log_value( + (NUM_MODULE_EPISODES_STORED, mid), + module_episodes_stored, + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + + @override(ReplayBufferInterface) + def sample( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = None, + beta: float = 0.0, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + sample_episodes: Optional[bool] = False, + to_numpy: bool = False, + # TODO (simon): Check, if we need here 1 as default. + lookback: int = 0, + min_batch_length_T: int = 0, + **kwargs, + ) -> Union[SampleBatchType, SingleAgentEpisode]: + """Samples from a buffer in a randomized way. + + Each sampled item defines a transition of the form: + + `(o_t, a_t, sum(r_(t+1:t+n+1)), o_(t+n), terminated_(t+n), truncated_(t+n))` + + where `o_t` is drawn by randomized sampling.`n` is defined by the `n_step` + applied. + + If requested, `info`s of a transitions last timestep `t+n` and respective + extra model outputs (e.g. action log-probabilities) are added to + the batch. + + Args: + num_items: Number of items (transitions) to sample from this + buffer. + batch_size_B: The number of rows (transitions) to return in the + batch + batch_length_T: THe sequence length to sample. At this point in time + only sequences of length 1 are possible. + n_step: The n-step to apply. For the default the batch contains in + `"new_obs"` the observation and in `"obs"` the observation `n` + time steps before. The reward will be the sum of rewards + collected in between these two observations and the action will + be the one executed n steps before such that we always have the + state-action pair that triggered the rewards. + If `n_step` is a tuple, it is considered as a range to sample + from. If `None`, we use `n_step=1`. + gamma: The discount factor to be used when applying n-step calculations. + The default of `0.99` should be replaced by the `Algorithm`s + discount factor. + include_infos: A boolean indicating, if `info`s should be included in + the batch. This could be of advantage, if the `info` contains + values from the environment important for loss computation. If + `True`, the info at the `"new_obs"` in the batch is included. + include_extra_model_outputs: A boolean indicating, if + `extra_model_outputs` should be included in the batch. This could be + of advantage, if the `extra_mdoel_outputs` contain outputs from the + model important for loss computation and only able to compute with the + actual state of model e.g. action log-probabilities, etc.). If `True`, + the extra model outputs at the `"obs"` in the batch is included (the + timestep at which the action is computed). + to_numpy: If episodes should be numpy'ized. + lookback: A desired lookback. Any non-negative integer is valid. + min_batch_length_T: An optional minimal length when sampling sequences. It + ensures that sampled sequences are at least `min_batch_length_T` time + steps long. This can be used to prevent empty sequences during + learning, when using a burn-in period for stateful `RLModule`s. In rare + cases, such as when episodes are very short early in training, this may + result in longer sampling times. + + Returns: + Either a batch with transitions in each row or (if `return_episodes=True`) + a list of 1-step long episodes containing all basic episode data and if + requested infos and extra model outputs. + """ + + if sample_episodes: + return self._sample_episodes( + num_items=num_items, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + beta=beta, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + to_numpy=to_numpy, + lookback=lookback, + min_batch_length_T=min_batch_length_T, + ) + else: + return self._sample_batch( + num_items=num_items, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + ) + + def _sample_batch( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + ) -> SampleBatchType: + """Returns a batch of size B (number of "rows"), where each row has length T. + + Each row contains consecutive timesteps from an episode, but might not start + at the beginning of that episode. Should an episode end within such a + row (trajectory), a random next episode (starting from its t0) will be + concatenated to that row. For more details, see the docstring of the + EpisodeReplayBuffer class. + + Args: + num_items: See `batch_size_B`. For compatibility with the + `ReplayBufferInterface` abstract base class. + batch_size_B: The number of rows (trajectories) to return in the batch. + batch_length_T: The length of each row (in timesteps) to return in the + batch. + + Returns: + The sampled batch (observations, actions, rewards, terminateds, truncateds) + of dimensions [B, T, ...]. + """ + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + batch_length_T = batch_length_T or self.batch_length_T + + # Rows to return. + observations = [[] for _ in range(batch_size_B)] + actions = [[] for _ in range(batch_size_B)] + rewards = [[] for _ in range(batch_size_B)] + is_first = [[False] * batch_length_T for _ in range(batch_size_B)] + is_last = [[False] * batch_length_T for _ in range(batch_size_B)] + is_terminated = [[False] * batch_length_T for _ in range(batch_size_B)] + is_truncated = [[False] * batch_length_T for _ in range(batch_size_B)] + + # Store the unique episode buffer indices to determine sample variation. + sampled_episode_idxs = set() + # Store the unique env step buffer indices to determine sample variation + sampled_env_step_idxs = set() + + B = 0 + T = 0 + while B < batch_size_B: + # Pull a new uniform random index tuple: (eps_idx, ts_in_eps_idx). + index_tuple = self._indices[self.rng.integers(len(self._indices))] + + # Compute the actual episode index (offset by the number of + # already evicted episodes). + episode_idx, episode_ts = ( + index_tuple[0] - self._num_episodes_evicted, + index_tuple[1], + ) + episode = self.episodes[episode_idx] + + # Starting a new chunk, set is_first to True. + is_first[B][T] = True + + # Begin of new batch item (row). + if len(rewards[B]) == 0: + # And we are at the start of an episode: Set reward to 0.0. + if episode_ts == 0: + rewards[B].append(0.0) + # We are in the middle of an episode: Set reward to the previous + # timestep's values. + else: + rewards[B].append(episode.rewards[episode_ts - 1]) + # We are in the middle of a batch item (row). Concat next episode to this + # row from the next episode's beginning. In other words, we never concat + # a middle of an episode to another truncated one. + else: + episode_ts = 0 + rewards[B].append(0.0) + + observations[B].extend(episode.observations[episode_ts:]) + # Repeat last action to have the same number of actions than observations. + actions[B].extend(episode.actions[episode_ts:]) + actions[B].append(episode.actions[-1]) + # Number of rewards are also the same as observations b/c we have the + # initial 0.0 one. + rewards[B].extend(episode.rewards[episode_ts:]) + assert len(observations[B]) == len(actions[B]) == len(rewards[B]) + + T = min(len(observations[B]), batch_length_T) + + # Set is_last=True. + is_last[B][T - 1] = True + # If episode is terminated and we have reached the end of it, set + # is_terminated=True. + if episode.is_terminated and T == len(observations[B]): + is_terminated[B][T - 1] = True + # If episode is truncated and we have reached the end of it, set + # is_truncated=True. + elif episode.is_truncated and T == len(observations[B]): + is_truncated[B][T - 1] = True + + # We are done with this batch row. + if T == batch_length_T: + # We may have overfilled this row: Clip trajectory at the end. + observations[B] = observations[B][:batch_length_T] + actions[B] = actions[B][:batch_length_T] + rewards[B] = rewards[B][:batch_length_T] + # Start filling the next row. + B += 1 + T = 0 + # Add the episode buffer index to the set of episode indexes. + sampled_episode_idxs.add(episode_idx) + # Add the unique hashcode for the timestep. + sampled_env_step_idxs.add( + hashlib.sha256(f"{episode.id_}-{episode_ts}".encode()).hexdigest() + ) + + # Update our sampled counter. + self.sampled_timesteps += batch_size_B * batch_length_T + + # Update the sample metrics. + num_env_steps_sampled = batch_size_B * batch_length_T + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + num_resamples = 0 + agent_to_sample_size = {DEFAULT_AGENT_ID: num_env_steps_sampled} + agent_to_num_episodes_per_sample = {DEFAULT_AGENT_ID: num_episodes_per_sample} + agent_to_num_steps_per_sample = {DEFAULT_AGENT_ID: num_env_steps_per_sample} + agent_to_num_resamples = {DEFAULT_AGENT_ID: num_resamples} + module_to_num_steps_sampled = {DEFAULT_MODULE_ID: num_env_steps_sampled} + module_to_num_episodes_per_sample = {DEFAULT_MODULE_ID: num_episodes_per_sample} + module_to_num_steps_per_sample = {DEFAULT_MODULE_ID: num_env_steps_per_sample} + module_to_num_resamples = {DEFAULT_MODULE_ID: num_resamples} + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + num_resamples=num_resamples, + sampled_n_step=None, + agent_to_num_steps_sampled=agent_to_sample_size, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_num_resamples=agent_to_num_resamples, + agent_to_sampled_n_step=None, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_num_resamples=module_to_num_resamples, + module_to_sampled_n_step=None, + ) + + # TODO: Return SampleBatch instead of this simpler dict. + ret = { + "obs": np.array(observations), + "actions": np.array(actions), + "rewards": np.array(rewards), + "is_first": np.array(is_first), + "is_last": np.array(is_last), + "is_terminated": np.array(is_terminated), + "is_truncated": np.array(is_truncated), + } + + return ret + + def _sample_episodes( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = None, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + to_numpy: bool = False, + lookback: int = 1, + min_batch_length_T: int = 0, + **kwargs, + ) -> List[SingleAgentEpisode]: + """Samples episodes from a buffer in a randomized way. + + Each sampled item defines a transition of the form: + + `(o_t, a_t, sum(r_(t+1:t+n+1)), o_(t+n), terminated_(t+n), truncated_(t+n))` + + where `o_t` is drawn by randomized sampling.`n` is defined by the `n_step` + applied. + + If requested, `info`s of a transitions last timestep `t+n` and respective + extra model outputs (e.g. action log-probabilities) are added to + the batch. + + Args: + num_items: Number of items (transitions) to sample from this + buffer. + batch_size_B: The number of rows (transitions) to return in the + batch + batch_length_T: The sequence length to sample. Can be either `None` + (the default) or any positive integer. + n_step: The n-step to apply. For the default the batch contains in + `"new_obs"` the observation and in `"obs"` the observation `n` + time steps before. The reward will be the sum of rewards + collected in between these two observations and the action will + be the one executed n steps before such that we always have the + state-action pair that triggered the rewards. + If `n_step` is a tuple, it is considered as a range to sample + from. If `None`, we use `n_step=1`. + gamma: The discount factor to be used when applying n-step calculations. + The default of `0.99` should be replaced by the `Algorithm`s + discount factor. + include_infos: A boolean indicating, if `info`s should be included in + the batch. This could be of advantage, if the `info` contains + values from the environment important for loss computation. If + `True`, the info at the `"new_obs"` in the batch is included. + include_extra_model_outputs: A boolean indicating, if + `extra_model_outputs` should be included in the batch. This could be + of advantage, if the `extra_mdoel_outputs` contain outputs from the + model important for loss computation and only able to compute with the + actual state of model e.g. action log-probabilities, etc.). If `True`, + the extra model outputs at the `"obs"` in the batch is included (the + timestep at which the action is computed). + to_numpy: If episodes should be numpy'ized. + lookback: A desired lookback. Any non-negative integer is valid. + min_batch_length_T: An optional minimal length when sampling sequences. It + ensures that sampled sequences are at least `min_batch_length_T` time + steps long. This can be used to prevent empty sequences during + learning, when using a burn-in period for stateful `RLModule`s. In rare + cases, such as when episodes are very short early in training, this may + result in longer sampling times. + + Returns: + A list of 1-step long episodes containing all basic episode data and if + requested infos and extra model outputs. + """ + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + + assert n_step is not None, ( + "When sampling episodes, `n_step` must be " + "provided, but `n_step` is `None`." + ) + # If no sequence should be sampled, we sample n-steps. + if not batch_length_T: + # Sample the `n_step`` itself, if necessary. + actual_n_step = n_step + random_n_step = isinstance(n_step, tuple) + # Otherwise we use an n-step of 1. + else: + assert ( + not isinstance(n_step, tuple) and n_step == 1 + ), "When sampling sequences n-step must be 1." + actual_n_step = n_step + + # Keep track of the indices that were sampled last for updating the + # weights later (see `ray.rllib.utils.replay_buffer.utils. + # update_priorities_in_episode_replay_buffer`). + self._last_sampled_indices = [] + + sampled_episodes = [] + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + # Record all n-steps that have been used. + sampled_n_steps = [] + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + # Record all n-steps that have been used. + sampled_n_steps = [] + + B = 0 + while B < batch_size_B: + # Pull a new uniform random index tuple: (eps_idx, ts_in_eps_idx). + index_tuple = self._indices[self.rng.integers(len(self._indices))] + + # Compute the actual episode index (offset by the number of + # already evicted episodes). + episode_idx, episode_ts = ( + index_tuple[0] - self._num_episodes_evicted, + index_tuple[1], + ) + episode = self.episodes[episode_idx] + + # If we use random n-step sampling, draw the n-step for this item. + if not batch_length_T and random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + + # Skip, if we are too far to the end and `episode_ts` + n_step would go + # beyond the episode's end. + if min_batch_length_T > 0 and episode_ts + min_batch_length_T >= len( + episode + ): + continue + if episode_ts + (batch_length_T or 0) + (actual_n_step - 1) > len(episode): + actual_length = len(episode) + else: + actual_length = episode_ts + (batch_length_T or 0) + (actual_n_step - 1) + + # If no sequence should be sampled, we sample here the n-step. + if not batch_length_T: + sampled_episode = episode.slice( + slice( + episode_ts, + episode_ts + actual_n_step, + ) + ) + # Note, this will be the reward after executing action + # `a_(episode_ts-n_step+1)`. For `n_step>1` this will be the discounted + # sum of all discounted rewards that were collected over the last n + # steps. + raw_rewards = sampled_episode.get_rewards() + + rewards = scipy.signal.lfilter( + [1], [1, -gamma], raw_rewards[::-1], axis=0 + )[-1] + + sampled_episode = SingleAgentEpisode( + id_=sampled_episode.id_, + agent_id=sampled_episode.agent_id, + module_id=sampled_episode.module_id, + observation_space=sampled_episode.observation_space, + action_space=sampled_episode.action_space, + observations=[ + sampled_episode.get_observations(0), + sampled_episode.get_observations(-1), + ], + actions=[sampled_episode.get_actions(0)], + rewards=[rewards], + infos=[ + sampled_episode.get_infos(0), + sampled_episode.get_infos(-1), + ], + terminated=sampled_episode.is_terminated, + truncated=sampled_episode.is_truncated, + extra_model_outputs={ + **( + { + k: [episode.get_extra_model_outputs(k, 0)] + for k in episode.extra_model_outputs.keys() + } + if include_extra_model_outputs + else {} + ), + }, + t_started=episode_ts, + len_lookback_buffer=0, + ) + # Otherwise we simply slice the episode. + else: + sampled_episode = episode.slice( + slice( + episode_ts, + actual_length, + ), + len_lookback_buffer=lookback, + ) + # Record a has for the episode ID and timestep inside of the episode. + sampled_env_step_idxs.add( + hashlib.sha256(f"{episode.id_}-{episode_ts}".encode()).hexdigest() + ) + # Record a has for the episode ID and timestep inside of the episode. + sampled_env_step_idxs.add( + hashlib.sha256(f"{episode.id_}-{episode_ts}".encode()).hexdigest() + ) + # Remove reference to sampled episode. + del episode + + # Add the actually chosen n-step in this episode. + sampled_episode.extra_model_outputs["n_step"] = InfiniteLookbackBuffer( + np.full((len(sampled_episode) + lookback,), actual_n_step), + lookback=lookback, + ) + # Some loss functions need `weights` - which are only relevant when + # prioritizing. + sampled_episode.extra_model_outputs["weights"] = InfiniteLookbackBuffer( + np.ones((len(sampled_episode) + lookback,)), lookback=lookback + ) + + # Append the sampled episode. + sampled_episodes.append(sampled_episode) + sampled_episode_idxs.add(episode_idx) + sampled_n_steps.append(actual_n_step) + + # Increment counter. + B += (actual_length - episode_ts - (actual_n_step - 1) + 1) or 1 + + # Update the metric. + self.sampled_timesteps += batch_size_B + + # Update the sample metrics. + num_env_steps_sampled = batch_size_B + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + sampled_n_step = sum(sampled_n_steps) / batch_size_B + num_resamples = 0 + agent_to_num_steps_sampled = {DEFAULT_AGENT_ID: num_env_steps_sampled} + agent_to_num_episodes_per_sample = {DEFAULT_AGENT_ID: num_episodes_per_sample} + agent_to_num_steps_per_sample = {DEFAULT_AGENT_ID: num_env_steps_per_sample} + agent_to_sampled_n_step = {DEFAULT_AGENT_ID: sampled_n_step} + agent_to_num_resamples = {DEFAULT_AGENT_ID: num_resamples} + module_to_num_steps_sampled = {DEFAULT_MODULE_ID: num_env_steps_sampled} + module_to_num_episodes_per_sample = {DEFAULT_MODULE_ID: num_episodes_per_sample} + module_to_num_steps_per_sample = {DEFAULT_MODULE_ID: num_env_steps_per_sample} + module_to_sampled_n_step = {DEFAULT_MODULE_ID: sampled_n_step} + module_to_num_resamples = {DEFAULT_MODULE_ID: num_resamples} + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + sampled_n_step=sampled_n_step, + num_resamples=num_resamples, + agent_to_num_steps_sampled=agent_to_num_steps_sampled, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_sampled_n_step=agent_to_sampled_n_step, + agent_to_num_resamples=agent_to_num_resamples, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_sampled_n_step=module_to_sampled_n_step, + module_to_num_resamples=module_to_num_resamples, + ) + + return sampled_episodes + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def _update_sample_metrics( + self, + *, + num_env_steps_sampled: int, + num_episodes_per_sample: int, + num_env_steps_per_sample: int, + sampled_n_step: Optional[float], + num_resamples: int, + agent_to_num_steps_sampled: Dict[AgentID, int], + agent_to_num_episodes_per_sample: Dict[AgentID, int], + agent_to_num_steps_per_sample: Dict[AgentID, int], + agent_to_sampled_n_step: Dict[AgentID, float], + agent_to_num_resamples: Dict[AgentID, int], + module_to_num_steps_sampled: Dict[ModuleID, int], + module_to_num_episodes_per_sample: Dict[ModuleID, int], + module_to_num_steps_per_sample: Dict[ModuleID, int], + module_to_sampled_n_step: Dict[ModuleID, float], + module_to_num_resamples: Dict[ModuleID, int], + **kwargs: Dict[str, Any], + ) -> None: + """Updates the replay buffer's sample metrics. + + Args: + num_env_steps_sampled: The number of environment steps sampled + this iteration in the `sample` method. + num_episodes_per_sample: The number of unique episodes in the + sample. + num_env_steps_per_sample: The number of unique environment steps + in the sample. + sampled_n_step: The mean n-step used in the sample. Note, this + is constant, if the n-step is not sampled. + num_resamples: The number of resamples in a single call to + `PrioritizedEpisodeReplayBuffer.sample`. A resampling is triggered + when the sampled timestep is to near to the episode end to cover the + required n-step. + agent_to_num_steps_sampled: A dictionary with the number of agent + steps per agent ID sampled during the `EpisodeReplayBuffer.sample` + call. + agent_to_num_episodes_per_sample: A dictionary with the number of + unique episodes per agent ID contained in the sample returned by + the `EpisodeReplayBuffer.sample` call. + agent_to_num_steps_per_sample: A dictionary with the number of + unique agent steps per agent ID contained in the sample returned by + the `EpisodeReplayBuffer.sample` call. + agent_to_sampled_n_step: A dictionary with the mean n-step per agent ID + used in the sample returned by the `EpisodeReplayBuffer.sample` call. + agent_to_num_resamples: A dictionary with the number of resamples per + agent ID in a single call to `PrioritizedEpisodeReplayBuffer.sample`. + A resampling is triggered when the sampled timestep is to near to the + episode end to cover the required n-step. + module_to_num_steps_sampled: A dictionary with the number of module + steps per module ID sampled during the `EpisodeReplayBuffer.sample` + call. + module_to_num_episodes_per_sample: A dictionary with the number of + unique episodes per module ID contained in the sample returned by + the `EpisodeReplayBuffer.sample` call. + module_to_num_steps_per_sample: A dictionary with the number of + unique module steps per module ID contained in the sample returned by + the `EpisodeReplayBuffer.sample` call. + module_to_sampled_n_step: A dictionary with the mean n-step per module ID + used in the sample returned by the `EpisodeReplayBuffer.sample` call. + module_to_num_resamples: A dictionary with the number of resamples per + module ID in a single call to `PrioritizedEpisodeReplayBuffer.sample`. + A resampling is triggered when the sampled timestep is to near to the + episode end to cover the required n-step. + """ + # Whole buffer sampled env steps metrics. + self.metrics.log_value( + NUM_EPISODES_PER_SAMPLE, + num_episodes_per_sample, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_PER_SAMPLE, + num_env_steps_per_sample, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_PER_SAMPLE_LIFETIME, + num_env_steps_per_sample, + reduce="sum", + ) + self.metrics.log_value( + NUM_ENV_STEPS_SAMPLED, + num_env_steps_sampled, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_SAMPLED_LIFETIME, + num_env_steps_sampled, + reduce="sum", + ) + self.metrics.log_value( + ENV_STEP_UTILIZATION, + self.metrics.peek(NUM_ENV_STEPS_PER_SAMPLE_LIFETIME) + / self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + if sampled_n_step: + self.metrics.log_value( + ACTUAL_N_STEP, + sampled_n_step, + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + for aid in agent_to_sampled_n_step: + self.metrics.log_value( + (AGENT_ACTUAL_N_STEP, aid), + agent_to_sampled_n_step[aid], + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + for mid in module_to_sampled_n_step: + self.metrics.log_value( + (MODULE_ACTUAL_N_STEP, mid), + module_to_sampled_n_step[mid], + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + + self.metrics.log_value( + NUM_RESAMPLES, + num_resamples, + reduce="sum", + clear_on_reduce=True, + ) + + # Add per-agent metrics. + for aid in agent_to_num_steps_sampled: + self.metrics.log_value( + (NUM_AGENT_STEPS_SAMPLED, aid), + agent_to_num_steps_sampled[aid], + reduce="sum", + clear_on_reduce=True, + ) + # TODO (simon): Check, if we can then deprecate + # self.sampled_timesteps. + self.metrics.log_value( + (NUM_AGENT_STEPS_SAMPLED_LIFETIME, aid), + agent_to_num_steps_sampled[aid], + reduce="sum", + ) + self.metrics.log_value( + (NUM_AGENT_EPISODES_PER_SAMPLE, aid), + agent_to_num_episodes_per_sample[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_PER_SAMPLE, aid), + agent_to_num_steps_per_sample[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_PER_SAMPLE_LIFETIME, aid), + agent_to_num_steps_per_sample[aid], + reduce="sum", + ) + self.metrics.log_value( + (AGENT_STEP_UTILIZATION, aid), + self.metrics.peek((NUM_AGENT_STEPS_PER_SAMPLE_LIFETIME, aid)) + / self.metrics.peek((NUM_AGENT_STEPS_SAMPLED_LIFETIME, aid)), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + self.metrics.log_value( + (NUM_AGENT_RESAMPLES, aid), + agent_to_num_resamples[aid], + reduce="sum", + clear_on_reduce=True, + ) + # Add per-module metrics. + for mid in module_to_num_steps_sampled: + self.metrics.log_value( + (NUM_MODULE_STEPS_SAMPLED, mid), + module_to_num_steps_sampled[mid], + reduce="sum", + clear_on_reduce=True, + ) + # TODO (simon): Check, if we can then deprecate + # self.sampled_timesteps. + self.metrics.log_value( + (NUM_MODULE_STEPS_SAMPLED_LIFETIME, mid), + module_to_num_steps_sampled[mid], + reduce="sum", + ) + self.metrics.log_value( + (NUM_MODULE_EPISODES_PER_SAMPLE, mid), + module_to_num_episodes_per_sample[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_PER_SAMPLE, mid), + module_to_num_steps_per_sample[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_PER_SAMPLE_LIFETIME, mid), + module_to_num_steps_per_sample[mid], + reduce="sum", + ) + self.metrics.log_value( + (MODULE_STEP_UTILIZATION, mid), + self.metrics.peek((NUM_MODULE_STEPS_PER_SAMPLE_LIFETIME, mid)) + / self.metrics.peek((NUM_MODULE_STEPS_SAMPLED_LIFETIME, mid)), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + self.metrics.log_value( + (NUM_MODULE_RESAMPLES, mid), + module_to_num_resamples[mid], + reduce="sum", + clear_on_reduce=True, + ) + + # TODO (simon): Check, if we can instead peek into the metrics + # and deprecate all variables. + def get_num_episodes(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of episodes (completed or truncated) stored in the buffer.""" + return len(self.episodes) + + def get_num_episodes_evicted(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of episodes that have been evicted from the buffer.""" + return self._num_episodes_evicted + + def get_num_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of individual timesteps stored in the buffer.""" + return len(self._indices) + + def get_sampled_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of timesteps that have been sampled in buffer's lifetime.""" + return self.sampled_timesteps + + def get_added_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of timesteps that have been added in buffer's lifetime.""" + return self._num_timesteps_added + + def get_metrics(self) -> ResultDict: + """Returns the metrics of the buffer and reduces them.""" + return self.metrics.reduce() + + @override(ReplayBufferInterface) + def get_state(self) -> Dict[str, Any]: + """Gets a pickable state of the buffer. + + This is used for checkpointing the buffer's state. It is specifically helpful, + for example, when a trial is paused and resumed later on. The buffer's state + can be saved to disk and reloaded when the trial is resumed. + + Returns: + A dict containing all necessary information to restore the buffer's state. + """ + return { + "episodes": [eps.get_state() for eps in self.episodes], + "episode_id_to_index": list(self.episode_id_to_index.items()), + "_num_episodes_evicted": self._num_episodes_evicted, + "_indices": self._indices, + "_num_timesteps": self._num_timesteps, + "_num_timesteps_added": self._num_timesteps_added, + "sampled_timesteps": self.sampled_timesteps, + } + + @override(ReplayBufferInterface) + def set_state(self, state) -> None: + """Sets the state of a buffer from a previously stored state. + + See `get_state()` for more information on what is stored in the state. This + method is used to restore the buffer's state from a previously stored state. + It is specifically helpful, for example, when a trial is paused and resumed + later on. The buffer's state can be saved to disk and reloaded when the trial + is resumed. + + Args: + state: The state to restore the buffer from. + """ + self._set_episodes(state) + self.episode_id_to_index = dict(state["episode_id_to_index"]) + self._num_episodes_evicted = state["_num_episodes_evicted"] + self._indices = state["_indices"] + self._num_timesteps = state["_num_timesteps"] + self._num_timesteps_added = state["_num_timesteps_added"] + self.sampled_timesteps = state["sampled_timesteps"] + + def _set_episodes(self, state) -> None: + """Sets the episodes from the state. + + Note, this method is used for class inheritance purposes. It is specifically + helpful when a subclass of this class wants to override the behavior of how + episodes are set from the state. By default, it sets `SingleAgentEpuisode`s, + but subclasses can override this method to set episodes of a different type. + """ + if not self.episodes: + self.episodes = deque( + [ + SingleAgentEpisode.from_state(eps_data) + for eps_data in state["episodes"] + ] + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/fifo_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/fifo_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..53fbff25344ccaee729101963e1afb35d8ed229b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/fifo_replay_buffer.py @@ -0,0 +1,109 @@ +import numpy as np +from typing import Any, Dict, Optional + +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer, StorageUnit +from ray.rllib.utils.typing import SampleBatchType +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class FifoReplayBuffer(ReplayBuffer): + """This replay buffer implements a FIFO queue. + + Sometimes, e.g. for offline use cases, it may be desirable to use + off-policy algorithms without a Replay Buffer. + This FifoReplayBuffer can be used in-place to achieve the same effect + without having to introduce separate algorithm execution branches. + + For simplicity and efficiency reasons, this replay buffer stores incoming + sample batches as-is, and returns them one at time. + This is to avoid any additional load when this replay buffer is used. + """ + + def __init__(self, *args, **kwargs): + """Initializes a FifoReplayBuffer. + + Args: + ``*args`` : Forward compatibility args. + ``**kwargs``: Forward compatibility kwargs. + """ + # Completely by-passing underlying ReplayBuffer by setting its + # capacity to 1 (lowest allowed capacity). + ReplayBuffer.__init__(self, 1, StorageUnit.FRAGMENTS, **kwargs) + + self._queue = [] + + @DeveloperAPI + @override(ReplayBuffer) + def add(self, batch: SampleBatchType, **kwargs) -> None: + return self._queue.append(batch) + + @DeveloperAPI + @override(ReplayBuffer) + def sample(self, *args, **kwargs) -> Optional[SampleBatchType]: + """Sample a saved training batch from this buffer. + + Args: + ``*args`` : Forward compatibility args. + ``**kwargs``: Forward compatibility kwargs. + + Returns: + A single training batch from the queue. + """ + if len(self._queue) <= 0: + # Return empty SampleBatch if queue is empty. + return MultiAgentBatch({}, 0) + batch = self._queue.pop(0) + # Equal weights of 1.0. + batch["weights"] = np.ones(len(batch)) + return batch + + @DeveloperAPI + def update_priorities(self, *args, **kwargs) -> None: + """Update priorities of items at given indices. + + No-op for this replay buffer. + + Args: + ``*args`` : Forward compatibility args. + ``**kwargs``: Forward compatibility kwargs. + """ + pass + + @DeveloperAPI + @override(ReplayBuffer) + def stats(self, debug: bool = False) -> Dict: + """Returns the stats of this buffer. + + Args: + debug: If true, adds sample eviction statistics to the returned stats dict. + + Returns: + A dictionary of stats about this buffer. + """ + # As if this replay buffer has never existed. + return {} + + @DeveloperAPI + @override(ReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + # Pass through replay buffer does not save states. + return {} + + @DeveloperAPI + @override(ReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by calling + `self.get_state()`. + """ + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_episode_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_episode_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..391fc0ff955e3c97e8c439b9717cbc33b5413430 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_episode_buffer.py @@ -0,0 +1,1179 @@ +import copy +from collections import defaultdict, deque +from gymnasium.core import ActType, ObsType +import hashlib +import numpy as np +import scipy +from typing import Any, Dict, List, Optional, Set, Tuple, Union + +from ray.rllib.core.columns import Columns +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils.replay_buffers.episode_replay_buffer import EpisodeReplayBuffer +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + DeveloperAPI, + override, +) +from ray.rllib.utils.spaces.space_utils import batch +from ray.rllib.utils.typing import AgentID, ModuleID, SampleBatchType + + +@DeveloperAPI +class MultiAgentEpisodeReplayBuffer(EpisodeReplayBuffer): + """Multi-agent episode replay buffer that stores episodes by their IDs. + + This class implements a replay buffer as used in "playing Atari with Deep + Reinforcement Learning" (Mnih et al., 2013) for multi-agent reinforcement + learning, + + Each "row" (a slot in a deque) in the buffer is occupied by one episode. If an + incomplete episode is added to the buffer and then another chunk of that episode is + added at a later time, the buffer will automatically concatenate the new fragment to + the original episode. This way, episodes can be completed via subsequent `add` + calls. + + Sampling returns a size `B` episode list (number of 'rows'), where each episode + holds a tuple tuple of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation `o_t`, + `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is the sum of + all rewards collected over the time steps between `t+1` and `t+n`. The `n`-step can + be chosen freely when sampling and defaults to `1`. If `n_step` is a tuple it is + sampled uniformly across the interval defined by the tuple (for each row in the + batch). + + Each episode contains - in addition to the data tuples presented above - two further + elements in its `extra_model_outputs`, namely `n_steps` and `weights`. The former + holds the `n_step` used for the sampled timesteps in the episode and the latter the + corresponding (importance sampling) weight for the transition. + + .. testcode:: + + import gymnasium as gym + + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole + from ray.rllib.utils.replay_buffers import MultiAgentEpisodeReplayBuffer + + + # Create the environment. + env = MultiAgentCartPole({"num_agents": 2}) + + # Set up the loop variables + agent_ids = env.agents + agent_ids.append("__all__") + terminateds = {aid: False for aid in agent_ids} + truncateds = {aid: False for aid in agent_ids} + num_timesteps = 10000 + episodes = [] + + # Initialize the first episode entries. + eps = MultiAgentEpisode() + obs, infos = env.reset() + eps.add_env_reset(observations=obs, infos=infos) + + # Sample 10,000 env timesteps. + for i in range(num_timesteps): + # If terminated we create a new episode. + if eps.is_done: + episodes.append(eps.to_numpy()) + eps = MultiAgentEpisode() + terminateds = {aid: False for aid in agent_ids} + truncateds = {aid: False for aid in agent_ids} + obs, infos = env.reset() + eps.add_env_reset(observations=obs, infos=infos) + + # Sample a random action for all agents that should step in the episode + # next. + actions = { + aid: env.get_action_space(aid).sample() + for aid in eps.get_agents_to_act() + } + obs, rewards, terminateds, truncateds, infos = env.step(actions) + eps.add_env_step( + obs, + actions, + rewards, + infos, + terminateds=terminateds, + truncateds=truncateds + ) + + # Add the last (truncated) episode to the list of episodes. + if not eps.is_done: + episodes.append(eps) + + # Create the buffer. + buffer = MultiAgentEpisodeReplayBuffer() + # Add the list of episodes sampled. + buffer.add(episodes) + + # Pull a sample from the buffer using an `n-step` of 3. + sample = buffer.sample(num_items=256, gamma=0.95, n_step=3) + """ + + def __init__( + self, + capacity: int = 10000, + *, + batch_size_B: int = 16, + batch_length_T: int = 1, + metrics_num_episodes_for_smoothing: int = 100, + **kwargs, + ): + """Initializes a multi-agent episode replay buffer. + + Args: + capacity: The total number of timesteps to be storable in this buffer. + Will start ejecting old episodes once this limit is reached. + batch_size_B: The number of episodes returned from `sample()`. + batch_length_T: The length of each episode in the episode list returned from + `sample()`. + """ + # Initialize the base episode replay buffer. + super().__init__( + capacity=capacity, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + metrics_num_episodes_for_smoothing=metrics_num_episodes_for_smoothing, + **kwargs, + ) + + # Stores indices of module (single-agent) timesteps. Each index is a tuple + # of the form: + # `(ma_episode_idx, agent_id, timestep)`. + # This information is stored for each timestep of an episode and is used in + # the `"independent"`` sampling process. The multi-agent episode index amd the + # agent ID are used to retrieve the single-agent episode. The timestep is then + # needed to retrieve the corresponding timestep data from that single-agent + # episode. + self._module_to_indices: Dict[ + ModuleID, List[Tuple[int, AgentID, int]] + ] = defaultdict(list) + + # Stores the number of single-agent timesteps in the buffer. + self._num_agent_timesteps: int = 0 + # Stores the number of single-agent timesteps per module. + self._num_module_timesteps: Dict[ModuleID, int] = defaultdict(int) + + # Stores the number of added single-agent timesteps over the + # lifetime of the buffer. + self._num_agent_timesteps_added: int = 0 + # Stores the number of added single-agent timesteps per module + # over the lifetime of the buffer. + self._num_module_timesteps_added: Dict[ModuleID, int] = defaultdict(int) + + self._num_module_episodes: Dict[ModuleID, int] = defaultdict(int) + # Stores the number of module episodes evicted. Note, this is + # important for indexing. + self._num_module_episodes_evicted: Dict[ModuleID, int] = defaultdict(int) + + # Stores hte number of module timesteps sampled. + self.sampled_timesteps_per_module: Dict[ModuleID, int] = defaultdict(int) + + @override(EpisodeReplayBuffer) + def add( + self, + episodes: Union[List["MultiAgentEpisode"], "MultiAgentEpisode"], + ) -> None: + """Adds episodes to the replay buffer. + + Note, if the incoming episodes' time steps cause the buffer to overflow, + older episodes are evicted. Because episodes usually come in chunks and + not complete, this could lead to edge cases (e.g. with very small capacity + or very long episode length) where the first part of an episode is evicted + while the next part just comes in. + To defend against such case, the complete episode is evicted, including + the new chunk, unless the episode is the only one in the buffer. In the + latter case the buffer will be allowed to overflow in a temporary fashion, + i.e. during the next addition of samples to the buffer an attempt is made + to fall below capacity again. + + The user is advised to select a large enough buffer with regard to the maximum + expected episode length. + + Args: + episodes: The multi-agent episodes to add to the replay buffer. Can be a + single episode or a list of episodes. + """ + episodes: List["MultiAgentEpisode"] = force_list(episodes) + + new_episode_ids: Set[str] = {eps.id_ for eps in episodes} + total_env_timesteps = sum([eps.env_steps() for eps in episodes]) + self._num_timesteps += total_env_timesteps + self._num_timesteps_added += total_env_timesteps + + # Set up some counters for metrics. + num_env_steps_added = 0 + agent_to_num_steps_added = defaultdict(int) + module_to_num_steps_added = defaultdict(int) + num_episodes_added = 0 + agent_to_num_episodes_added = defaultdict(int) + module_to_num_episodes_added = defaultdict(int) + num_episodes_evicted = 0 + agent_to_num_episodes_evicted = defaultdict(int) + module_to_num_episodes_evicted = defaultdict(int) + num_env_steps_evicted = 0 + agent_to_num_steps_evicted = defaultdict(int) + module_to_num_steps_evicted = defaultdict(int) + + # Evict old episodes. + eps_evicted_ids: Set[Union[str, int]] = set() + eps_evicted_idxs: Set[int] = set() + while ( + self._num_timesteps > self.capacity + and self._num_remaining_episodes(new_episode_ids, eps_evicted_ids) != 1 + ): + # Evict episode. + evicted_episode = self.episodes.popleft() + eps_evicted_ids.add(evicted_episode.id_) + eps_evicted_idxs.add(self.episode_id_to_index.pop(evicted_episode.id_)) + # If this episode has a new chunk in the new episodes added, + # we subtract it again. + # TODO (sven, simon): Should we just treat such an episode chunk + # as a new episode? + if evicted_episode.id_ in new_episode_ids: + idx = next( + i + for i, eps in enumerate(episodes) + if eps.id_ == evicted_episode.id_ + ) + new_eps_to_evict = episodes.pop(idx) + self._num_timesteps -= new_eps_to_evict.env_steps() + self._num_timesteps_added -= new_eps_to_evict.env_steps() + # Remove the timesteps of the evicted episode from the counter. + self._num_timesteps -= evicted_episode.env_steps() + self._num_agent_timesteps -= evicted_episode.agent_steps() + self._num_episodes_evicted += 1 + # Increase the counters. + num_episodes_evicted += 1 + num_env_steps_evicted += evicted_episode.env_steps() + for aid, a_eps in evicted_episode.agent_episodes.items(): + mid = evicted_episode._agent_to_module_mapping[aid] + agent_to_num_episodes_evicted[aid] += 1 + module_to_num_episodes_evicted[mid] += 1 + agent_to_num_steps_evicted[aid] += a_eps.agent_steps() + module_to_num_steps_evicted[mid] += a_eps.agent_steps() + # Remove the module timesteps of the evicted episode from the counters. + self._evict_module_episodes(evicted_episode) + del evicted_episode + + # Add agent and module steps. + for eps in episodes: + self._num_agent_timesteps += eps.agent_steps() + self._num_agent_timesteps_added += eps.agent_steps() + # Update the module counters by the module timesteps. + self._update_module_counters(eps) + + # Remove corresponding indices, if episodes were evicted. + if eps_evicted_idxs: + # If the episode is not evicted, we keep the index. + # Note, each index 2-tuple is of the form (ma_episode_idx, timestep) + # and refers to a certain environment timestep in a certain + # multi-agent episode. + self._indices = [ + idx_tuple + for idx_tuple in self._indices + if idx_tuple[0] not in eps_evicted_idxs + ] + # Also remove corresponding module indices. + for module_id, module_indices in self._module_to_indices.items(): + # Each index 3-tuple is of the form + # (ma_episode_idx, agent_id, timestep) and refers to a certain + # agent timestep in a certain multi-agent episode. + self._module_to_indices[module_id] = [ + idx_triplet + for idx_triplet in module_indices + if idx_triplet[0] not in eps_evicted_idxs + ] + + for eps in episodes: + eps = copy.deepcopy(eps) + # If the episode is part of an already existing episode, concatenate. + if eps.id_ in self.episode_id_to_index: + eps_idx = self.episode_id_to_index[eps.id_] + existing_eps = self.episodes[eps_idx - self._num_episodes_evicted] + existing_len = len(existing_eps) + self._indices.extend( + [ + ( + eps_idx, + existing_len + i, + ) + for i in range(len(eps)) + ] + ) + # Add new module indices. + self._add_new_module_indices(eps, eps_idx, True) + # Concatenate the episode chunk. + existing_eps.concat_episode(eps) + # Otherwise, create a new entry. + else: + # New episode. + self.episodes.append(eps) + # Update the counters + num_episodes_added += 1 + for aid, a_eps in eps.agent_episodes.items(): + mid = eps._agent_to_module_mapping[aid] + agent_to_num_episodes_added[aid] += 1 + module_to_num_episodes_added[mid] += 1 + eps_idx = len(self.episodes) - 1 + self._num_episodes_evicted + self.episode_id_to_index[eps.id_] = eps_idx + self._indices.extend([(eps_idx, i) for i in range(len(eps))]) + # Add new module indices. + self._add_new_module_indices(eps, eps_idx, False) + # Update the step counters. + num_env_steps_added += eps.env_steps() + for aid, e_eps in eps.agent_episodes.items(): + mid = eps._agent_to_module_mapping[aid] + agent_to_num_steps_added[aid] += e_eps.agent_steps() + module_to_num_steps_added[mid] += e_eps.agent_steps() + + # Update the adding metrics. + self._update_add_metrics( + num_episodes_added=num_episodes_added, + num_env_steps_added=num_env_steps_added, + num_episodes_evicted=num_episodes_evicted, + num_env_steps_evicted=num_env_steps_evicted, + agent_to_num_episodes_added=agent_to_num_episodes_added, + agent_to_num_steps_added=agent_to_num_steps_added, + agent_to_num_episodes_evicted=agent_to_num_episodes_evicted, + agent_to_num_steps_evicted=agent_to_num_steps_evicted, + module_to_num_episodes_added=module_to_num_steps_added, + module_to_num_steps_added=module_to_num_episodes_added, + module_to_num_episodes_evicted=module_to_num_episodes_evicted, + module_to_num_steps_evicted=module_to_num_steps_evicted, + ) + + @override(EpisodeReplayBuffer) + def sample( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = 1, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + replay_mode: str = "independent", + modules_to_sample: Optional[List[ModuleID]] = None, + **kwargs, + ) -> Union[List["MultiAgentEpisode"], List["SingleAgentEpisode"]]: + """Samples a batch of multi-agent transitions. + + Multi-agent transitions can be sampled either `"independent"` or + `"synchronized"` with the former sampling for each module independent agent + steps and the latter sampling agent transitions from the same environment step. + + The n-step parameter can be either a single integer or a tuple of two integers. + In the former case, the n-step is fixed to the given integer and in the latter + case, the n-step is sampled uniformly from the given range. Large n-steps could + potentially lead to a many retries because not all samples might have a full + n-step transition. + + Sampling returns batches of size B (number of 'rows'), where each row is a tuple + of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation + `o_t`, `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is + the sum of all rewards collected over the time steps between `t+1` and `t+n`. + The n`-step can be chosen freely when sampling and defaults to `1`. If `n_step` + is a tuple it is sampled uniformly across the interval defined by the tuple (for + each row in the batch). + + Each batch contains - in addition to the data tuples presented above - two + further columns, namely `n_steps` and `weigths`. The former holds the `n_step` + used for each row in the batch and the latter a (default) weight of `1.0` for + each row in the batch. This weight is used for weighted loss calculations in + the training process. + + Args: + num_items: The number of items to sample. If provided, `batch_size_B` + should be `None`. + batch_size_B: The batch size to sample. If provided, `num_items` + should be `None`. + batch_length_T: The length of the sampled batch. If not provided, the + default batch length is used. This feature is not yet implemented. + n_step: The n-step to sample. If the n-step is a tuple, the n-step is + sampled uniformly from the given range. If not provided, the default + n-step of `1` is used. + gamma: The discount factor for the n-step reward calculation. + include_infos: Whether to include the infos in the sampled batch. + include_extra_model_outputs: Whether to include the extra model outputs + in the sampled batch. + replay_mode: The replay mode to use for sampling. Either `"independent"` + or `"synchronized"`. + modules_to_sample: A list of module IDs to sample from. If not provided, + transitions for aall modules are sampled. + + Returns: + A dictionary of the form `ModuleID -> SampleBatchType` containing the + sampled data for each module or each module in `modules_to_sample`, + if provided. + """ + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + # TODO (simon): Implement trajectory sampling for RNNs. + batch_length_T = batch_length_T or self.batch_length_T + + # Sample for each module independently. + if replay_mode == "independent": + return self._sample_independent( + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + modules_to_sample=modules_to_sample, + ) + else: + return self._sample_synchonized( + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + modules_to_sample=modules_to_sample, + ) + + def get_added_agent_timesteps(self) -> int: + """Returns number of agent timesteps that have been added in buffer's lifetime. + + Note, this could be more than the `get_added_timesteps` returns as an + environment timestep could contain multiple agent timesteps (for eaxch agent + one). + """ + return self._num_agent_timesteps_added + + def get_module_ids(self) -> List[ModuleID]: + """Returns a list of module IDs stored in the buffer.""" + return list(self._module_to_indices.keys()) + + def get_num_agent_timesteps(self) -> int: + """Returns number of agent timesteps stored in the buffer. + + Note, this could be more than the `num_timesteps` as an environment timestep + could contain multiple agent timesteps (for eaxch agent one). + """ + return self._num_agent_timesteps + + @override(EpisodeReplayBuffer) + def get_num_episodes(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of episodes stored for a module in the buffer. + + Note, episodes could be either complete or truncated. + + Args: + module_id: The ID of the module to query. If not provided, the number of + episodes for all modules is returned. + + Returns: + The number of episodes stored for the module or all modules. + """ + return ( + self._num_module_episodes[module_id] + if module_id + else super().get_num_episodes() + ) + + @override(EpisodeReplayBuffer) + def get_num_episodes_evicted(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of episodes evicted for a module in the buffer.""" + return ( + self._num_module_episodes_evicted[module_id] + if module_id + else super().get_num_episodes_evicted() + ) + + @override(EpisodeReplayBuffer) + def get_num_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of individual timesteps for a module stored in the buffer. + + Args: + module_id: The ID of the module to query. If not provided, the number of + timesteps for all modules are returned. + + Returns: + The number of timesteps stored for the module or all modules. + """ + return ( + self._num_module_timesteps[module_id] + if module_id + else super().get_num_timesteps() + ) + + @override(EpisodeReplayBuffer) + def get_sampled_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of timesteps that have been sampled for a module. + + Args: + module_id: The ID of the module to query. If not provided, the number of + sampled timesteps for all modules are returned. + + Returns: + The number of timesteps sampled for the module or all modules. + """ + return ( + self.sampled_timesteps_per_module[module_id] + if module_id + else super().get_sampled_timesteps() + ) + + @override(EpisodeReplayBuffer) + def get_added_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns the number of timesteps added in buffer's lifetime for given module. + + Args: + module_id: The ID of the module to query. If not provided, the total number + of timesteps ever added. + + Returns: + The number of timesteps added for `module_id` (or all modules if `module_id` + is None). + """ + return ( + self._num_module_timesteps_added[module_id] + if module_id + else super().get_added_timesteps() + ) + + @override(EpisodeReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Gets a pickable state of the buffer. + + This is used for checkpointing the buffer's state. It is specifically helpful, + for example, when a trial is paused and resumed later on. The buffer's state + can be saved to disk and reloaded when the trial is resumed. + + Returns: + A dict containing all necessary information to restore the buffer's state. + """ + return super().get_state() | { + "_module_to_indices": list(self._module_to_indices.items()), + "_num_agent_timesteps": self._num_agent_timesteps, + "_num_agent_timesteps_added": self._num_agent_timesteps_added, + "_num_module_timesteps": list(self._num_module_timesteps.items()), + "_num_module_timesteps_added": list( + self._num_module_timesteps_added.items() + ), + "_num_module_episodes": list(self._num_module_episodes.items()), + "_num_module_episodes_evicted": list( + self._num_module_episodes_evicted.items() + ), + "sampled_timesteps_per_module": list( + self.sampled_timesteps_per_module.items() + ), + } + + @override(EpisodeReplayBuffer) + def set_state(self, state) -> None: + """Sets the state of a buffer from a previously stored state. + + See `get_state()` for more information on what is stored in the state. This + method is used to restore the buffer's state from a previously stored state. + It is specifically helpful, for example, when a trial is paused and resumed + later on. The buffer's state can be saved to disk and reloaded when the trial + is resumed. + + Args: + state: The state to restore the buffer from. + """ + # Set the episodes. + self._set_episodes(state) + # Set the super's state. + super().set_state(state) + # Now set the remaining attributes. + self._module_to_indices = defaultdict(list, dict(state["_module_to_indices"])) + self._num_agent_timesteps = state["_num_agent_timesteps"] + self._num_agent_timesteps_added = state["_num_agent_timesteps_added"] + self._num_module_timesteps = defaultdict( + int, dict(state["_num_module_timesteps"]) + ) + self._num_module_timesteps_added = defaultdict( + int, dict(state["_num_module_timesteps_added"]) + ) + self._num_module_episodes = defaultdict( + int, dict(state["_num_module_episodes"]) + ) + self._num_module_episodes_evicted = defaultdict( + int, dict(state["_num_module_episodes_evicted"]) + ) + self.sampled_timesteps_per_module = defaultdict( + list, dict(state["sampled_timesteps_per_module"]) + ) + + def _set_episodes(self, state: Dict[str, Any]) -> None: + """Sets the episodes from the state.""" + if not self.episodes: + self.episodes = deque( + [ + MultiAgentEpisode.from_state(eps_data) + for eps_data in state["episodes"] + ] + ) + + def _sample_independent( + self, + batch_size_B: Optional[int], + batch_length_T: Optional[int], + n_step: Optional[Union[int, Tuple[int, int]]], + gamma: float, + include_infos: bool, + include_extra_model_outputs: bool, + modules_to_sample: Optional[Set[ModuleID]], + ) -> List["SingleAgentEpisode"]: + """Samples a batch of independent multi-agent transitions.""" + + actual_n_step = n_step or 1 + # Sample the n-step if necessary. + random_n_step = isinstance(n_step, (tuple, list)) + + sampled_episodes = [] + # Record the number of samples per module/agent/total. + num_env_steps_sampled = 0 + agent_to_num_steps_sampled = defaultdict(int) + module_to_num_steps_sampled = defaultdict(int) + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + agent_to_sampled_env_step_idxs = defaultdict(set) + module_to_sampled_env_step_idxs = defaultdict(set) + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + agent_to_sampled_episode_idxs = defaultdict(set) + module_to_sampled_episode_idxs = defaultdict(set) + # Record all n-steps that have been used. + sampled_n_steps = [] + agent_to_sampled_n_steps = defaultdict(list) + module_to_sampled_n_steps = defaultdict(list) + # Record the number of times a sample needs to be resampled. + num_resamples = 0 + agent_to_num_resamples = defaultdict(int) + module_to_num_resamples = defaultdict(int) + + # TODO (simon): Ensure that the module has data and if not, skip it. + # TODO (sven): Should we then error out or skip? I think the Learner + # should handle this case when a module has no train data. + modules_to_sample = modules_to_sample or set(self._module_to_indices.keys()) + for module_id in modules_to_sample: + module_indices = self._module_to_indices[module_id] + B = 0 + while B < batch_size_B: + # Now sample from the single-agent timesteps. + index_tuple = module_indices[self.rng.integers(len(module_indices))] + + # This will be an agent timestep (not env timestep). + # TODO (simon, sven): Maybe deprecate sa_episode_idx (_) in the index + # quads. Is there any need for it? + ma_episode_idx, agent_id, sa_episode_ts = ( + index_tuple[0] - self._num_episodes_evicted, + index_tuple[1], + index_tuple[2], + ) + + # Get the multi-agent episode. + ma_episode = self.episodes[ma_episode_idx] + # Retrieve the single-agent episode for filtering. + sa_episode = ma_episode.agent_episodes[agent_id] + + # If we use random n-step sampling, draw the n-step for this item. + if random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + # If we cannnot make the n-step, we resample. + if sa_episode_ts + actual_n_step > len(sa_episode): + num_resamples += 1 + agent_to_num_resamples[agent_id] += 1 + module_to_num_resamples[module_id] += 1 + continue + # Note, this will be the reward after executing action + # `a_(episode_ts)`. For `n_step>1` this will be the discounted sum + # of all rewards that were collected over the last n steps. + sa_raw_rewards = sa_episode.get_rewards( + slice(sa_episode_ts, sa_episode_ts + actual_n_step) + ) + sa_rewards = scipy.signal.lfilter( + [1], [1, -gamma], sa_raw_rewards[::-1], axis=0 + )[-1] + + sampled_sa_episode = SingleAgentEpisode( + id_=sa_episode.id_, + # Provide the IDs for the learner connector. + agent_id=sa_episode.agent_id, + module_id=sa_episode.module_id, + multi_agent_episode_id=ma_episode.id_, + # Ensure that each episode contains a tuple of the form: + # (o_t, a_t, sum(r_(t:t+n_step)), o_(t+n_step)) + # Two observations (t and t+n). + observations=[ + sa_episode.get_observations(sa_episode_ts), + sa_episode.get_observations(sa_episode_ts + actual_n_step), + ], + observation_space=sa_episode.observation_space, + infos=( + [ + sa_episode.get_infos(sa_episode_ts), + sa_episode.get_infos(sa_episode_ts + actual_n_step), + ] + if include_infos + else None + ), + actions=[sa_episode.get_actions(sa_episode_ts)], + action_space=sa_episode.action_space, + rewards=[sa_rewards], + # If the sampled single-agent episode is the single-agent episode's + # last time step, check, if the single-agent episode is terminated + # or truncated. + terminated=( + sa_episode_ts + actual_n_step >= len(sa_episode) + and sa_episode.is_terminated + ), + truncated=( + sa_episode_ts + actual_n_step >= len(sa_episode) + and sa_episode.is_truncated + ), + extra_model_outputs={ + "weights": [1.0], + "n_step": [actual_n_step], + **( + { + k: [ + sa_episode.get_extra_model_outputs(k, sa_episode_ts) + ] + for k in sa_episode.extra_model_outputs.keys() + } + if include_extra_model_outputs + else {} + ), + }, + # TODO (sven): Support lookback buffers. + len_lookback_buffer=0, + t_started=sa_episode_ts, + ) + # Append single-agent episode to the list of sampled episodes. + sampled_episodes.append(sampled_sa_episode) + # Add the episode indices. + sampled_episode_idxs.add(ma_episode_idx) + agent_to_sampled_episode_idxs[sa_episode.agent_id].add(sa_episode.id_) + module_to_sampled_episode_idxs[module_id].add(sa_episode.id_) + # Add the unique step hashes. + # Get the corresponding index in the `env_to_agent_t` mapping. + # TODO (simon, sven): This has complexity O(n) and could become + # expensive when the episode is large. Note, however, that conversion + # from list to `numpy.ndarray` is also complexity O(n) and we do this + # at many places - also in the `MultiAgentEpisode`s. + ma_episode_ts = ma_episode.env_t_to_agent_t[agent_id].data.index( + sa_episode_ts + ) + sampled_env_step_idxs.add( + hashlib.sha256( + f"{ma_episode.id_}-{ma_episode_ts}".encode() + ).hexdigest() + ) + hashed_agent_step = hashlib.sha256( + f"{sa_episode.id_}-{sa_episode_ts}".encode() + ).hexdigest() + agent_to_sampled_env_step_idxs[agent_id].add(hashed_agent_step) + module_to_sampled_env_step_idxs[module_id].add(hashed_agent_step) + # Add the actual n-step used in generating this sample. + sampled_n_steps.append(actual_n_step) + agent_to_sampled_n_steps[agent_id].append(actual_n_step) + module_to_sampled_n_steps[module_id].append(actual_n_step) + + # Increase counter. + B += 1 + + # Increase the per module timesteps counter. + self.sampled_timesteps_per_module[module_id] += B + # Increase the counter metrics. + num_env_steps_sampled += B + agent_to_num_steps_sampled[agent_id] += B + module_to_num_steps_sampled[module_id] += B + + # Increase the counter for environment timesteps. + self.sampled_timesteps += batch_size_B + + # Update the sample metrics. + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + sampled_n_step = sum(sampled_n_steps) / batch_size_B + agent_to_num_episodes_per_sample = { + aid: len(l) for aid, l in agent_to_sampled_episode_idxs.items() + } + module_to_num_episodes_per_sample = { + mid: len(l) for mid, l in module_to_sampled_episode_idxs.items() + } + agent_to_num_steps_per_sample = { + aid: len(l) for aid, l in agent_to_sampled_env_step_idxs.items() + } + module_to_num_steps_per_sample = { + mid: len(l) for mid, l in module_to_sampled_env_step_idxs.items() + } + agent_to_sampled_n_step = { + aid: sum(l) / len(l) for aid, l in agent_to_sampled_n_steps.items() + } + module_to_sampled_n_step = { + mid: sum(l) / len(l) for mid, l in module_to_sampled_n_steps.items() + } + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + sampled_n_step=sampled_n_step, + num_resamples=num_resamples, + agent_to_num_steps_sampled=agent_to_num_steps_sampled, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_sampled_n_step=agent_to_sampled_n_step, + agent_to_num_resamples=agent_to_num_resamples, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_sampled_n_step=module_to_sampled_n_step, + module_to_num_resamples=module_to_num_resamples, + ) + + # Return multi-agent dictionary. + return sampled_episodes + + def _sample_synchonized( + self, + batch_size_B: Optional[int], + batch_length_T: Optional[int], + n_step: Optional[Union[int, Tuple]], + gamma: float, + include_infos: bool, + include_extra_model_outputs: bool, + modules_to_sample: Optional[List[ModuleID]], + ) -> SampleBatchType: + """Samples a batch of synchronized multi-agent transitions.""" + # Sample the n-step if necessary. + if isinstance(n_step, tuple): + # Use random n-step sampling. + random_n_step = True + else: + actual_n_step = n_step or 1 + random_n_step = False + + # Containers for the sampled data. + observations: Dict[ModuleID, List[ObsType]] = defaultdict(list) + next_observations: Dict[ModuleID, List[ObsType]] = defaultdict(list) + actions: Dict[ModuleID, List[ActType]] = defaultdict(list) + rewards: Dict[ModuleID, List[float]] = defaultdict(list) + is_terminated: Dict[ModuleID, List[bool]] = defaultdict(list) + is_truncated: Dict[ModuleID, List[bool]] = defaultdict(list) + weights: Dict[ModuleID, List[float]] = defaultdict(list) + n_steps: Dict[ModuleID, List[int]] = defaultdict(list) + # If `info` should be included, construct also a container for them. + if include_infos: + infos: Dict[ModuleID, List[Dict[str, Any]]] = defaultdict(list) + # If `extra_model_outputs` should be included, construct a container for them. + if include_extra_model_outputs: + extra_model_outputs: Dict[ModuleID, List[Dict[str, Any]]] = defaultdict( + list + ) + + B = 0 + while B < batch_size_B: + index_tuple = self._indices[self.rng.integers(len(self._indices))] + + # This will be an env timestep (not agent timestep) + ma_episode_idx, ma_episode_ts = ( + index_tuple[0] - self._num_episodes_evicted, + index_tuple[1], + ) + # If we use random n-step sampling, draw the n-step for this item. + if random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + # If we are at the end of an episode, continue. + # Note, priority sampling got us `o_(t+n)` and we need for the loss + # calculation in addition `o_t`. + # TODO (simon): Maybe introduce a variable `num_retries` until the + # while loop should break when not enough samples have been collected + # to make n-step possible. + if ma_episode_ts - actual_n_step < 0: + continue + + # Retrieve the multi-agent episode. + ma_episode = self.episodes[ma_episode_idx] + + # Ensure that each row contains a tuple of the form: + # (o_t, a_t, sum(r_(t:t+n_step)), o_(t+n_step)) + # TODO (simon): Implement version for sequence sampling when using RNNs. + eps_observation = ma_episode.get_observations( + slice(ma_episode_ts - actual_n_step, ma_episode_ts + 1), + return_list=True, + ) + # Note, `MultiAgentEpisode` stores the action that followed + # `o_t` with `o_(t+1)`, therefore, we need the next one. + # TODO (simon): This gets the wrong action as long as the getters are not + # fixed. + eps_actions = ma_episode.get_actions(ma_episode_ts - actual_n_step) + # Make sure that at least a single agent should have full transition. + # TODO (simon): Filter for the `modules_to_sample`. + agents_to_sample = self._agents_with_full_transitions( + eps_observation, + eps_actions, + ) + # If not, we resample. + if not agents_to_sample: + continue + # TODO (simon, sven): Do we need to include the common agent rewards? + # Note, the reward that is collected by transitioning from `o_t` to + # `o_(t+1)` is stored in the next transition in `MultiAgentEpisode`. + eps_rewards = ma_episode.get_rewards( + slice(ma_episode_ts - actual_n_step, ma_episode_ts), + return_list=True, + ) + # TODO (simon, sven): Do we need to include the common infos? And are + # there common extra model outputs? + if include_infos: + # If infos are included we include the ones from the last timestep + # as usually the info contains additional values about the last state. + eps_infos = ma_episode.get_infos(ma_episode_ts) + if include_extra_model_outputs: + # If `extra_model_outputs` are included we include the ones from the + # first timestep as usually the `extra_model_outputs` contain additional + # values from the forward pass that produced the action at the first + # timestep. + # Note, we extract them into single row dictionaries similar to the + # infos, in a connector we can then extract these into single batch + # rows. + eps_extra_model_outputs = { + k: ma_episode.get_extra_model_outputs( + k, ma_episode_ts - actual_n_step + ) + for k in ma_episode.extra_model_outputs.keys() + } + # If the sampled time step is the episode's last time step check, if + # the episode is terminated or truncated. + episode_terminated = False + episode_truncated = False + if ma_episode_ts == ma_episode.env_t: + episode_terminated = ma_episode.is_terminated + episode_truncated = ma_episode.is_truncated + # TODO (simon): Filter for the `modules_to_sample`. + # TODO (sven, simon): We could here also sample for all agents in the + # `modules_to_sample` and then adapt the `n_step` for agents that + # have not a full transition. + for agent_id in agents_to_sample: + # Map our agent to the corresponding module we want to + # train. + module_id = ma_episode._agent_to_module_mapping[agent_id] + # Sample only for the modules in `modules_to_sample`. + if module_id not in ( + modules_to_sample or self._module_to_indices.keys() + ): + continue + # TODO (simon, sven): Here we could skip for modules not + # to be sampled in `modules_to_sample`. + observations[module_id].append(eps_observation[0][agent_id]) + next_observations[module_id].append(eps_observation[-1][agent_id]) + # Fill missing rewards with zeros. + agent_rewards = [r[agent_id] or 0.0 for r in eps_rewards] + rewards[module_id].append( + scipy.signal.lfilter([1], [1, -gamma], agent_rewards[::-1], axis=0)[ + -1 + ] + ) + # Note, this should exist, as we filtered for agents with full + # transitions. + actions[module_id].append(eps_actions[agent_id]) + if include_infos: + infos[module_id].append(eps_infos[agent_id]) + if include_extra_model_outputs: + extra_model_outputs[module_id].append( + { + k: eps_extra_model_outputs[agent_id][k] + for k in eps_extra_model_outputs[agent_id].keys() + } + ) + # If sampled observation is terminal for the agent. Either MAE + # episode is truncated/terminated or SAE episode is truncated/ + # terminated at this ts. + # TODO (simon, sven): Add method agent_alive(ts) to MAE. + # or add slicing to get_terminateds(). + agent_ts = ma_episode.env_t_to_agent_t[agent_id][ma_episode_ts] + agent_eps = ma_episode.agent_episodes[agent_id] + agent_terminated = agent_ts == agent_eps.t and agent_eps.is_terminated + agent_truncated = ( + agent_ts == agent_eps.t + and agent_eps.is_truncated + and not agent_eps.is_terminated + ) + if episode_terminated or agent_terminated: + is_terminated[module_id].append(True) + is_truncated[module_id].append(False) + elif episode_truncated or agent_truncated: + is_truncated[module_id].append(True) + is_terminated[module_id].append(False) + else: + is_terminated[module_id].append(False) + is_truncated[module_id].append(False) + # Increase the per module counter. + self.sampled_timesteps_per_module[module_id] += 1 + + # Increase counter. + B += 1 + # Increase the counter for environment timesteps. + self.sampled_timesteps += batch_size_B + + # Should be convertible to MultiAgentBatch. + ret = { + **{ + module_id: { + Columns.OBS: batch(observations[module_id]), + Columns.ACTIONS: batch(actions[module_id]), + Columns.REWARDS: np.array(rewards[module_id]), + Columns.NEXT_OBS: batch(next_observations[module_id]), + Columns.TERMINATEDS: np.array(is_terminated[module_id]), + Columns.TRUNCATEDS: np.array(is_truncated[module_id]), + "weights": np.array(weights[module_id]), + "n_step": np.array(n_steps[module_id]), + } + for module_id in observations.keys() + } + } + + # Return multi-agent dictionary. + return ret + + def _num_remaining_episodes(self, new_eps, evicted_eps): + """Calculates the number of remaining episodes. + + When adding episodes and evicting them in the `add()` method + this function calculates iteratively the number of remaining + episodes. + + Args: + new_eps: List of new episode IDs. + evicted_eps: List of evicted episode IDs. + + Returns: + Number of episodes remaining after evicting the episodes in + `evicted_eps` and adding the episode in `new_eps`. + """ + return len( + set(self.episode_id_to_index.keys()).union(set(new_eps)) - set(evicted_eps) + ) + + def _evict_module_episodes(self, ma_episode: MultiAgentEpisode) -> None: + """Evicts the module episodes from the buffer adn updates all counters. + + Args: + multi_agent_eps: The multi-agent episode to evict from the buffer. + """ + + # Note we need to take the agent ids from the evicted episode because + # different episodes can have different agents and module mappings. + for agent_id in ma_episode.agent_episodes: + # Retrieve the corresponding module ID and module episode. + module_id = ma_episode._agent_to_module_mapping[agent_id] + module_eps = ma_episode.agent_episodes[agent_id] + # Update all counters. + self._num_module_timesteps[module_id] -= module_eps.env_steps() + self._num_module_episodes[module_id] -= 1 + self._num_module_episodes_evicted[module_id] += 1 + + def _update_module_counters(self, ma_episode: MultiAgentEpisode) -> None: + """Updates the module counters after adding an episode. + + Args: + multi_agent_episode: The multi-agent episode to update the module counters + for. + """ + for agent_id in ma_episode.agent_ids: + agent_steps = ma_episode.agent_episodes[agent_id].env_steps() + # Only add if the agent has stepped in the episode (chunk). + if agent_steps > 0: + # Receive the corresponding module ID. + module_id = ma_episode.module_for(agent_id) + self._num_module_timesteps[module_id] += agent_steps + self._num_module_timesteps_added[module_id] += agent_steps + # if ma_episode.agent_episodes[agent_id].is_done: + # # TODO (simon): Check, if we do not count the same episode + # # multiple times. + # # Also add to the module episode counter. + # self._num_module_episodes[module_id] += 1 + + def _add_new_module_indices( + self, + ma_episode: MultiAgentEpisode, + episode_idx: int, + ma_episode_exists: bool = True, + ) -> None: + """Adds the module indices for new episode chunks. + + Args: + ma_episode: The multi-agent episode to add the module indices for. + episode_idx: The index of the episode in the `self.episodes`. + ma_episode_exists: Whether `ma_episode` is already in this buffer (with a + predecessor chunk to which we'll concatenate `ma_episode` later). + """ + existing_ma_episode = None + if ma_episode_exists: + existing_ma_episode = self.episodes[ + self.episode_id_to_index[ma_episode.id_] - self._num_episodes_evicted + ] + + # Note, we iterate through the agent episodes b/c we want to store records + # and some agents could not have entered the environment. + for agent_id in ma_episode.agent_episodes: + # Get the corresponding module id. + module_id = ma_episode.module_for(agent_id) + # Get the module episode. + module_eps = ma_episode.agent_episodes[agent_id] + + # Is the agent episode already in the buffer's existing `ma_episode`? + if ma_episode_exists and agent_id in existing_ma_episode.agent_episodes: + existing_sa_eps_len = len(existing_ma_episode.agent_episodes[agent_id]) + # Otherwise, it is a new single-agent episode and we increase the counter. + else: + existing_sa_eps_len = 0 + self._num_module_episodes[module_id] += 1 + + # Add new module indices. + self._module_to_indices[module_id].extend( + [ + ( + # Keep the MAE index for sampling + episode_idx, + agent_id, + existing_sa_eps_len + i, + ) + for i in range(len(module_eps)) + ] + ) + + def _agents_with_full_transitions( + self, observations: Dict[AgentID, ObsType], actions: Dict[AgentID, ActType] + ): + """Filters for agents that have full transitions. + + Args: + observations: The observations of the episode. + actions: The actions of the episode. + + Returns: + List of agent IDs that have full transitions. + """ + agents_to_sample = [] + for agent_id in observations[0].keys(): + # Only if the agent has an action at the first and an observation + # at the first and last timestep of the n-step transition, we can sample it. + if agent_id in actions and agent_id in observations[-1]: + agents_to_sample.append(agent_id) + return agents_to_sample diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_mixin_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_mixin_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..4c406f36ed081a03b4df01db8edb48c114adb55f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_mixin_replay_buffer.py @@ -0,0 +1,404 @@ +import collections +import logging +import random +from typing import Any, Dict, Optional + +import numpy as np + +from ray.rllib.policy.rnn_sequencing import timeslice_along_seq_lens_with_overlap +from ray.rllib.policy.sample_batch import ( + DEFAULT_POLICY_ID, + SampleBatch, + concat_samples_into_ma_batch, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.replay_buffers.multi_agent_prioritized_replay_buffer import ( + MultiAgentPrioritizedReplayBuffer, +) +from ray.rllib.utils.replay_buffers.multi_agent_replay_buffer import ( + MultiAgentReplayBuffer, + ReplayMode, + merge_dicts_with_warning, +) +from ray.rllib.utils.replay_buffers.replay_buffer import _ALL_POLICIES, StorageUnit +from ray.rllib.utils.typing import PolicyID, SampleBatchType +from ray.util.annotations import DeveloperAPI +from ray.util.debug import log_once + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class MultiAgentMixInReplayBuffer(MultiAgentPrioritizedReplayBuffer): + """This buffer adds replayed samples to a stream of new experiences. + + - Any newly added batch (`add()`) is immediately returned upon + the next `sample` call (close to on-policy) as well as being moved + into the buffer. + - Additionally, a certain number of old samples is mixed into the + returned sample according to a given "replay ratio". + - If >1 calls to `add()` are made without any `sample()` calls + in between, all newly added batches are returned (plus some older samples + according to the "replay ratio"). + + .. testcode:: + :skipif: True + + # replay ratio 0.66 (2/3 replayed, 1/3 new samples): + buffer = MultiAgentMixInReplayBuffer(capacity=100, + replay_ratio=0.66) + buffer.add() + buffer.add() + buffer.sample(1) + + .. testoutput:: + + ..[, , ] + + .. testcode:: + :skipif: True + + buffer.add() + buffer.sample(1) + + .. testoutput:: + + [, , ] + or: [, , ], [, , ] or [, , ], + but always as it is the newest sample + + .. testcode:: + :skipif: True + + buffer.add() + buffer.sample(1) + + .. testoutput:: + + [, , ] + or [, , ], [, , ] or [, , ], etc.. + but always as it is the newest sample + + .. testcode:: + :skipif: True + + # replay proportion 0.0 -> replay disabled: + buffer = MixInReplay(capacity=100, replay_ratio=0.0) + buffer.add() + buffer.sample() + + .. testoutput:: + + [] + + .. testcode:: + :skipif: True + + buffer.add() + buffer.sample() + + .. testoutput:: + + [] + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: str = "timesteps", + num_shards: int = 1, + replay_mode: str = "independent", + replay_sequence_override: bool = True, + replay_sequence_length: int = 1, + replay_burn_in: int = 0, + replay_zero_init_states: bool = True, + replay_ratio: float = 0.66, + underlying_buffer_config: dict = None, + prioritized_replay_alpha: float = 0.6, + prioritized_replay_beta: float = 0.4, + prioritized_replay_eps: float = 1e-6, + **kwargs, + ): + """Initializes MultiAgentMixInReplayBuffer instance. + + Args: + capacity: The capacity of the buffer, measured in `storage_unit`. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. If they + are stored in episodes, replay_sequence_length is ignored. + num_shards: The number of buffer shards that exist in total + (including this one). + replay_mode: One of "independent" or "lockstep". Determines, + whether batches are sampled independently or to an equal + amount. + replay_sequence_override: If True, ignore sequences found in incoming + batches, slicing them into sequences as specified by + `replay_sequence_length` and `replay_sequence_burn_in`. This only has + an effect if storage_unit is `sequences`. + replay_sequence_length: The sequence length (T) of a single + sample. If > 1, we will sample B x T from this buffer. This + only has an effect if storage_unit is 'timesteps'. + replay_burn_in: The burn-in length in case + `replay_sequence_length` > 0. This is the number of timesteps + each sequence overlaps with the previous one to generate a + better internal state (=state after the burn-in), instead of + starting from 0.0 each RNN rollout. + replay_zero_init_states: Whether the initial states in the + buffer (if replay_sequence_length > 0) are alwayas 0.0 or + should be updated with the previous train_batch state outputs. + replay_ratio: Ratio of replayed samples in the returned + batches. E.g. a ratio of 0.0 means only return new samples + (no replay), a ratio of 0.5 means always return newest sample + plus one old one (1:1), a ratio of 0.66 means always return + the newest sample plus 2 old (replayed) ones (1:2), etc... + underlying_buffer_config: A config that contains all necessary + constructor arguments and arguments for methods to call on + the underlying buffers. This replaces the standard behaviour + of the underlying PrioritizedReplayBuffer. The config + follows the conventions of the general + replay_buffer_config. kwargs for subsequent calls of methods + may also be included. Example: + "replay_buffer_config": {"type": PrioritizedReplayBuffer, + "capacity": 10, "storage_unit": "timesteps", + prioritized_replay_alpha: 0.5, prioritized_replay_beta: 0.5, + prioritized_replay_eps: 0.5} + prioritized_replay_alpha: Alpha parameter for a prioritized + replay buffer. Use 0.0 for no prioritization. + prioritized_replay_beta: Beta parameter for a prioritized + replay buffer. + prioritized_replay_eps: Epsilon parameter for a prioritized + replay buffer. + **kwargs: Forward compatibility kwargs. + """ + if not 0 <= replay_ratio <= 1: + raise ValueError("Replay ratio must be within [0, 1]") + + MultiAgentPrioritizedReplayBuffer.__init__( + self, + capacity=capacity, + storage_unit=storage_unit, + num_shards=num_shards, + replay_mode=replay_mode, + replay_sequence_override=replay_sequence_override, + replay_sequence_length=replay_sequence_length, + replay_burn_in=replay_burn_in, + replay_zero_init_states=replay_zero_init_states, + underlying_buffer_config=underlying_buffer_config, + prioritized_replay_alpha=prioritized_replay_alpha, + prioritized_replay_beta=prioritized_replay_beta, + prioritized_replay_eps=prioritized_replay_eps, + **kwargs, + ) + + self.replay_ratio = replay_ratio + + self.last_added_batches = collections.defaultdict(list) + + @DeveloperAPI + @override(MultiAgentPrioritizedReplayBuffer) + def add(self, batch: SampleBatchType, **kwargs) -> None: + """Adds a batch to the appropriate policy's replay buffer. + + Turns the batch into a MultiAgentBatch of the DEFAULT_POLICY_ID if + it is not a MultiAgentBatch. Subsequently, adds the individual policy + batches to the storage. + + Args: + batch: The batch to be added. + **kwargs: Forward compatibility kwargs. + """ + # Make a copy so the replay buffer doesn't pin plasma memory. + batch = batch.copy() + # Handle everything as if multi-agent. + batch = batch.as_multi_agent() + + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + pids_and_batches = self._maybe_split_into_policy_batches(batch) + + # We need to split batches into timesteps, sequences or episodes + # here already to properly keep track of self.last_added_batches + # underlying buffers should not split up the batch any further + with self.add_batch_timer: + if self.storage_unit == StorageUnit.TIMESTEPS: + for policy_id, sample_batch in pids_and_batches.items(): + timeslices = sample_batch.timeslices(1) + for time_slice in timeslices: + self.replay_buffers[policy_id].add(time_slice, **kwargs) + self.last_added_batches[policy_id].append(time_slice) + + elif self.storage_unit == StorageUnit.SEQUENCES: + for policy_id, sample_batch in pids_and_batches.items(): + timeslices = timeslice_along_seq_lens_with_overlap( + sample_batch=sample_batch, + seq_lens=sample_batch.get(SampleBatch.SEQ_LENS) + if self.replay_sequence_override + else None, + zero_pad_max_seq_len=self.replay_sequence_length, + pre_overlap=self.replay_burn_in, + zero_init_states=self.replay_zero_init_states, + ) + for slice in timeslices: + self.replay_buffers[policy_id].add(slice, **kwargs) + self.last_added_batches[policy_id].append(slice) + + elif self.storage_unit == StorageUnit.EPISODES: + for policy_id, sample_batch in pids_and_batches.items(): + for eps in sample_batch.split_by_episode(): + # Only add full episodes to the buffer + if eps.get(SampleBatch.T)[0] == 0 and ( + eps.get(SampleBatch.TERMINATEDS, [True])[-1] + or eps.get(SampleBatch.TRUNCATEDS, [False])[-1] + ): + self.replay_buffers[policy_id].add(eps, **kwargs) + self.last_added_batches[policy_id].append(eps) + else: + if log_once("only_full_episodes"): + logger.info( + "This buffer uses episodes as a storage " + "unit and thus allows only full episodes " + "to be added to it. Some samples may be " + "dropped." + ) + elif self.storage_unit == StorageUnit.FRAGMENTS: + for policy_id, sample_batch in pids_and_batches.items(): + self.replay_buffers[policy_id].add(sample_batch, **kwargs) + self.last_added_batches[policy_id].append(sample_batch) + + self._num_added += batch.count + + @DeveloperAPI + @override(MultiAgentReplayBuffer) + def sample( + self, num_items: int, policy_id: PolicyID = DEFAULT_POLICY_ID, **kwargs + ) -> Optional[SampleBatchType]: + """Samples a batch of size `num_items` from a specified buffer. + + Concatenates old samples to new ones according to + self.replay_ratio. If not enough new samples are available, mixes in + less old samples to retain self.replay_ratio on average. Returns + an empty batch if there are no items in the buffer. + + Args: + num_items: Number of items to sample from this buffer. + policy_id: ID of the policy that produced the experiences to be + sampled. + **kwargs: Forward compatibility kwargs. + + Returns: + Concatenated MultiAgentBatch of items. + """ + # Merge kwargs, overwriting standard call arguments + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + def mix_batches(_policy_id): + """Mixes old with new samples. + + Tries to mix according to self.replay_ratio on average. + If not enough new samples are available, mixes in less old samples + to retain self.replay_ratio on average. + """ + + def round_up_or_down(value, ratio): + """Returns an integer averaging to value*ratio.""" + product = value * ratio + ceil_prob = product % 1 + if random.uniform(0, 1) < ceil_prob: + return int(np.ceil(product)) + else: + return int(np.floor(product)) + + max_num_new = round_up_or_down(num_items, 1 - self.replay_ratio) + # if num_samples * self.replay_ratio is not round, + # we need one more sample with a probability of + # (num_items*self.replay_ratio) % 1 + + _buffer = self.replay_buffers[_policy_id] + output_batches = self.last_added_batches[_policy_id][:max_num_new] + self.last_added_batches[_policy_id] = self.last_added_batches[_policy_id][ + max_num_new: + ] + + # No replay desired + if self.replay_ratio == 0.0: + return concat_samples_into_ma_batch(output_batches) + # Only replay desired + elif self.replay_ratio == 1.0: + return _buffer.sample(num_items, **kwargs) + + num_new = len(output_batches) + + if np.isclose(num_new, num_items * (1 - self.replay_ratio)): + # The optimal case, we can mix in a round number of old + # samples on average + num_old = num_items - max_num_new + else: + # We never want to return more elements than num_items + num_old = min( + num_items - max_num_new, + round_up_or_down( + num_new, self.replay_ratio / (1 - self.replay_ratio) + ), + ) + + output_batches.append(_buffer.sample(num_old, **kwargs)) + # Depending on the implementation of underlying buffers, samples + # might be SampleBatches + output_batches = [batch.as_multi_agent() for batch in output_batches] + return concat_samples_into_ma_batch(output_batches) + + def check_buffer_is_ready(_policy_id): + if ( + (len(self.replay_buffers[policy_id]) == 0) and self.replay_ratio > 0.0 + ) or ( + len(self.last_added_batches[_policy_id]) == 0 + and self.replay_ratio < 1.0 + ): + return False + return True + + with self.replay_timer: + samples = [] + + if self.replay_mode == ReplayMode.LOCKSTEP: + assert ( + policy_id is None + ), "`policy_id` specifier not allowed in `lockstep` mode!" + if check_buffer_is_ready(_ALL_POLICIES): + samples.append(mix_batches(_ALL_POLICIES).as_multi_agent()) + elif policy_id is not None: + if check_buffer_is_ready(policy_id): + samples.append(mix_batches(policy_id).as_multi_agent()) + else: + for policy_id, replay_buffer in self.replay_buffers.items(): + if check_buffer_is_ready(policy_id): + samples.append(mix_batches(policy_id).as_multi_agent()) + + return concat_samples_into_ma_batch(samples) + + @DeveloperAPI + @override(MultiAgentPrioritizedReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + data = { + "last_added_batches": self.last_added_batches, + } + parent = MultiAgentPrioritizedReplayBuffer.get_state(self) + parent.update(data) + return parent + + @DeveloperAPI + @override(MultiAgentPrioritizedReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by + calling `self.get_state()`. + """ + self.last_added_batches = state["last_added_batches"] + MultiAgentPrioritizedReplayBuffer.set_state(state) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_episode_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_episode_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0d9247bbe5440077f081d499f2fee3a67267d8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_episode_buffer.py @@ -0,0 +1,1078 @@ +import copy +import hashlib +import numpy as np +import scipy + +from collections import defaultdict, deque +from numpy.typing import NDArray +from typing import Dict, List, Optional, Set, Tuple, Union +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import override +from ray.rllib.utils.replay_buffers.multi_agent_episode_buffer import ( + MultiAgentEpisodeReplayBuffer, +) +from ray.rllib.utils.replay_buffers.prioritized_episode_buffer import ( + PrioritizedEpisodeReplayBuffer, +) +from ray.rllib.utils.typing import ModuleID +from ray.rllib.execution.segment_tree import MinSegmentTree, SumSegmentTree + + +class MultiAgentPrioritizedEpisodeReplayBuffer( + MultiAgentEpisodeReplayBuffer, PrioritizedEpisodeReplayBuffer +): + """Multi-agent episode replay buffer that stores episodes by their IDs. + + This class implements a replay buffer as used in "Prioritized Experience + Replay" (Schaul et al., 2016) for multi-agent reinforcement learning, + + Each "row" (a slot in a deque) in the buffer is occupied by one episode. If an + incomplete episode is added to the buffer and then another chunk of that episode is + added at a later time, the buffer will automatically concatenate the new fragment to + the original episode. This way, episodes can be completed via subsequent `add` + calls. + + Sampling returns a size `B` episode list (number of 'rows'), where each episode + holds a tuple tuple of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation `o_t`, + `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is the sum of + all rewards collected over the time steps between `t+1` and `t+n`. The `n`-step can + be chosen freely when sampling and defaults to `1`. If `n_step` is a tuple it is + sampled uniformly across the interval defined by the tuple (for each row in the + batch). + + Each episode contains - in addition to the data tuples presented above - two further + elements in its `extra_model_outputs`, namely `n_steps` and `weights`. The former + holds the `n_step` used for the sampled timesteps in the episode and the latter the + corresponding (importance sampling) weight for the transition. + + After sampling priorities can be updated (for the last sampled episode list) with + `self.update_priorities`. This method assigns the new priorities automatically to + the last sampled timesteps. Note, this implies that sampling timesteps and updating + their corresponding priorities needs to alternate (e.g. sampling several times and + then updating the priorities would not work because the buffer caches the last + sampled timestep indices). + + .. testcode:: + + import gymnasium as gym + + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole + from ray.rllib.utils.replay_buffers import ( + MultiAgentPrioritizedEpisodeReplayBuffer, + ) + + + # Create the environment. + env = MultiAgentCartPole({"num_agents": 2}) + + # Set up the loop variables + agent_ids = env.agents + agent_ids.append("__all__") + terminateds = {aid: False for aid in agent_ids} + truncateds = {aid: False for aid in agent_ids} + num_timesteps = 10000 + episodes = [] + + # Initialize the first episode entries. + eps = MultiAgentEpisode() + obs, infos = env.reset() + eps.add_env_reset(observations=obs, infos=infos) + + # Sample 10,000 env timesteps. + for i in range(num_timesteps): + # If terminated we create a new episode. + if eps.is_done: + episodes.append(eps.to_numpy()) + eps = MultiAgentEpisode() + terminateds = {aid: False for aid in agent_ids} + truncateds = {aid: False for aid in agent_ids} + obs, infos = env.reset() + eps.add_env_reset(observations=obs, infos=infos) + + # Sample a random action for all agents that should step in the episode + # next. + actions = { + aid: env.get_action_space(aid).sample() + for aid in eps.get_agents_to_act() + } + obs, rewards, terminateds, truncateds, infos = env.step(actions) + eps.add_env_step( + obs, + actions, + rewards, + infos, + terminateds=terminateds, + truncateds=truncateds + ) + + # Add the last (truncated) episode to the list of episodes. + if not eps.is_done: + episodes.append(eps) + + # Create the buffer. + buffer = MultiAgentPrioritizedEpisodeReplayBuffer() + # Add the list of episodes sampled. + buffer.add(episodes) + + # Pull a sample from the buffer using an `n-step` of 3. + sample = buffer.sample(num_items=256, gamma=0.95, n_step=3, beta=0.5) + """ + + def __init__( + self, + capacity: int = 10000, + *, + batch_size_B: int = 16, + batch_length_T: int = 1, + alpha: float = 1.0, + metrics_num_episodes_for_smoothing: int = 100, + **kwargs, + ): + """Initializes a `MultiAgentPrioritizedEpisodeReplayBuffer` object + + Args: + capacity: The total number of timesteps to be storable in this buffer. + Will start ejecting old episodes once this limit is reached. + batch_size_B: The number of episodes returned from `sample()`. + batch_length_T: The length of each episode in the episode list returned from + `sample()`. + alpha: The amount of prioritization to be used: `alpha=1.0` means full + prioritization, `alpha=0.0` means no prioritization. + """ + # Initialize the parents. + MultiAgentEpisodeReplayBuffer.__init__( + self, + capacity=capacity, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + metrics_num_episodes_for_smoothing=metrics_num_episodes_for_smoothing, + **kwargs, + ) + PrioritizedEpisodeReplayBuffer.__init__( + self, + capacity=capacity, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + alpha=alpha, + metrics_num_episodes_for_smoothing=metrics_num_episodes_for_smoothing, + **kwargs, + ) + + # TODO (simon): If not needed in synchronized sampling, remove. + # Maps indices from samples to their corresponding tree index. + self._sample_idx_to_tree_idx = {} + # Initialize segment trees for the priority weights per module. Note, b/c + # the trees are binary we need for them a capacity that is an exponential + # of 2. Double it to enable temporary buffer overflow (we need then free + # nodes in the trees). + tree_capacity = int(2 ** np.ceil(np.log2(self.capacity))) + + # Each module receives its own segment trees for independent sampling. + self._module_to_max_priority: Dict[ModuleID, float] = defaultdict(lambda: 1.0) + self._module_to_sum_segment: Dict[ModuleID, "SumSegmentTree"] = defaultdict( + lambda: SumSegmentTree(2 * tree_capacity) + ) + self._module_to_min_segment: Dict[ModuleID, "MinSegmentTree"] = defaultdict( + lambda: MinSegmentTree(2 * tree_capacity) + ) + # At initialization all nodes are free. + self._module_to_free_nodes: Dict[ModuleID, "deque"] = defaultdict( + lambda: deque(list(range(2 * tree_capacity)), maxlen=2 * tree_capacity) + ) + # Keep track of the maximum index used from the trees. This helps + # to not traverse the complete trees. + self._module_to_max_idx: Dict[ModuleID, int] = defaultdict(lambda: 0) + # Map from tree indices to sample indices (i.e. `self._indices`). + self._module_to_tree_idx_to_sample_idx: Dict[ModuleID, dict] = defaultdict( + lambda: {} + ) + # Map from module ID to the last sampled indices to update priorities. + self._module_to_last_sampled_indices: Dict[ModuleID, list] = defaultdict( + lambda: [] + ) + + @override(MultiAgentEpisodeReplayBuffer) + def add( + self, + episodes: Union[List["MultiAgentEpisode"], "MultiAgentEpisode"], + weight: Optional[Union[float, Dict[ModuleID, float]]] = None, + ) -> None: + """Adds incoming episodes to the replay buffer. + + Note, if the incoming episodes' time steps cause the buffer to overflow, + older episodes are evicted. Because episodes usually come in chunks and + not complete, this could lead to edge cases (e.g. with very small capacity + or very long episode length) where the first part of an episode is evicted + while the next part just comes in. + To defend against such case, the complete episode is evicted, including + the new chunk, unless the episode is the only one in the buffer. In the + latter case the buffer will be allowed to overflow in a temporary fashion, + i.e. during the next addition of samples to the buffer an attempt is made + to fall below capacity again. + + The user is advised to select a large enough buffer with regard to the maximum + expected episode length. + + Args: + episodes: A list of `SingleAgentEpisode`s that contain the episode data. + weight: A starting priority for the time steps in `episodes`. If `None` + the maximum priority is used, i.e. 1.0 (as suggested in the original + paper we scale weights to the interval [0.0, 1.0]). If a dictionary + is provided, it must contain the weights for each module. + + """ + # Define the weights. + weight_per_module = {} + # If no weight is provided, use the maximum priority. + if weight is None: + weight = self._max_priority + # If `weight` is a dictionary, use the module weights. + elif isinstance(dict, weight): + weight_per_module = weight + # Define the weight as the mean of the module weights. + weight = np.mean(list(weight.values())) + + episodes: List["MultiAgentEpisode"] = force_list(episodes) + + new_episode_ids: List[str] = [eps.id_ for eps in episodes] + # Calculate the total number of environment timesteps in the new episodes. + # Note, we need the potential new sum of timesteps to decide whether to + # evict episodes. + total_env_timesteps = sum([eps.env_steps() for eps in episodes]) + self._num_timesteps += total_env_timesteps + self._num_timesteps_added += total_env_timesteps + + # Set up some counters for metrics. + num_env_steps_added = 0 + agent_to_num_steps_added = defaultdict(int) + module_to_num_steps_added = defaultdict(int) + num_episodes_added = 0 + agent_to_num_episodes_added = defaultdict(int) + module_to_num_episodes_added = defaultdict(int) + num_episodes_evicted = 0 + agent_to_num_episodes_evicted = defaultdict(int) + module_to_num_episodes_evicted = defaultdict(int) + num_env_steps_evicted = 0 + agent_to_num_steps_evicted = defaultdict(int) + module_to_num_steps_evicted = defaultdict(int) + + # Evict old episodes. + eps_evicted_ids: Set[Union[str, int]] = set() + eps_evicted_idxs: Set[int] = set() + # Only evict episodes if the buffer is full and there is more than one + + while ( + self._num_timesteps > self.capacity + and self._num_remaining_episodes(new_episode_ids, eps_evicted_ids) != 1 + ): + # Evict episode. + evicted_episode = self.episodes.popleft() + eps_evicted_ids.add(evicted_episode.id_) + eps_evicted_idxs.add(self.episode_id_to_index.pop(evicted_episode.id_)) + # If this episode has a new chunk in the new episodes added, + # we subtract it again. + # TODO (sven, simon): Should we just treat such an episode chunk + # as a new episode? + if evicted_episode.id_ in new_episode_ids: + idx = next( + i + for i, eps in enumerate(episodes) + if eps.id_ == evicted_episode.id_ + ) + new_eps_to_evict = episodes.pop(idx) + # Remove the timesteps of the evicted new episode from the counter. + self._num_timesteps -= new_eps_to_evict.env_steps() + self._num_timesteps_added -= new_eps_to_evict.env_steps() + # Remove the timesteps of the evicted old episode from the counter. + self._num_timesteps -= evicted_episode.env_steps() + self._num_agent_timesteps -= evicted_episode.agent_steps() + self._num_episodes_evicted += 1 + # Increase the counters. + num_episodes_evicted += 1 + num_env_steps_evicted += evicted_episode.env_steps() + for aid, a_eps in evicted_episode.agent_episodes.items(): + mid = evicted_episode._agent_to_module_mapping[aid] + agent_to_num_episodes_evicted[aid] += 1 + module_to_num_episodes_evicted[mid] += 1 + agent_to_num_steps_evicted[aid] += a_eps.agent_steps() + module_to_num_steps_evicted[mid] += a_eps.agent_steps() + # Remove the module timesteps of the evicted episode from the counters. + self._evict_module_episodes(evicted_episode) + del evicted_episode + + # Add agent and module steps. + for eps in episodes: + self._num_agent_timesteps += eps.agent_steps() + self._num_agent_timesteps_added += eps.agent_steps() + # Update the module counters by the module timesteps. + self._update_module_counters(eps) + + # Remove corresponding indices, if episodes were evicted. + if eps_evicted_idxs: + new_indices = [] + # Each index 2-tuple is of the form (ma_episode_idx, timestep) and + # refers to a certain environment timestep in a certain multi-agent + # episode. + i = 0 + for idx_tuple in self._indices: + # If episode index is from an evicted episode, remove it from the + # indices and clean up. + if idx_tuple[0] in eps_evicted_idxs: + # Here we need the index of a multi-agent sample in the segment + # tree. + self._free_nodes.appendleft(idx_tuple[2]) + # Remove also the potentially maximum index. + self._max_idx -= 1 if self._max_idx == idx_tuple[2] else 0 + # Reset to defaults. + self._sum_segment[idx_tuple[2]] = 0.0 + self._min_segment[idx_tuple[2]] = float("inf") + sample_idx = self._tree_idx_to_sample_idx[idx_tuple[2]] + self._tree_idx_to_sample_idx.pop(idx_tuple[2]) + self._sample_idx_to_tree_idx.pop(sample_idx) + # Otherwise, keep the index. + else: + new_indices.append(idx_tuple) + self._tree_idx_to_sample_idx[idx_tuple[2]] = i + self._sample_idx_to_tree_idx[i] = idx_tuple[2] + i += 1 + # Assign the new list of indices. + self._indices = new_indices + # Also remove corresponding module indices. + for module_id, module_indices in self._module_to_indices.items(): + new_module_indices = [] + # Each index 4-tuple is of the form + # (ma_episode_idx, agent_id, timestep, segtree_idx) and refers to a + # certain agent timestep in a certain multi-agent episode. + i = 0 + for idx_quadlet in module_indices: + # If episode index is from an evicted episode, remove it from the + # indices and clean up. + if idx_quadlet[0] in eps_evicted_idxs: + # Here we need the index of a multi-agent sample in the segment + # tree. + self._module_to_free_nodes[module_id].appendleft(idx_quadlet[3]) + # Remove also the potentially maximum index per module. + self._module_to_max_idx[module_id] -= ( + 1 + if self._module_to_max_idx[module_id] == idx_quadlet[3] + else 0 + ) + # Set to defaults. + self._module_to_sum_segment[module_id][idx_quadlet[3]] = 0.0 + self._module_to_min_segment[module_id][idx_quadlet[3]] = float( + "inf" + ) + self._module_to_tree_idx_to_sample_idx[module_id].pop( + idx_quadlet[3] + ) + # Otherwise, keep the index. + else: + new_module_indices.append(idx_quadlet) + self._module_to_tree_idx_to_sample_idx[module_id][ + idx_quadlet[3] + ] = i + i += 1 + # Assign the new list of indices for the module. + self._module_to_indices[module_id] = new_module_indices + + j = len(self._indices) + for eps in episodes: + eps = copy.deepcopy(eps) + # If the episode is part of an already existing episode, concatenate. + if eps.id_ in self.episode_id_to_index: + eps_idx = self.episode_id_to_index[eps.id_] + existing_eps = self.episodes[eps_idx - self._num_episodes_evicted] + existing_len = len(existing_eps) + self._indices.extend( + [ + ( + eps_idx, + existing_len + i, + # Get the index in the segment trees. + self._get_free_node_and_assign(j + i, weight), + ) + for i in range(len(eps)) + ] + ) + # Add new module indices. + self._add_new_module_indices(eps, eps_idx, True, weight_per_module) + # Concatenate the episode chunk. + existing_eps.concat_episode(eps) + # Otherwise, create a new entry. + else: + # New episode. + self.episodes.append(eps) + # Update the counters. + num_episodes_added += 1 + for aid, a_eps in eps.agent_episodes.items(): + mid = eps._agent_to_module_mapping[aid] + agent_to_num_episodes_added[aid] += 1 + module_to_num_episodes_added[mid] += 1 + eps_idx = len(self.episodes) - 1 + self._num_episodes_evicted + self.episode_id_to_index[eps.id_] = eps_idx + self._indices.extend( + [ + (eps_idx, i, self._get_free_node_and_assign(j + i, weight)) + for i in range(len(eps)) + ] + ) + # Add new module indices. + self._add_new_module_indices(eps, eps_idx, False, weight_per_module) + + # Update the step counters. + num_env_steps_added += eps.env_steps() + for aid, e_eps in eps.agent_episodes.items(): + mid = eps._agent_to_module_mapping[aid] + agent_to_num_steps_added[aid] += e_eps.agent_steps() + module_to_num_steps_added[mid] += e_eps.agent_steps() + # Increase index to the new length of `self._indices`. + j = len(self._indices) + + # Update the adding metrics. + # Update the adding metrics. + self._update_add_metrics( + num_episodes_added=num_episodes_added, + num_env_steps_added=num_env_steps_added, + num_episodes_evicted=num_episodes_evicted, + num_env_steps_evicted=num_env_steps_evicted, + agent_to_num_episodes_added=agent_to_num_episodes_added, + agent_to_num_steps_added=agent_to_num_steps_added, + agent_to_num_episodes_evicted=agent_to_num_episodes_evicted, + agent_to_num_steps_evicted=agent_to_num_steps_evicted, + module_to_num_episodes_added=module_to_num_steps_added, + module_to_num_steps_added=module_to_num_episodes_added, + module_to_num_episodes_evicted=module_to_num_episodes_evicted, + module_to_num_steps_evicted=module_to_num_steps_evicted, + ) + + @override(MultiAgentEpisodeReplayBuffer) + def sample( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = 1, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + replay_mode: str = "independent", + modules_to_sample: Optional[List[ModuleID]] = None, + beta: float = 0.0, + **kwargs, + ) -> Union[List["MultiAgentEpisode"], List["SingleAgentEpisode"]]: + """Samples a list of episodes with multi-agent transitions. + + This sampling method also adds (importance sampling) weights to the returned + batch. See for prioritized sampling Schaul et al. (2016). + + Multi-agent transitions can be sampled either `"independent"` or + `"synchronized"` with the former sampling for each module independent agent + steps and the latter sampling agent transitions from the same environment step. + + The n-step parameter can be either a single integer or a tuple of two integers. + In the former case, the n-step is fixed to the given integer and in the latter + case, the n-step is sampled uniformly from the given range. Large n-steps could + potentially lead to many retries because not all samples might have a full + n-step transition. + + Sampling returns episode lists of size B (number of 'rows'), where each episode + holds a transition of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n, terminated_t+n, truncated_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation + `o_t`, `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is + the sum of all rewards collected over the time steps between `t+1` and `t+n`. + The `n`-step can be chosen freely when sampling and defaults to `1`. If `n_step` + is a tuple it is sampled uniformly across the interval defined by the tuple (for + each row in the batch), i.e. from the interval `[n_step[0], n_step[1]]`. + + If requested, `info`s of a transition's first and last timestep `t+n` and/or + `extra_model_outputs` from the first timestep (e.g. log-probabilities, etc.) are + added to the batch. + + Each episode contains - in addition to the data tuples presented above - two + further entries in its `extra_model_outputs`, namely `n_steps` and `weigths`. + The former holds the `n_step` used for each transition and the latter the + (importance sampling) weight of `1.0` for each row in the batch. This weight + is used for weighted loss calculations in the training process. + + Args: + num_items: The number of items to sample. If provided, `batch_size_B` + should be `None`. + batch_size_B: The batch size to sample. If provided, `num_items` + should be `None`. + batch_length_T: The length of the sampled batch. If not provided, the + default batch length is used. This feature is not yet implemented. + n_step: The n-step to sample. If the n-step is a tuple, the n-step is + sampled uniformly from the given range. If not provided, the default + n-step of `1` is used. + gamma: The discount factor for the n-step reward calculation. + include_infos: Whether to include the infos in the sampled episodes. + include_extra_model_outputs: Whether to include the extra model outputs + in the sampled episodes. + replay_mode: The replay mode to use for sampling. Either `"independent"` + or `"synchronized"`. + modules_to_sample: A list of module IDs to sample from. If not provided, + transitions for aall modules are sampled. + beta: The exponent of the importance sampling weight (see Schaul et + al. (2016)). A `beta=0.0` does not correct for the bias introduced + by prioritized replay and `beta=1.0` fully corrects for it. + + Returns: + A list of 1-step long single-agent episodes containing all basic episode + data and if requested infos and extra model outputs. In addition extra model + outputs hold the (importance sampling) weights and the n-step used for each + transition. + """ + assert beta >= 0.0 + + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + # TODO (simon): Implement trajectory sampling for RNNs. + batch_length_T = batch_length_T or self.batch_length_T + + # Sample for each module independently. + if replay_mode == "independent": + return self._sample_independent( + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + modules_to_sample=modules_to_sample, + beta=beta, + ) + # Otherwise, sample synchronized. + else: + return self._sample_synchonized( + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + modules_to_sample=modules_to_sample, + ) + + @override(PrioritizedEpisodeReplayBuffer) + def update_priorities( + self, + priorities: Union[NDArray, Dict[ModuleID, NDArray]], + module_id: ModuleID, + ) -> None: + """Update the priorities of items at corresponding indices. + + Usually, incoming priorities are TD-errors. + + Args: + priorities: Numpy array containing the new priorities to be used + in sampling for the items in the last sampled batch. + """ + + assert len(priorities) == len(self._module_to_last_sampled_indices[module_id]) + + for idx, priority in zip( + self._module_to_last_sampled_indices[module_id], priorities + ): + # sample_idx = self._module_to_tree_idx_to_sample_idx[module_id][idx] + # ma_episode_idx = ( + # self._module_to_indices[module_id][sample_idx][0] + # - self._num_episodes_evicted + # ) + + # ma_episode_indices.append(ma_episode_idx) + # Note, TD-errors come in as absolute values or results from + # cross-entropy loss calculations. + # assert priority > 0, f"priority was {priority}" + priority = max(priority, 1e-12) + assert 0 <= idx < self._module_to_sum_segment[module_id].capacity + # TODO (simon): Create metrics. + # delta = priority**self._alpha - self._sum_segment[idx] + # Update the priorities in the segment trees. + self._module_to_sum_segment[module_id][idx] = priority**self._alpha + self._module_to_min_segment[module_id][idx] = priority**self._alpha + # Update the maximal priority. + self._module_to_max_priority[module_id] = max( + self._module_to_max_priority[module_id], priority + ) + # Clear the corresponding index list for the module. + self._module_to_last_sampled_indices[module_id].clear() + + # TODO (simon): Use this later for synchronized sampling. + # for ma_episode_idx in ma_episode_indices: + # ma_episode_tree_idx = self._sample_idx_to_tree_idx(ma_episode_idx) + # ma_episode_idx = + + # # Update the weights + # self._sum_segment[tree_idx] = sum( + # self._module_to_sum_segment[module_id][idx] + # for module_id, idx in self._tree_idx_to_sample_idx[tree_idx] + # ) + # self._min_segment[tree_idx] = min( + # self._module_to_min_segment[module_id][idx] + # for module_id, idx in self._tree_idx_to_sample_idx[tree_idx] + # ) + + @override(MultiAgentEpisodeReplayBuffer) + def get_state(self): + return ( + MultiAgentEpisodeReplayBuffer.get_state(self) + | PrioritizedEpisodeReplayBuffer.get_state(self) + | { + "_module_to_max_priority": list(self._module_to_max_priority.items()), + "_module_to_sum_segment": list(self._module_to_sum_segment.items()), + "_module_to_min_segment": list(self._module_to_min_segment.items()), + "_module_to_free_nodes": list(self._module_to_free_nodes.items()), + "_module_to_max_idx": list(self._module_to_max_idx.items()), + "_module_to_tree_idx_to_sample_idx": list( + self._module_to_tree_idx_to_sample_idx.items() + ), + "_module_to_last_sampled_indices": list( + self._module_to_last_sampled_indices.items() + ), + } + ) + + @override(MultiAgentEpisodeReplayBuffer) + def set_state(self, state) -> None: + MultiAgentEpisodeReplayBuffer.set_state(self, state) + PrioritizedEpisodeReplayBuffer.set_state(self, state) + self._module_to_max_priority = defaultdict( + lambda: 1.0, dict(state["_module_to_max_priority"]) + ) + tree_capacity = int(2 ** np.ceil(np.log2(self.capacity))) + self._module_to_sum_segment = defaultdict( + lambda: SumSegmentTree(2 * tree_capacity), + dict(state["_module_to_sum_segment"]), + ) + self._module_to_min_segment = defaultdict( + lambda: SumSegmentTree(2 * tree_capacity), + dict(state["_module_to_min_segment"]), + ) + self._module_to_free_nodes = defaultdict( + lambda: deque(list(range(2 * tree_capacity)), maxlen=2 * tree_capacity), + dict(state["_module_to_free_nodes"]), + ) + self._module_to_max_idx = defaultdict( + lambda: 0, dict(state["_module_to_max_idx"]) + ) + self._module_to_tree_idx_to_sample_idx = defaultdict( + lambda: {}, dict(state["_module_to_tree_idx_to_sample_idx"]) + ) + self._module_to_last_sampled_indices = defaultdict( + lambda: [], dict(state["_module_to_last_sampled_indices"]) + ) + + @override(MultiAgentEpisodeReplayBuffer) + def _add_new_module_indices( + self, + ma_episode: MultiAgentEpisode, + ma_episode_idx: int, + ma_episode_exists: bool = True, + weight: Optional[Union[float, Dict[ModuleID, float]]] = None, + ) -> None: + """Adds the module indices for new episode chunks. + + Args: + multi_agent_episode: The multi-agent episode to add the module indices for. + episode_idx: The index of the episode in the `self.episodes`. + """ + existing_ma_episode = None + if ma_episode_exists: + existing_ma_episode = self.episodes[ + self.episode_id_to_index[ma_episode.id_] - self._num_episodes_evicted + ] + + for agent_id in ma_episode.agent_ids: + # Get the corresponding module id. + module_id = ma_episode.module_for(agent_id) + # Get the module episode. + module_eps = ma_episode.agent_episodes[agent_id] + + # Is the agent episode already in the buffer's existing `ma_episode`? + if ma_episode_exists and agent_id in existing_ma_episode.agent_episodes: + existing_sa_eps_len = len(existing_ma_episode.agent_episodes[agent_id]) + # Otherwise, it is a new single-agent episode and we increase the counter. + else: + existing_sa_eps_len = 0 + self._num_module_episodes[module_id] += 1 + + # Add new module indices. + module_weight = weight.get( + module_id, self._module_to_max_priority[module_id] + ) + j = len(self._module_to_indices[module_id]) + self._module_to_indices[module_id].extend( + [ + ( + # Keep the MAE index for sampling. + ma_episode_idx, + agent_id, + existing_sa_eps_len + i, + # Get the index in the segment trees. + self._get_free_node_per_module_and_assign( + module_id, + j + i, + module_weight, + ), + ) + for i in range(len(module_eps)) + ] + ) + + @override(PrioritizedEpisodeReplayBuffer) + def _get_free_node_and_assign(self, sample_index, weight: float = 1.0) -> int: + """Gets the next free node in the segment trees. + + In addition the initial priorities for a new transition are added + to the segment trees and the index of the nodes is added to the + index mapping. + + Args: + sample_index: The index of the sample in the `self._indices` list. + weight: The initial priority weight to be used in sampling for + the item at index `sample_index`. + + Returns: + The index in the segment trees `self._sum_segment` and + `self._min_segment` for the item at index `sample_index` in + ``self._indices`. + """ + # Get an index from the free nodes in the segment trees. + idx = self._free_nodes.popleft() + self._max_idx = idx if idx > self._max_idx else self._max_idx + # Add the weight to the segments. + self._sum_segment[idx] = weight**self._alpha + self._min_segment[idx] = weight**self._alpha + # Map the index in the trees to the index in `self._indices`. + self._tree_idx_to_sample_idx[idx] = sample_index + self._sample_idx_to_tree_idx[sample_index] = idx + # Return the index. + return idx + + def _get_free_node_per_module_and_assign( + self, module_id: ModuleID, sample_index, weight: float = 1.0 + ) -> int: + """Gets the next free node in the segment trees. + + In addition the initial priorities for a new transition are added + to the segment trees and the index of the nodes is added to the + index mapping. + + Args: + sample_index: The index of the sample in the `self._indices` list. + weight: The initial priority weight to be used in sampling for + the item at index `sample_index`. + + Returns: + The index in the segment trees `self._sum_segment` and + `self._min_segment` for the item at index `sample_index` in + ``self._indices`. + """ + # Get an index from the free nodes in the segment trees. + idx = self._module_to_free_nodes[module_id].popleft() + self._module_to_max_idx[module_id] = ( + idx + if idx > self._module_to_max_idx[module_id] + else self._module_to_max_idx[module_id] + ) + # Add the weight to the segments. + # TODO (simon): Allow alpha to be chosen per module. + self._module_to_sum_segment[module_id][idx] = weight**self._alpha + self._module_to_min_segment[module_id][idx] = weight**self._alpha + # Map the index in the trees to the index in `self._indices`. + self._module_to_tree_idx_to_sample_idx[module_id][idx] = sample_index + # Return the index. + return idx + + @override(MultiAgentEpisodeReplayBuffer) + def _sample_independent( + self, + batch_size_B: Optional[int], + batch_length_T: Optional[int], + n_step: Optional[Union[int, Tuple]], + gamma: float, + include_infos: bool, + include_extra_model_outputs: bool, + modules_to_sample: Optional[List[ModuleID]], + beta: Optional[float], + ) -> List["SingleAgentEpisode"]: + """Samples a single-agent episode list with independent transitions. + + Note, independent sampling means that each module samples its transitions + independently from the replay buffer. This is the default sampling mode. + In contrast, synchronized sampling samples transitions from the same + environment step. + """ + + actual_n_step = n_step or 1 + # Sample the n-step if necessary. + random_n_step = isinstance(n_step, tuple) + + # Keep track of the indices that were sampled last for updating the + # weights later (see `ray.rllib.utils.replay_buffer.utils. + # update_priorities_in_episode_replay_buffer`). + # self._last_sampled_indices = defaultdict(lambda: []) + + sampled_episodes = [] + # Record the number of samples per module/agent/total. + num_env_steps_sampled = 0 + agent_to_num_steps_sampled = defaultdict(int) + module_to_num_steps_sampled = defaultdict(int) + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + agent_to_sampled_env_step_idxs = defaultdict(set) + module_to_sampled_env_step_idxs = defaultdict(set) + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + agent_to_sampled_episode_idxs = defaultdict(set) + module_to_sampled_episode_idxs = defaultdict(set) + # Record all n-steps that have been used. + sampled_n_steps = [] + agent_to_sampled_n_steps = defaultdict(list) + module_to_sampled_n_steps = defaultdict(list) + # Record the number of times a sample needs to be resampled. + num_resamples = 0 + agent_to_num_resamples = defaultdict(int) + module_to_num_resamples = defaultdict(int) + + # TODO (simon): Ensure that the module has data and if not, skip it. + # TODO (sven): Should we then error out or skip? I think the Learner + # should handle this case when a module has no train data. + modules_to_sample = modules_to_sample or set(self._module_to_indices.keys()) + for module_id in modules_to_sample: + # Sample proportionally from the replay buffer's module segments using the + # respective weights. + module_total_segment_sum = self._module_to_sum_segment[module_id].sum() + module_p_min = ( + self._module_to_min_segment[module_id].min() / module_total_segment_sum + ) + # TODO (simon): Allow individual betas per module. + module_max_weight = (module_p_min * self.get_num_timesteps(module_id)) ** ( + -beta + ) + B = 0 + while B < batch_size_B: + # First, draw a random sample from Uniform(0, sum over all weights). + # Note, transitions with higher weight get sampled more often (as + # more random draws fall into larger intervals). + module_random_sum = ( + self.rng.random() * self._module_to_sum_segment[module_id].sum() + ) + # Get the highest index in the sum-tree for which the sum is + # smaller or equal the random sum sample. + # Note, in contrast to Schaul et al. (2018) (who sample + # `o_(t + n_step)`, Algorithm 1) we sample `o_t`. + module_idx = self._module_to_sum_segment[module_id].find_prefixsum_idx( + module_random_sum + ) + # Get the theoretical probability mass for drawing this sample. + module_p_sample = ( + self._module_to_sum_segment[module_id][module_idx] + / module_total_segment_sum + ) + # Compute the importance sampling weight. + module_weight = ( + module_p_sample * self.get_num_timesteps(module_id) + ) ** (-beta) + # Now, get the transition stored at this index. + index_quadlet = self._module_to_indices[module_id][ + self._module_to_tree_idx_to_sample_idx[module_id][module_idx] + ] + + # This will be an agent timestep (not env timestep). + # TODO (simon, sven): Maybe deprecate sa_episode_idx (_) in the index + # quads. Is there any need for it? + ma_episode_idx, agent_id, sa_episode_ts = ( + index_quadlet[0] - self._num_episodes_evicted, + index_quadlet[1], + index_quadlet[2], + ) + + # Get the multi-agent episode. + ma_episode = self.episodes[ma_episode_idx] + # Retrieve the single-agent episode for filtering. + sa_episode = ma_episode.agent_episodes[agent_id] + + # If we use random n-step sampling, draw the n-step for this item. + if random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + # If we cannnot make the n-step, we resample. + if sa_episode_ts + actual_n_step > len(sa_episode): + num_resamples += 1 + agent_to_num_resamples[agent_id] += 1 + module_to_num_resamples[module_id] += 1 + continue + # Note, this will be the reward after executing action + # `a_(episode_ts)`. For `n_step>1` this will be the discounted sum + # of all rewards that were collected over the last n steps. + sa_raw_rewards = sa_episode.get_rewards( + slice(sa_episode_ts, sa_episode_ts + actual_n_step) + ) + sa_rewards = scipy.signal.lfilter( + [1], [1, -gamma], sa_raw_rewards[::-1], axis=0 + )[-1] + + sampled_sa_episode = SingleAgentEpisode( + id_=sa_episode.id_, + # Provide the IDs for the learner connector. + agent_id=sa_episode.agent_id, + module_id=sa_episode.module_id, + multi_agent_episode_id=ma_episode.id_, + # Ensure that each episode contains a tuple of the form: + # (o_t, a_t, sum(r_(t:t+n_step)), o_(t+n_step)) + # Two observations (t and t+n). + observations=[ + sa_episode.get_observations(sa_episode_ts), + sa_episode.get_observations(sa_episode_ts + actual_n_step), + ], + observation_space=sa_episode.observation_space, + infos=( + [ + sa_episode.get_infos(sa_episode_ts), + sa_episode.get_infos(sa_episode_ts + actual_n_step), + ] + if include_infos + else None + ), + actions=[sa_episode.get_actions(sa_episode_ts)], + action_space=sa_episode.action_space, + rewards=[sa_rewards], + # If the sampled single-agent episode is the single-agent episode's + # last time step, check, if the single-agent episode is terminated + # or truncated. + terminated=( + sa_episode_ts + actual_n_step >= len(sa_episode) + and sa_episode.is_terminated + ), + truncated=( + sa_episode_ts + actual_n_step >= len(sa_episode) + and sa_episode.is_truncated + ), + extra_model_outputs={ + "weights": [ + module_weight / module_max_weight * 1 + ], # actual_size=1 + "n_step": [actual_n_step], + **( + { + k: [ + sa_episode.get_extra_model_outputs(k, sa_episode_ts) + ] + for k in sa_episode.extra_model_outputs.keys() + } + if include_extra_model_outputs + else {} + ), + }, + # TODO (sven): Support lookback buffers. + len_lookback_buffer=0, + t_started=sa_episode_ts, + ) + # Append single-agent episode to the list of sampled episodes. + sampled_episodes.append(sampled_sa_episode) + # Add the episode indices. + sampled_episode_idxs.add(ma_episode_idx) + agent_to_sampled_episode_idxs[sa_episode.agent_id].add(sa_episode.id_) + module_to_sampled_episode_idxs[module_id].add(sa_episode.id_) + # Get the corresponding index in the `env_to_agent_t` mapping. + # TODO (simon, sven): This has complexity O(n) and could become + # expensive when the episode is large. Note, however, that conversion + # from list to `numpy.ndarray` is also complexity O(n) and we do this + # at many places - also in the `MultiAgentEpisode`s. + ma_episode_ts = ma_episode.env_t_to_agent_t[agent_id].data.index( + sa_episode_ts + ) + # Add the unique step hashes. + sampled_env_step_idxs.add( + hashlib.sha256( + f"{ma_episode.id_}-{ma_episode_ts}".encode() + ).hexdigest() + ) + # Add the unique agent step hashes. + hashed_agent_step = hashlib.sha256( + f"{sa_episode.id_}-{sa_episode_ts}".encode() + ).hexdigest() + agent_to_sampled_env_step_idxs[agent_id].add(hashed_agent_step) + # Add the unique module step hashes. + module_to_sampled_env_step_idxs[module_id].add(hashed_agent_step) + # Add the actual n-step used in generating this sample. + sampled_n_steps.append(actual_n_step) + agent_to_sampled_n_steps[agent_id].append(actual_n_step) + module_to_sampled_n_steps[module_id].append(actual_n_step) + + # Increase counter. + B += 1 + # Keep track of sampled indices for updating priorities later for each + # module. + self._module_to_last_sampled_indices[module_id].append(module_idx) + + # Increase the per module timesteps counter. + self.sampled_timesteps_per_module[module_id] += B + # Increase the counter metrics. + num_env_steps_sampled += B + agent_to_num_steps_sampled[agent_id] += B + module_to_num_steps_sampled[module_id] += B + + # Increase the counter for environment timesteps. + self.sampled_timesteps += batch_size_B + + # Update the sample metrics. + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + sampled_n_step = sum(sampled_n_steps) / batch_size_B + agent_to_num_episodes_per_sample = { + aid: len(l) for aid, l in agent_to_sampled_episode_idxs.items() + } + module_to_num_episodes_per_sample = { + mid: len(l) for mid, l in module_to_sampled_episode_idxs.items() + } + agent_to_num_steps_per_sample = { + aid: len(l) for aid, l in agent_to_sampled_env_step_idxs.items() + } + module_to_num_steps_per_sample = { + mid: len(l) for mid, l in module_to_sampled_env_step_idxs.items() + } + agent_to_sampled_n_step = { + aid: sum(l) / len(l) for aid, l in agent_to_sampled_n_steps.items() + } + module_to_sampled_n_step = { + mid: sum(l) / len(l) for mid, l in module_to_sampled_n_steps.items() + } + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + sampled_n_step=sampled_n_step, + num_resamples=num_resamples, + agent_to_num_steps_sampled=agent_to_num_steps_sampled, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_sampled_n_step=agent_to_sampled_n_step, + agent_to_num_resamples=agent_to_num_resamples, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_sampled_n_step=module_to_sampled_n_step, + module_to_num_resamples=module_to_num_resamples, + ) + + # Return multi-agent dictionary. + return sampled_episodes diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..368b95d737ed6b85f64bd7091599c7bab4bc14b8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_replay_buffer.py @@ -0,0 +1,279 @@ +from typing import Dict +import logging +import numpy as np + +from ray.util.timer import _Timer +from ray.rllib.utils.annotations import override +from ray.rllib.utils.replay_buffers.multi_agent_replay_buffer import ( + MultiAgentReplayBuffer, + ReplayMode, + merge_dicts_with_warning, +) +from ray.rllib.utils.replay_buffers.prioritized_replay_buffer import ( + PrioritizedReplayBuffer, +) +from ray.rllib.utils.replay_buffers.replay_buffer import ( + StorageUnit, +) +from ray.rllib.utils.typing import PolicyID, SampleBatchType +from ray.rllib.policy.sample_batch import SampleBatch +from ray.util.debug import log_once +from ray.util.annotations import DeveloperAPI +from ray.rllib.policy.rnn_sequencing import timeslice_along_seq_lens_with_overlap + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class MultiAgentPrioritizedReplayBuffer( + MultiAgentReplayBuffer, PrioritizedReplayBuffer +): + """A prioritized replay buffer shard for multiagent setups. + + This buffer is meant to be run in parallel to distribute experiences + across `num_shards` shards. Unlike simpler buffers, it holds a set of + buffers - one for each policy ID. + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: str = "timesteps", + num_shards: int = 1, + replay_mode: str = "independent", + replay_sequence_override: bool = True, + replay_sequence_length: int = 1, + replay_burn_in: int = 0, + replay_zero_init_states: bool = True, + underlying_buffer_config: dict = None, + prioritized_replay_alpha: float = 0.6, + prioritized_replay_beta: float = 0.4, + prioritized_replay_eps: float = 1e-6, + **kwargs, + ): + """Initializes a MultiAgentReplayBuffer instance. + + Args: + capacity: The capacity of the buffer, measured in `storage_unit`. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. If they + are stored in episodes, replay_sequence_length is ignored. + If they are stored in episodes, replay_sequence_length is + ignored. + num_shards: The number of buffer shards that exist in total + (including this one). + replay_mode: One of "independent" or "lockstep". Determines, + whether batches are sampled independently or to an equal + amount. + replay_sequence_override: If True, ignore sequences found in incoming + batches, slicing them into sequences as specified by + `replay_sequence_length` and `replay_sequence_burn_in`. This only has + an effect if storage_unit is `sequences`. + replay_sequence_length: The sequence length (T) of a single + sample. If > 1, we will sample B x T from this buffer. + replay_burn_in: The burn-in length in case + `replay_sequence_length` > 0. This is the number of timesteps + each sequence overlaps with the previous one to generate a + better internal state (=state after the burn-in), instead of + starting from 0.0 each RNN rollout. + replay_zero_init_states: Whether the initial states in the + buffer (if replay_sequence_length > 0) are alwayas 0.0 or + should be updated with the previous train_batch state outputs. + underlying_buffer_config: A config that contains all necessary + constructor arguments and arguments for methods to call on + the underlying buffers. This replaces the standard behaviour + of the underlying PrioritizedReplayBuffer. The config + follows the conventions of the general + replay_buffer_config. kwargs for subsequent calls of methods + may also be included. Example: + "replay_buffer_config": {"type": PrioritizedReplayBuffer, + "capacity": 10, "storage_unit": "timesteps", + prioritized_replay_alpha: 0.5, prioritized_replay_beta: 0.5, + prioritized_replay_eps: 0.5} + prioritized_replay_alpha: Alpha parameter for a prioritized + replay buffer. Use 0.0 for no prioritization. + prioritized_replay_beta: Beta parameter for a prioritized + replay buffer. + prioritized_replay_eps: Epsilon parameter for a prioritized + replay buffer. + ``**kwargs``: Forward compatibility kwargs. + """ + if "replay_mode" in kwargs and ( + kwargs["replay_mode"] == "lockstep" + or kwargs["replay_mode"] == ReplayMode.LOCKSTEP + ): + if log_once("lockstep_mode_not_supported"): + logger.error( + "Replay mode `lockstep` is not supported for " + "MultiAgentPrioritizedReplayBuffer. " + "This buffer will run in `independent` mode." + ) + kwargs["replay_mode"] = "independent" + + if underlying_buffer_config is not None: + if log_once("underlying_buffer_config_not_supported"): + logger.info( + "PrioritizedMultiAgentReplayBuffer instantiated " + "with underlying_buffer_config. This will " + "overwrite the standard behaviour of the " + "underlying PrioritizedReplayBuffer." + ) + prioritized_replay_buffer_config = underlying_buffer_config + else: + prioritized_replay_buffer_config = { + "type": PrioritizedReplayBuffer, + "alpha": prioritized_replay_alpha, + "beta": prioritized_replay_beta, + } + + shard_capacity = capacity // num_shards + MultiAgentReplayBuffer.__init__( + self, + capacity=shard_capacity, + storage_unit=storage_unit, + replay_sequence_override=replay_sequence_override, + replay_mode=replay_mode, + replay_sequence_length=replay_sequence_length, + replay_burn_in=replay_burn_in, + replay_zero_init_states=replay_zero_init_states, + underlying_buffer_config=prioritized_replay_buffer_config, + **kwargs, + ) + + self.prioritized_replay_eps = prioritized_replay_eps + self.update_priorities_timer = _Timer() + + @DeveloperAPI + @override(MultiAgentReplayBuffer) + def _add_to_underlying_buffer( + self, policy_id: PolicyID, batch: SampleBatchType, **kwargs + ) -> None: + """Add a batch of experiences to the underlying buffer of a policy. + + If the storage unit is `timesteps`, cut the batch into timeslices + before adding them to the appropriate buffer. Otherwise, let the + underlying buffer decide how slice batches. + + Args: + policy_id: ID of the policy that corresponds to the underlying + buffer + batch: SampleBatch to add to the underlying buffer + ``**kwargs``: Forward compatibility kwargs. + """ + # Merge kwargs, overwriting standard call arguments + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + # For the storage unit `timesteps`, the underlying buffer will + # simply store the samples how they arrive. For sequences and + # episodes, the underlying buffer may split them itself. + if self.storage_unit is StorageUnit.TIMESTEPS: + timeslices = batch.timeslices(1) + elif self.storage_unit is StorageUnit.SEQUENCES: + timeslices = timeslice_along_seq_lens_with_overlap( + sample_batch=batch, + seq_lens=batch.get(SampleBatch.SEQ_LENS) + if self.replay_sequence_override + else None, + zero_pad_max_seq_len=self.replay_sequence_length, + pre_overlap=self.replay_burn_in, + zero_init_states=self.replay_zero_init_states, + ) + elif self.storage_unit == StorageUnit.EPISODES: + timeslices = [] + for eps in batch.split_by_episode(): + if eps.get(SampleBatch.T)[0] == 0 and ( + eps.get(SampleBatch.TERMINATEDS, [True])[-1] + or eps.get(SampleBatch.TRUNCATEDS, [False])[-1] + ): + # Only add full episodes to the buffer + timeslices.append(eps) + else: + if log_once("only_full_episodes"): + logger.info( + "This buffer uses episodes as a storage " + "unit and thus allows only full episodes " + "to be added to it. Some samples may be " + "dropped." + ) + elif self.storage_unit == StorageUnit.FRAGMENTS: + timeslices = [batch] + else: + raise ValueError("Unknown `storage_unit={}`".format(self.storage_unit)) + + for slice in timeslices: + # If SampleBatch has prio-replay weights, average + # over these to use as a weight for the entire + # sequence. + if self.replay_mode is ReplayMode.INDEPENDENT: + if "weights" in slice and len(slice["weights"]): + weight = np.mean(slice["weights"]) + else: + weight = None + + if "weight" in kwargs and weight is not None: + if log_once("overwrite_weight"): + logger.warning( + "Adding batches with column " + "`weights` to this buffer while " + "providing weights as a call argument " + "to the add method results in the " + "column being overwritten." + ) + + kwargs = {"weight": weight, **kwargs} + else: + if "weight" in kwargs: + if log_once("lockstep_no_weight_allowed"): + logger.warning( + "Settings weights for batches in " + "lockstep mode is not allowed." + "Weights are being ignored." + ) + + kwargs = {**kwargs, "weight": None} + self.replay_buffers[policy_id].add(slice, **kwargs) + + @DeveloperAPI + @override(PrioritizedReplayBuffer) + def update_priorities(self, prio_dict: Dict) -> None: + """Updates the priorities of underlying replay buffers. + + Computes new priorities from td_errors and prioritized_replay_eps. + These priorities are used to update underlying replay buffers per + policy_id. + + Args: + prio_dict: A dictionary containing td_errors for + batches saved in underlying replay buffers. + """ + with self.update_priorities_timer: + for policy_id, (batch_indexes, td_errors) in prio_dict.items(): + new_priorities = np.abs(td_errors) + self.prioritized_replay_eps + self.replay_buffers[policy_id].update_priorities( + batch_indexes, new_priorities + ) + + @DeveloperAPI + @override(MultiAgentReplayBuffer) + def stats(self, debug: bool = False) -> Dict: + """Returns the stats of this buffer and all underlying buffers. + + Args: + debug: If True, stats of underlying replay buffers are + fetched with debug=True. + + Returns: + stat: Dictionary of buffer stats. + """ + stat = { + "add_batch_time_ms": round(1000 * self.add_batch_timer.mean, 3), + "replay_time_ms": round(1000 * self.replay_timer.mean, 3), + "update_priorities_time_ms": round( + 1000 * self.update_priorities_timer.mean, 3 + ), + } + for policy_id, replay_buffer in self.replay_buffers.items(): + stat.update( + {"policy_{}".format(policy_id): replay_buffer.stats(debug=debug)} + ) + return stat diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3af0125b27dcaf2487491ef6a1a653531f525a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/multi_agent_replay_buffer.py @@ -0,0 +1,392 @@ +import collections +import logging +from enum import Enum +from typing import Any, Dict, Optional + +from ray.util.timer import _Timer +from ray.rllib.policy.rnn_sequencing import timeslice_along_seq_lens_with_overlap +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.replay_buffers.replay_buffer import ( + _ALL_POLICIES, + ReplayBuffer, + StorageUnit, +) +from ray.rllib.utils.typing import PolicyID, SampleBatchType +from ray.util.annotations import DeveloperAPI +from ray.util.debug import log_once + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class ReplayMode(Enum): + LOCKSTEP = "lockstep" + INDEPENDENT = "independent" + + +@DeveloperAPI +def merge_dicts_with_warning(args_on_init, args_on_call): + """Merge argument dicts, overwriting args_on_call with warning. + + The MultiAgentReplayBuffer supports setting standard arguments for calls + of methods of the underlying buffers. These arguments can be + overwritten. Such overwrites trigger a warning to the user. + """ + for arg_name, arg_value in args_on_call.items(): + if arg_name in args_on_init: + if log_once("overwrite_argument_{}".format((str(arg_name)))): + logger.warning( + "Replay Buffer was initialized to have " + "underlying buffers methods called with " + "argument `{}={}`, but was subsequently called " + "with `{}={}`.".format( + arg_name, + args_on_init[arg_name], + arg_name, + arg_value, + ) + ) + return {**args_on_init, **args_on_call} + + +@DeveloperAPI +class MultiAgentReplayBuffer(ReplayBuffer): + """A replay buffer shard for multiagent setups. + + This buffer is meant to be run in parallel to distribute experiences + across `num_shards` shards. Unlike simpler buffers, it holds a set of + buffers - one for each policy ID. + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: str = "timesteps", + num_shards: int = 1, + replay_mode: str = "independent", + replay_sequence_override: bool = True, + replay_sequence_length: int = 1, + replay_burn_in: int = 0, + replay_zero_init_states: bool = True, + underlying_buffer_config: dict = None, + **kwargs, + ): + """Initializes a MultiAgentReplayBuffer instance. + + Args: + capacity: The capacity of the buffer, measured in `storage_unit`. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. If they + are stored in episodes, replay_sequence_length is ignored. + num_shards: The number of buffer shards that exist in total + (including this one). + replay_mode: One of "independent" or "lockstep". Determines, + whether batches are sampled independently or to an equal + amount. + replay_sequence_override: If True, ignore sequences found in incoming + batches, slicing them into sequences as specified by + `replay_sequence_length` and `replay_sequence_burn_in`. This only has + an effect if storage_unit is `sequences`. + replay_sequence_length: The sequence length (T) of a single + sample. If > 1, we will sample B x T from this buffer. This + only has an effect if storage_unit is 'timesteps'. + replay_burn_in: This is the number of timesteps + each sequence overlaps with the previous one to generate a + better internal state (=state after the burn-in), instead of + starting from 0.0 each RNN rollout. This only has an effect + if storage_unit is `sequences`. + replay_zero_init_states: Whether the initial states in the + buffer (if replay_sequence_length > 0) are alwayas 0.0 or + should be updated with the previous train_batch state outputs. + underlying_buffer_config: A config that contains all necessary + constructor arguments and arguments for methods to call on + the underlying buffers. + ``**kwargs``: Forward compatibility kwargs. + """ + shard_capacity = capacity // num_shards + ReplayBuffer.__init__(self, capacity, storage_unit) + + # If the user provides an underlying buffer config, we use to + # instantiate and interact with underlying buffers + self.underlying_buffer_config = underlying_buffer_config + if self.underlying_buffer_config is not None: + self.underlying_buffer_call_args = self.underlying_buffer_config + else: + self.underlying_buffer_call_args = {} + self.replay_sequence_override = replay_sequence_override + self.replay_mode = replay_mode + self.replay_sequence_length = replay_sequence_length + self.replay_burn_in = replay_burn_in + self.replay_zero_init_states = replay_zero_init_states + self.replay_sequence_override = replay_sequence_override + + if ( + replay_sequence_length > 1 + and self.storage_unit is not StorageUnit.SEQUENCES + ): + logger.warning( + "MultiAgentReplayBuffer configured with " + "`replay_sequence_length={}`, but `storage_unit={}`. " + "replay_sequence_length will be ignored and set to 1.".format( + replay_sequence_length, storage_unit + ) + ) + self.replay_sequence_length = 1 + + if replay_sequence_length == 1 and self.storage_unit is StorageUnit.SEQUENCES: + logger.warning( + "MultiAgentReplayBuffer configured with " + "`replay_sequence_length={}`, but `storage_unit={}`. " + "This will result in sequences equal to timesteps.".format( + replay_sequence_length, storage_unit + ) + ) + + if replay_mode in ["lockstep", ReplayMode.LOCKSTEP]: + self.replay_mode = ReplayMode.LOCKSTEP + if self.storage_unit in [StorageUnit.EPISODES, StorageUnit.SEQUENCES]: + raise ValueError( + "MultiAgentReplayBuffer does not support " + "lockstep mode with storage unit `episodes`" + "or `sequences`." + ) + elif replay_mode in ["independent", ReplayMode.INDEPENDENT]: + self.replay_mode = ReplayMode.INDEPENDENT + else: + raise ValueError("Unsupported replay mode: {}".format(replay_mode)) + + if self.underlying_buffer_config: + ctor_args = { + **{"capacity": shard_capacity, "storage_unit": StorageUnit.FRAGMENTS}, + **self.underlying_buffer_config, + } + + def new_buffer(): + return from_config(self.underlying_buffer_config["type"], ctor_args) + + else: + # Default case + def new_buffer(): + self.underlying_buffer_call_args = {} + return ReplayBuffer( + self.capacity, + storage_unit=StorageUnit.FRAGMENTS, + ) + + self.replay_buffers = collections.defaultdict(new_buffer) + + # Metrics. + self.add_batch_timer = _Timer() + self.replay_timer = _Timer() + self._num_added = 0 + + def __len__(self) -> int: + """Returns the number of items currently stored in this buffer.""" + return sum(len(buffer._storage) for buffer in self.replay_buffers.values()) + + @DeveloperAPI + @Deprecated( + old="ReplayBuffer.replay()", + new="ReplayBuffer.sample(num_items)", + error=True, + ) + def replay(self, num_items: int = None, **kwargs) -> Optional[SampleBatchType]: + """Deprecated in favor of new ReplayBuffer API.""" + pass + + @DeveloperAPI + @override(ReplayBuffer) + def add(self, batch: SampleBatchType, **kwargs) -> None: + """Adds a batch to the appropriate policy's replay buffer. + + Turns the batch into a MultiAgentBatch of the DEFAULT_POLICY_ID if + it is not a MultiAgentBatch. Subsequently, adds the individual policy + batches to the storage. + + Args: + batch : The batch to be added. + ``**kwargs``: Forward compatibility kwargs. + """ + if batch is None: + if log_once("empty_batch_added_to_buffer"): + logger.info( + "A batch that is `None` was added to {}. This can be " + "normal at the beginning of execution but might " + "indicate an issue.".format(type(self).__name__) + ) + return + # Make a copy so the replay buffer doesn't pin plasma memory. + batch = batch.copy() + # Handle everything as if multi-agent. + batch = batch.as_multi_agent() + + with self.add_batch_timer: + pids_and_batches = self._maybe_split_into_policy_batches(batch) + for policy_id, sample_batch in pids_and_batches.items(): + self._add_to_underlying_buffer(policy_id, sample_batch, **kwargs) + + self._num_added += batch.count + + @DeveloperAPI + def _add_to_underlying_buffer( + self, policy_id: PolicyID, batch: SampleBatchType, **kwargs + ) -> None: + """Add a batch of experiences to the underlying buffer of a policy. + + If the storage unit is `timesteps`, cut the batch into timeslices + before adding them to the appropriate buffer. Otherwise, let the + underlying buffer decide how slice batches. + + Args: + policy_id: ID of the policy that corresponds to the underlying + buffer + batch: SampleBatch to add to the underlying buffer + ``**kwargs``: Forward compatibility kwargs. + """ + # Merge kwargs, overwriting standard call arguments + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + # For the storage unit `timesteps`, the underlying buffer will + # simply store the samples how they arrive. For sequences and + # episodes, the underlying buffer may split them itself. + if self.storage_unit is StorageUnit.TIMESTEPS: + timeslices = batch.timeslices(1) + elif self.storage_unit is StorageUnit.SEQUENCES: + timeslices = timeslice_along_seq_lens_with_overlap( + sample_batch=batch, + seq_lens=batch.get(SampleBatch.SEQ_LENS) + if self.replay_sequence_override + else None, + zero_pad_max_seq_len=self.replay_sequence_length, + pre_overlap=self.replay_burn_in, + zero_init_states=self.replay_zero_init_states, + ) + elif self.storage_unit == StorageUnit.EPISODES: + timeslices = [] + for eps in batch.split_by_episode(): + if eps.get(SampleBatch.T)[0] == 0 and ( + eps.get(SampleBatch.TERMINATEDS, [True])[-1] + or eps.get(SampleBatch.TRUNCATEDS, [False])[-1] + ): + # Only add full episodes to the buffer + timeslices.append(eps) + else: + if log_once("only_full_episodes"): + logger.info( + "This buffer uses episodes as a storage " + "unit and thus allows only full episodes " + "to be added to it. Some samples may be " + "dropped." + ) + elif self.storage_unit == StorageUnit.FRAGMENTS: + timeslices = [batch] + else: + raise ValueError("Unknown `storage_unit={}`".format(self.storage_unit)) + + for slice in timeslices: + self.replay_buffers[policy_id].add(slice, **kwargs) + + @DeveloperAPI + @override(ReplayBuffer) + def sample( + self, num_items: int, policy_id: Optional[PolicyID] = None, **kwargs + ) -> Optional[SampleBatchType]: + """Samples a MultiAgentBatch of `num_items` per one policy's buffer. + + If less than `num_items` records are in the policy's buffer, + some samples in the results may be repeated to fulfil the batch size + `num_items` request. Returns an empty batch if there are no items in + the buffer. + + Args: + num_items: Number of items to sample from a policy's buffer. + policy_id: ID of the policy that created the experiences we sample. If + none is given, sample from all policies. + + Returns: + Concatenated MultiAgentBatch of items. + ``**kwargs``: Forward compatibility kwargs. + """ + # Merge kwargs, overwriting standard call arguments + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + with self.replay_timer: + # Lockstep mode: Sample from all policies at the same time an + # equal amount of steps. + if self.replay_mode == ReplayMode.LOCKSTEP: + assert ( + policy_id is None + ), "`policy_id` specifier not allowed in `lockstep` mode!" + # In lockstep mode we sample MultiAgentBatches + return self.replay_buffers[_ALL_POLICIES].sample(num_items, **kwargs) + elif policy_id is not None: + sample = self.replay_buffers[policy_id].sample(num_items, **kwargs) + return MultiAgentBatch({policy_id: sample}, sample.count) + else: + samples = {} + for policy_id, replay_buffer in self.replay_buffers.items(): + samples[policy_id] = replay_buffer.sample(num_items, **kwargs) + return MultiAgentBatch(samples, sum(s.count for s in samples.values())) + + @DeveloperAPI + @override(ReplayBuffer) + def stats(self, debug: bool = False) -> Dict: + """Returns the stats of this buffer and all underlying buffers. + + Args: + debug: If True, stats of underlying replay buffers + are fetched with debug=True. + + Returns: + stat: Dictionary of buffer stats. + """ + stat = { + "add_batch_time_ms": round(1000 * self.add_batch_timer.mean, 3), + "replay_time_ms": round(1000 * self.replay_timer.mean, 3), + } + for policy_id, replay_buffer in self.replay_buffers.items(): + stat.update( + {"policy_{}".format(policy_id): replay_buffer.stats(debug=debug)} + ) + return stat + + @DeveloperAPI + @override(ReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + state = {"num_added": self._num_added, "replay_buffers": {}} + for policy_id, replay_buffer in self.replay_buffers.items(): + state["replay_buffers"][policy_id] = replay_buffer.get_state() + return state + + @DeveloperAPI + @override(ReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by + calling `self.get_state()`. + """ + self._num_added = state["num_added"] + buffer_states = state["replay_buffers"] + for policy_id in buffer_states.keys(): + self.replay_buffers[policy_id].set_state(buffer_states[policy_id]) + + def _maybe_split_into_policy_batches(self, batch: SampleBatchType): + """Returns a dict of policy IDs and batches, depending on our replay mode. + + This method helps with splitting up MultiAgentBatches only if the + self.replay_mode requires it. + """ + if self.replay_mode == ReplayMode.LOCKSTEP: + return {_ALL_POLICIES: batch} + else: + return batch.policy_batches diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/prioritized_episode_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/prioritized_episode_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..dc00b94cb0d05d6c36a22601ffe01214276776e1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/prioritized_episode_buffer.py @@ -0,0 +1,732 @@ +import copy +import hashlib +import numpy as np +import scipy + +from collections import deque +from numpy.typing import NDArray +from typing import Any, Dict, List, Optional, Tuple, Union + +from ray.rllib.core import DEFAULT_AGENT_ID, DEFAULT_MODULE_ID +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.execution.segment_tree import MinSegmentTree, SumSegmentTree +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + override, +) +from ray.rllib.utils.replay_buffers.episode_replay_buffer import EpisodeReplayBuffer +from ray.rllib.utils.typing import ModuleID, SampleBatchType + + +class PrioritizedEpisodeReplayBuffer(EpisodeReplayBuffer): + """Prioritized Replay Buffer that stores episodes by their ID. + + This replay buffer stores episode data (more specifically `SingleAgentEpisode` + objects) and implements prioritized experience replay first proposed + in the paper by Schaul et al. (2016, https://arxiv.org/abs/1511.05952). + + Implementation is based on segment trees as suggested by the authors of + the cited paper, i.e. we use proportional prioritization with an order + of O(log N) in updating and sampling. + + Each "row" (a slot in a deque) in the buffer is occupied by one episode. If an + incomplete episode is added to the buffer and then another chunk of that episode is + added at a later time, the buffer will automatically concatenate the new fragment to + the original episode. This way, episodes can be completed via subsequent `add` + calls. + + Sampling returns a size `B` episode list (number of 'rows'), where each episode + holds a tuple tuple of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation `o_t`, + `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is the sum of + all rewards collected over the time steps between `t+1` and `t+n`. The `n`-step can + be chosen freely when sampling and defaults to `1`. If `n_step` is a tuple it is + sampled uniformly across the interval defined by the tuple (for each row in the + batch). + + Each episode contains - in addition to the data tuples presented above - two further + elements in its ` extra_model_outputs`, namely `n_steps` and `weights`. The former + holds the `n_step` used for the sampled timesteps in the episode and the latter the + corresponding (importance sampling) weight for the transition. + + After sampling priorities can be updated (for the last sampled episode list) with + `self.update_priorities`. This method assigns the new priorities automatically to + the last sampled timesteps. Note, this implies that sampling timesteps and updating + their corresponding priorities needs to alternate (e.g. sampling several times and + then updating the priorities would not work because the buffer caches the last + sampled timestep indices). + + .. testcode:: + + import gymnasium as gym + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.replay_buffers import ( + PrioritizedEpisodeReplayBuffer + ) + + # Create the environment. + env = gym.make("CartPole-v1") + + # Set up the loop variables + terminated = False + truncated = False + num_timesteps = 10000 + episodes = [] + + # Initialize the first episode entries. + eps = SingleAgentEpisode() + obs, info = env.reset() + eps.add_env_reset(obs, info) + + # Sample 10,000 timesteps. + for i in range(num_timesteps): + # If terminated we create a new episode. + if terminated: + episodes.append(eps.to_numpy()) + eps = SingleAgentEpisode() + obs, info = env.reset() + eps.add_env_reset(obs, info) + + action = env.action_space.sample() + obs, reward, terminated, truncated, info = env.step(action) + eps.add_env_step( + obs, + action, + reward, + info, + terminated=terminated, + truncated=truncated + ) + + # Add the last (truncated) episode to the list of episodes. + if not terminated or truncated: + episodes.append(eps) + + # Create the buffer. + buffer = PrioritizedEpisodeReplayBuffer() + # Add the list of episodes sampled. + buffer.add(episodes) + + # Pull a sample from the buffer using an `n-step` of 3. + sample = buffer.sample(num_items=256, gamma=0.95, n_step=3) + """ + + def __init__( + self, + capacity: int = 10000, + *, + batch_size_B: int = 16, + batch_length_T: int = 1, + alpha: float = 1.0, + metrics_num_episodes_for_smoothing: int = 100, + **kwargs, + ): + """Initializes a `PrioritizedEpisodeReplayBuffer` object + + Args: + capacity: The total number of timesteps to be storable in this buffer. + Will start ejecting old episodes once this limit is reached. + batch_size_B: The number of episodes returned from `sample()`. + batch_length_T: The length of each episode in the episode list returned from + `sample()`. + alpha: The amount of prioritization to be used: `alpha=1.0` means full + prioritization, `alpha=0.0` means no prioritization. + """ + super().__init__( + capacity=capacity, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + metrics_num_episodes_for_smoothing=metrics_num_episodes_for_smoothing, + ) + + # `alpha` should be non-negative. + assert alpha >= 0 + self._alpha = alpha + + # Initialize segment trees for the priority weights. Note, b/c the trees + # are binary we need for them a capacity that is an exponential of 2. + # Double it to enable temporary buffer overflow (we need then free nodes + # in the trees). + tree_capacity = int(2 ** np.ceil(np.log2(self.capacity))) + + self._max_priority = 1.0 + self._sum_segment = SumSegmentTree(2 * tree_capacity) + self._min_segment = MinSegmentTree(2 * tree_capacity) + # At initialization all nodes are free. + self._free_nodes = deque( + list(range(2 * tree_capacity)), maxlen=2 * tree_capacity + ) + # Keep track of the maximum index used from the trees. This helps + # to not traverse the complete trees. + self._max_idx = 0 + # Map from tree indices to sample indices (i.e. `self._indices`). + self._tree_idx_to_sample_idx = {} + # Keep track of the indices that were sampled last for updating the + # weights later. + self._last_sampled_indices = [] + + @override(EpisodeReplayBuffer) + def add( + self, + episodes: Union[List["SingleAgentEpisode"], "SingleAgentEpisode"], + weight: Optional[float] = None, + ) -> None: + """Adds incoming episodes to the replay buffer. + + Note, if the incoming episodes' time steps cause the buffer to overflow, + older episodes are evicted. Because episodes usually come in chunks and + not complete, this could lead to edge cases (e.g. with very small capacity + or very long episode length) where the first part of an episode is evicted + while the next part just comes in. + To defend against such case, the complete episode is evicted, including + the new chunk, unless the episode is the only one in the buffer. In the + latter case the buffer will be allowed to overflow in a temporary fashion, + i.e. during the next addition of samples to the buffer an attempt is made + to fall below capacity again. + + The user is advised to select a large enough buffer with regard to the maximum + expected episode length. + + Args: + episodes: A list of `SingleAgentEpisode`s that contain the episode data. + weight: A starting priority for the time steps in `episodes`. If `None` + the maximum priority is used, i.e. 1.0 (as suggested in the original + paper we scale weights to the interval [0.0, 1.0]).. + """ + + # TODO (sven, simon): Eventually allow here an array? + if weight is None: + weight = self._max_priority + + episodes = force_list(episodes) + + # Set up some counters for metrics. + num_env_steps_added = 0 + agent_to_num_steps_added = {DEFAULT_AGENT_ID: 0} + module_to_num_steps_added = {DEFAULT_MODULE_ID: 0} + num_episodes_added = 0 + agent_to_num_episodes_added = {DEFAULT_AGENT_ID: 0} + module_to_num_episodes_added = {DEFAULT_MODULE_ID: 0} + num_episodes_evicted = 0 + agent_to_num_episodes_evicted = {DEFAULT_AGENT_ID: 0} + module_to_num_episodes_evicted = {DEFAULT_MODULE_ID: 0} + num_env_steps_evicted = 0 + agent_to_num_steps_evicted = {DEFAULT_AGENT_ID: 0} + module_to_num_steps_evicted = {DEFAULT_MODULE_ID: 0} + + # Add first the timesteps of new episodes to have info about how many + # episodes should be evicted to stay below capacity. + new_episode_ids = [] + for eps in episodes: + new_episode_ids.append(eps.id_) + self._num_timesteps += len(eps) + self._num_timesteps_added += len(eps) + + eps_evicted = [] + eps_evicted_ids = [] + eps_evicted_idxs = [] + while ( + self._num_timesteps > self.capacity + and self._num_remaining_episodes(new_episode_ids, eps_evicted_ids) != 1 + ): + # Evict episode + eps_evicted.append(self.episodes.popleft()) + eps_evicted_ids.append(eps_evicted[-1].id_) + eps_evicted_idxs.append(self.episode_id_to_index.pop(eps_evicted_ids[-1])) + num_episodes_evicted += 1 + num_env_steps_evicted += len(eps_evicted[-1]) + agent_to_num_episodes_evicted[DEFAULT_AGENT_ID] += 1 + agent_to_num_steps_evicted[DEFAULT_AGENT_ID] += eps_evicted[ + -1 + ].agent_steps() + module_to_num_episodes_evicted[DEFAULT_MODULE_ID] += 1 + module_to_num_steps_evicted[DEFAULT_MODULE_ID] += eps_evicted[ + -1 + ].agent_steps() + # If this episode has a new chunk in the new episodes added, + # we subtract it again. + # TODO (sven, simon): Should we just treat such an episode chunk + # as a new episode? + if eps_evicted_ids[-1] in new_episode_ids: + # TODO (simon): Apply the same logic as in the MA-case. + len_to_subtract = len( + episodes[new_episode_ids.index(eps_evicted_idxs[-1])] + ) + self._num_timesteps -= len_to_subtract + self._num_timesteps_added -= len_to_subtract + # Remove the timesteps of the evicted episode from the counter. + self._num_timesteps -= len(eps_evicted[-1]) + self._num_episodes_evicted += 1 + + # Remove corresponding indices, if episodes were evicted. + # TODO (simon): Refactor into method such that MultiAgent + # version can inherit. + if eps_evicted_idxs: + new_indices = [] + i = 0 + for idx_triple in self._indices: + # If the index comes from an evicted episode free the nodes. + if idx_triple[0] in eps_evicted_idxs: + # Here we need the index of a sample in the segment tree. + self._free_nodes.appendleft(idx_triple[2]) + # Also remove the potentially maximum index. + self._max_idx -= 1 if self._max_idx == idx_triple[2] else 0 + self._sum_segment[idx_triple[2]] = 0.0 + self._min_segment[idx_triple[2]] = float("inf") + self._tree_idx_to_sample_idx.pop(idx_triple[2]) + # Otherwise update the index in the index mapping. + else: + new_indices.append(idx_triple) + self._tree_idx_to_sample_idx[idx_triple[2]] = i + i += 1 + # Assign the new list of indices. + self._indices = new_indices + + # Now append the indices for the new episodes. + j = len(self._indices) + for eps in episodes: + # If the episode chunk is part of an evicted episode continue. + if eps.id_ in eps_evicted_ids: + continue + # Otherwise, add the episode data to the buffer. + else: + eps = copy.deepcopy(eps) + # If the episode is part of an already existing episode, concatenate. + if eps.id_ in self.episode_id_to_index: + eps_idx = self.episode_id_to_index[eps.id_] + existing_eps = self.episodes[eps_idx - self._num_episodes_evicted] + old_len = len(existing_eps) + self._indices.extend( + [ + ( + eps_idx, + old_len + i, + # Get the index in the segment trees. + self._get_free_node_and_assign(j + i, weight), + ) + for i in range(len(eps)) + ] + ) + existing_eps.concat_episode(eps) + # Otherwise, create a new entry. + else: + num_episodes_added += 1 + agent_to_num_episodes_added[DEFAULT_AGENT_ID] += 1 + module_to_num_episodes_added[DEFAULT_MODULE_ID] += 1 + self.episodes.append(eps) + eps_idx = len(self.episodes) - 1 + self._num_episodes_evicted + self.episode_id_to_index[eps.id_] = eps_idx + self._indices.extend( + [ + ( + eps_idx, + i, + self._get_free_node_and_assign(j + i, weight), + ) + for i in range(len(eps)) + ] + ) + num_env_steps_added += len(eps) + agent_to_num_steps_added[DEFAULT_AGENT_ID] += eps.agent_steps() + module_to_num_steps_added[DEFAULT_MODULE_ID] += eps.agent_steps() + # Increase index to the new length of `self._indices`. + j = len(self._indices) + + # Increase metrics. + self._update_add_metrics( + num_episodes_added=num_episodes_added, + num_env_steps_added=num_env_steps_added, + num_episodes_evicted=num_episodes_evicted, + num_env_steps_evicted=num_env_steps_evicted, + agent_to_num_episodes_added=agent_to_num_episodes_added, + agent_to_num_steps_added=agent_to_num_steps_added, + agent_to_num_episodes_evicted=agent_to_num_episodes_evicted, + agent_to_num_steps_evicted=agent_to_num_steps_evicted, + module_to_num_episodes_added=module_to_num_steps_added, + module_to_num_steps_added=module_to_num_episodes_added, + module_to_num_episodes_evicted=module_to_num_episodes_evicted, + module_to_num_steps_evicted=module_to_num_steps_evicted, + ) + + @override(EpisodeReplayBuffer) + def sample( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = None, + beta: float = 0.0, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + to_numpy: bool = False, + **kwargs, + ) -> SampleBatchType: + """Samples from a buffer in a prioritized way. + + This sampling method also adds (importance sampling) weights to + the returned batch. See for prioritized sampling Schaul et al. + (2016). + + Each sampled item defines a transition of the form: + + `(o_t, a_t, sum(r_(t+1:t+n+1)), o_(t+n), terminated_(t+n), truncated_(t+n))` + + where `o_(t+n)` is drawn by prioritized sampling, i.e. the priority + of `o_(t+n)` led to the sample and defines the importance weight that + is returned in the sample batch. `n` is defined by the `n_step` applied. + + If requested, `info`s of a transitions last timestep `t+n` are added to + the batch. + + Args: + num_items: Number of items (transitions) to sample from this + buffer. + batch_size_B: The number of rows (transitions) to return in the + batch + batch_length_T: THe sequence length to sample. At this point in time + only sequences of length 1 are possible. + n_step: The n-step to apply. For the default the batch contains in + `"new_obs"` the observation and in `"obs"` the observation `n` + time steps before. The reward will be the sum of rewards + collected in between these two observations and the action will + be the one executed n steps before such that we always have the + state-action pair that triggered the rewards. + If `n_step` is a tuple, it is considered as a range to sample + from. If `None`, we use `n_step=1`. + beta: The exponent of the importance sampling weight (see Schaul et + al. (2016)). A `beta=0.0` does not correct for the bias introduced + by prioritized replay and `beta=1.0` fully corrects for it. + gamma: The discount factor to be used when applying n-step calculations. + The default of `0.99` should be replaced by the `Algorithm`s + discount factor. + include_infos: A boolean indicating, if `info`s should be included in + the batch. This could be of advantage, if the `info` contains + values from the environment important for loss computation. If + `True`, the info at the `"new_obs"` in the batch is included. + include_extra_model_outputs: A boolean indicating, if + `extra_model_outputs` should be included in the batch. This could be + of advantage, if the `extra_mdoel_outputs` contain outputs from the + model important for loss computation and only able to compute with the + actual state of model e.g. action log-probabilities, etc.). If `True`, + the extra model outputs at the `"obs"` in the batch is included (the + timestep at which the action is computed). + + Returns: + A list of 1-step long episodes containing all basic episode data and if + requested infos and extra model outputs. + """ + assert beta >= 0.0 + + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + # TODO (simon): Implement trajectory sampling for RNNs. + batch_length_T = batch_length_T or self.batch_length_T + + # Sample the n-step if necessary. + actual_n_step = n_step or 1 + random_n_step = isinstance(n_step, tuple) + + # Keep track of the indices that were sampled last for updating the + # weights later (see `ray.rllib.utils.replay_buffer.utils. + # update_priorities_in_episode_replay_buffer`). + self._last_sampled_indices = [] + + sampled_episodes = [] + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + # Record all n-steps that have been used. + sampled_n_steps = [] + # Record the number of times it needs to be resampled. + num_resamples = 0 + + # Sample proportionally from replay buffer's segments using the weights. + total_segment_sum = self._sum_segment.sum() + p_min = self._min_segment.min() / total_segment_sum + max_weight = (p_min * self.get_num_timesteps()) ** (-beta) + B = 0 + while B < batch_size_B: + # First, draw a random sample from Uniform(0, sum over all weights). + # Note, transitions with higher weight get sampled more often (as + # more random draws fall into larger intervals). + random_sum = self.rng.random() * self._sum_segment.sum() + # Get the highest index in the sum-tree for which the sum is + # smaller or equal the random sum sample. + # Note, in contrast to Schaul et al. (2018) (who sample `o_(t + n_step)`, + # Algorithm 1) we sample `o_t`. + idx = self._sum_segment.find_prefixsum_idx(random_sum) + # Get the theoretical probability mass for drawing this sample. + p_sample = self._sum_segment[idx] / total_segment_sum + # Compute the importance sampling weight. + weight = (p_sample * self.get_num_timesteps()) ** (-beta) + # Now, get the transition stored at this index. + index_triple = self._indices[self._tree_idx_to_sample_idx[idx]] + + # Compute the actual episode index (offset by the number of + # already evicted episodes) + episode_idx, episode_ts = ( + index_triple[0] - self._num_episodes_evicted, + index_triple[1], + ) + episode = self.episodes[episode_idx] + + # If we use random n-step sampling, draw the n-step for this item. + if random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + + # Skip, if we are too far to the end and `episode_ts` + n_step would go + # beyond the episode's end. + if episode_ts + actual_n_step > len(episode): + num_resamples += 1 + continue + + # Note, this will be the reward after executing action + # `a_(episode_ts-n_step+1)`. For `n_step>1` this will be the discounted + # sum of all discounted rewards that were collected over the last n steps. + raw_rewards = episode.get_rewards( + slice(episode_ts, episode_ts + actual_n_step) + ) + rewards = scipy.signal.lfilter([1], [1, -gamma], raw_rewards[::-1], axis=0)[ + -1 + ] + + # Generate the episode to be returned. + sampled_episode = SingleAgentEpisode( + # Ensure that each episode contains a tuple of the form: + # (o_t, a_t, sum(r_(t:t+n_step)), o_(t+n_step)) + # Two observations (t and t+n). + observations=[ + episode.get_observations(episode_ts), + episode.get_observations(episode_ts + actual_n_step), + ], + observation_space=episode.observation_space, + infos=( + [ + episode.get_infos(episode_ts), + episode.get_infos(episode_ts + actual_n_step), + ] + if include_infos + else None + ), + actions=[episode.get_actions(episode_ts)], + action_space=episode.action_space, + rewards=[rewards], + # If the sampled time step is the episode's last time step check, if + # the episode is terminated or truncated. + terminated=( + False + if episode_ts + actual_n_step < len(episode) + else episode.is_terminated + ), + truncated=( + False + if episode_ts + actual_n_step < len(episode) + else episode.is_truncated + ), + extra_model_outputs={ + # TODO (simon): Check, if we have to correct here for sequences + # later. + "weights": [weight / max_weight * 1], # actual_size=1 + "n_step": [actual_n_step], + **( + { + k: [episode.get_extra_model_outputs(k, episode_ts)] + for k in episode.extra_model_outputs.keys() + } + if include_extra_model_outputs + else {} + ), + }, + # TODO (sven): Support lookback buffers. + len_lookback_buffer=0, + t_started=episode_ts, + ) + # Record here the episode time step via a hash code. + sampled_env_step_idxs.add( + hashlib.sha256(f"{episode.id_}-{episode_ts}".encode()).hexdigest() + ) + # Convert to numpy arrays, if required. + if to_numpy: + sampled_episode.to_numpy() + sampled_episodes.append(sampled_episode) + + # Add the episode buffer index to the sampled indices. + sampled_episode_idxs.add(episode_idx) + # Record the actual n-step for this sample. + sampled_n_steps.append(actual_n_step) + + # Increment counter. + B += 1 + + # Keep track of sampled indices for updating priorities later. + self._last_sampled_indices.append(idx) + + # Add to the sampled timesteps counter of the buffer. + self.sampled_timesteps += batch_size_B + + # Update the sample metrics. + num_env_steps_sampled = batch_size_B + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + sampled_n_step = sum(sampled_n_steps) / batch_size_B + agent_to_num_steps_sampled = {DEFAULT_AGENT_ID: num_env_steps_sampled} + agent_to_num_episodes_per_sample = {DEFAULT_AGENT_ID: num_episodes_per_sample} + agent_to_num_steps_per_sample = {DEFAULT_AGENT_ID: num_env_steps_per_sample} + agent_to_sampled_n_step = {DEFAULT_AGENT_ID: sampled_n_step} + agent_to_num_resamples = {DEFAULT_AGENT_ID: num_resamples} + module_to_num_steps_sampled = {DEFAULT_MODULE_ID: num_env_steps_sampled} + module_to_num_episodes_per_sample = {DEFAULT_MODULE_ID: num_episodes_per_sample} + module_to_num_steps_per_sample = {DEFAULT_MODULE_ID: num_env_steps_per_sample} + module_to_sampled_n_step = {DEFAULT_MODULE_ID: sampled_n_step} + module_to_num_resamples = {DEFAULT_MODULE_ID: num_resamples} + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + sampled_n_step=sampled_n_step, + num_resamples=num_resamples, + agent_to_num_steps_sampled=agent_to_num_steps_sampled, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_sampled_n_step=agent_to_sampled_n_step, + agent_to_num_resamples=agent_to_num_resamples, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_sampled_n_step=module_to_sampled_n_step, + module_to_num_resamples=module_to_num_resamples, + ) + + return sampled_episodes + + @override(EpisodeReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Gets the state of a `PrioritizedEpisodeReplayBuffer`. + + Returns: + A state dict that can be stored in a checkpoint. + """ + # Get super's state. + state = super().get_state() + # Add additional attributes. + state.update( + { + "_sum_segment": self._sum_segment.get_state(), + "_min_segment": self._min_segment.get_state(), + "_free_nodes": list(self._free_nodes), + "_max_priority": self._max_priority, + "_max_idx": self._max_idx, + "_tree_idx_to_sample_idx": list(self._tree_idx_to_sample_idx.items()), + # TODO (sven, simon): Do we need these? + "_last_sampled_indices": self._last_sampled_indices, + } + ) + return state + + @override(EpisodeReplayBuffer) + def set_state(self, state) -> None: + """Sets the state of a `PrioritizedEpisodeReplayBuffer`. + + Args: + state: A buffer state stored (usually stored in a checkpoint). + """ + # Set super's state. + super().set_state(state) + # Set additional attributes. + self._sum_segment.set_state(state["_sum_segment"]) + self._min_segment.set_state(state["_min_segment"]) + self._free_nodes = deque(state["_free_nodes"]) + self._max_priority = state["_max_priority"] + self._max_idx = state["_max_idx"] + self._tree_idx_to_sample_idx = dict(state["_tree_idx_to_sample_idx"]) + # TODO (sven, simon): Do we need these? + self._last_sampled_indices = state["_last_sampled_indices"] + + def update_priorities( + self, priorities: NDArray, module_id: Optional[ModuleID] = None + ) -> None: + """Update the priorities of items at corresponding indices. + + Usually, incoming priorities are TD-errors. + + Args: + priorities: Numpy array containing the new priorities to be used + in sampling for the items in the last sampled batch. + """ + assert len(priorities) == len(self._last_sampled_indices) + + for idx, priority in zip(self._last_sampled_indices, priorities): + # Note, TD-errors come in as absolute values or results from + # cross-entropy loss calculations. + # assert priority > 0, f"priority was {priority}" + priority = max(priority, 1e-12) + assert 0 <= idx < self._sum_segment.capacity + # TODO (simon): Create metrics. + # delta = priority**self._alpha - self._sum_segment[idx] + # Update the priorities in the segment trees. + self._sum_segment[idx] = priority**self._alpha + self._min_segment[idx] = priority**self._alpha + # Update the maximal priority. + self._max_priority = max(self._max_priority, priority) + self._last_sampled_indices.clear() + + def _get_free_node_and_assign(self, sample_index, weight: float = 1.0) -> int: + """Gets the next free node in the segment trees. + + In addition the initial priorities for a new transition are added + to the segment trees and the index of the nodes is added to the + index mapping. + + Args: + sample_index: The index of the sample in the `self._indices` list. + weight: The initial priority weight to be used in sampling for + the item at index `sample_index`. + + Returns: + The index in the segment trees `self._sum_segment` and + `self._min_segment` for the item at index `sample_index` in + ``self._indices`. + """ + # Get an index from the free nodes in the segment trees. + idx = self._free_nodes.popleft() + self._max_idx = idx if idx > self._max_idx else self._max_idx + # Add the weight to the segments. + self._sum_segment[idx] = weight**self._alpha + self._min_segment[idx] = weight**self._alpha + # Map the index in the trees to the index in `self._indices`. + self._tree_idx_to_sample_idx[idx] = sample_index + # Return the index. + return idx + + def _num_remaining_episodes(self, new_eps, evicted_eps): + """Calculates the number of remaining episodes. + + When adding episodes and evicting them in the `add()` method + this function calculates iteratively the number of remaining + episodes. + + Args: + new_eps: List of new episode IDs. + evicted_eps: List of evicted episode IDs. + + Returns: + Number of episodes remaining after evicting the episodes in + `evicted_eps` and adding the episode in `new_eps`. + """ + return len( + set(self.episode_id_to_index.keys()).union(set(new_eps)) - set(evicted_eps) + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/prioritized_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/prioritized_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..00db60b7adfaad1867a445ee376b7a6f0f815f2a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/prioritized_replay_buffer.py @@ -0,0 +1,240 @@ +import random +from typing import Any, Dict, List, Optional +import numpy as np + +# Import ray before psutil will make sure we use psutil's bundled version +import ray # noqa F401 +import psutil # noqa E402 + +from ray.rllib.execution.segment_tree import SumSegmentTree, MinSegmentTree +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics.window_stat import WindowStat +from ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer +from ray.rllib.utils.typing import SampleBatchType +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class PrioritizedReplayBuffer(ReplayBuffer): + """This buffer implements Prioritized Experience Replay. + + The algorithm has been described by Tom Schaul et. al. in "Prioritized + Experience Replay". See https://arxiv.org/pdf/1511.05952.pdf for + the full paper. + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: str = "timesteps", + alpha: float = 1.0, + **kwargs, + ): + """Initializes a PrioritizedReplayBuffer instance. + + Args: + capacity: Max number of timesteps to store in the FIFO + buffer. After reaching this number, older samples will be + dropped to make space for new ones. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. + alpha: How much prioritization is used + (0.0=no prioritization, 1.0=full prioritization). + ``**kwargs``: Forward compatibility kwargs. + """ + ReplayBuffer.__init__(self, capacity, storage_unit, **kwargs) + + assert alpha > 0 + self._alpha = alpha + + # Segment tree must have capacity that is a power of 2 + it_capacity = 1 + while it_capacity < self.capacity: + it_capacity *= 2 + + self._it_sum = SumSegmentTree(it_capacity) + self._it_min = MinSegmentTree(it_capacity) + self._max_priority = 1.0 + self._prio_change_stats = WindowStat("reprio", 1000) + + @DeveloperAPI + @override(ReplayBuffer) + def _add_single_batch(self, item: SampleBatchType, **kwargs) -> None: + """Add a batch of experiences to self._storage with weight. + + An item consists of either one or more timesteps, a sequence or an + episode. Differs from add() in that it does not consider the storage + unit or type of batch and simply stores it. + + Args: + item: The item to be added. + ``**kwargs``: Forward compatibility kwargs. + """ + weight = kwargs.get("weight", None) + + if weight is None: + weight = self._max_priority + + self._it_sum[self._next_idx] = weight**self._alpha + self._it_min[self._next_idx] = weight**self._alpha + + ReplayBuffer._add_single_batch(self, item) + + def _sample_proportional(self, num_items: int) -> List[int]: + res = [] + for _ in range(num_items): + # TODO(szymon): should we ensure no repeats? + mass = random.random() * self._it_sum.sum(0, len(self._storage)) + idx = self._it_sum.find_prefixsum_idx(mass) + res.append(idx) + return res + + @DeveloperAPI + @override(ReplayBuffer) + def sample( + self, num_items: int, beta: float, **kwargs + ) -> Optional[SampleBatchType]: + """Sample `num_items` items from this buffer, including prio. weights. + + Samples in the results may be repeated. + + Examples for storage of SamplesBatches: + - If storage unit `timesteps` has been chosen and batches of + size 5 have been added, sample(5) will yield a concatenated batch of + 15 timesteps. + - If storage unit 'sequences' has been chosen and sequences of + different lengths have been added, sample(5) will yield a concatenated + batch with a number of timesteps equal to the sum of timesteps in + the 5 sampled sequences. + - If storage unit 'episodes' has been chosen and episodes of + different lengths have been added, sample(5) will yield a concatenated + batch with a number of timesteps equal to the sum of timesteps in + the 5 sampled episodes. + + Args: + num_items: Number of items to sample from this buffer. + beta: To what degree to use importance weights (0 - no corrections, + 1 - full correction). + ``**kwargs``: Forward compatibility kwargs. + + Returns: + Concatenated SampleBatch of items including "weights" and + "batch_indexes" fields denoting IS of each sampled + transition and original idxes in buffer of sampled experiences. + """ + assert beta >= 0.0 + + if len(self) == 0: + raise ValueError("Trying to sample from an empty buffer.") + + idxes = self._sample_proportional(num_items) + + weights = [] + batch_indexes = [] + p_min = self._it_min.min() / self._it_sum.sum() + max_weight = (p_min * len(self)) ** (-beta) + + for idx in idxes: + p_sample = self._it_sum[idx] / self._it_sum.sum() + weight = (p_sample * len(self)) ** (-beta) + count = self._storage[idx].count + # If zero-padded, count will not be the actual batch size of the + # data. + if ( + isinstance(self._storage[idx], SampleBatch) + and self._storage[idx].zero_padded + ): + actual_size = self._storage[idx].max_seq_len + else: + actual_size = count + weights.extend([weight / max_weight] * actual_size) + batch_indexes.extend([idx] * actual_size) + self._num_timesteps_sampled += count + batch = self._encode_sample(idxes) + + # Note: prioritization is not supported in multi agent lockstep + if isinstance(batch, SampleBatch): + batch["weights"] = np.array(weights) + batch["batch_indexes"] = np.array(batch_indexes) + + return batch + + @DeveloperAPI + def update_priorities(self, idxes: List[int], priorities: List[float]) -> None: + """Update priorities of items at given indices. + + Sets priority of item at index idxes[i] in buffer + to priorities[i]. + + Args: + idxes: List of indices of items + priorities: List of updated priorities corresponding to items at the + idxes denoted by variable `idxes`. + """ + # Making sure we don't pass in e.g. a torch tensor. + assert isinstance( + idxes, (list, np.ndarray) + ), "ERROR: `idxes` is not a list or np.ndarray, but {}!".format( + type(idxes).__name__ + ) + assert len(idxes) == len(priorities) + for idx, priority in zip(idxes, priorities): + assert priority > 0 + assert 0 <= idx < len(self._storage) + delta = priority**self._alpha - self._it_sum[idx] + self._prio_change_stats.push(delta) + self._it_sum[idx] = priority**self._alpha + self._it_min[idx] = priority**self._alpha + + self._max_priority = max(self._max_priority, priority) + + @DeveloperAPI + @override(ReplayBuffer) + def stats(self, debug: bool = False) -> Dict: + """Returns the stats of this buffer. + + Args: + debug: If true, adds sample eviction statistics to the returned stats dict. + + Returns: + A dictionary of stats about this buffer. + """ + parent = ReplayBuffer.stats(self, debug) + if debug: + parent.update(self._prio_change_stats.stats()) + return parent + + @DeveloperAPI + @override(ReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + # Get parent state. + state = super().get_state() + # Add prio weights. + state.update( + { + "sum_segment_tree": self._it_sum.get_state(), + "min_segment_tree": self._it_min.get_state(), + "max_priority": self._max_priority, + } + ) + return state + + @DeveloperAPI + @override(ReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by calling + `self.get_state()`. + """ + super().set_state(state) + self._it_sum.set_state(state["sum_segment_tree"]) + self._it_min.set_state(state["min_segment_tree"]) + self._max_priority = state["max_priority"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd2c2c378ab6d93ed66d45c62c72a8317e3cbb8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/replay_buffer.py @@ -0,0 +1,374 @@ +from enum import Enum +import logging +import numpy as np +import random +from typing import Any, Dict, List, Optional, Union + +# Import ray before psutil will make sure we use psutil's bundled version +import ray # noqa F401 +import psutil + +from ray.rllib.policy.sample_batch import SampleBatch, concat_samples +from ray.rllib.utils.actor_manager import FaultAwareApply +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics.window_stat import WindowStat +from ray.rllib.utils.replay_buffers.base import ReplayBufferInterface +from ray.rllib.utils.typing import SampleBatchType +from ray.util.annotations import DeveloperAPI +from ray.util.debug import log_once + +# Constant that represents all policies in lockstep replay mode. +_ALL_POLICIES = "__all__" + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class StorageUnit(Enum): + """Specifies how batches are structured in a ReplayBuffer. + + timesteps: One buffer slot per timestep. + sequences: One buffer slot per sequence. + episodes: One buffer slot per episode. + fragemts: One buffer slot per incoming batch. + """ + + TIMESTEPS = "timesteps" + SEQUENCES = "sequences" + EPISODES = "episodes" + FRAGMENTS = "fragments" + + +@DeveloperAPI +def warn_replay_capacity(*, item: SampleBatchType, num_items: int) -> None: + """Warn if the configured replay buffer capacity is too large.""" + if log_once("replay_capacity"): + item_size = item.size_bytes() + psutil_mem = psutil.virtual_memory() + total_gb = psutil_mem.total / 1e9 + mem_size = num_items * item_size / 1e9 + msg = ( + "Estimated max memory usage for replay buffer is {} GB " + "({} batches of size {}, {} bytes each), " + "available system memory is {} GB".format( + mem_size, num_items, item.count, item_size, total_gb + ) + ) + if mem_size > total_gb: + raise ValueError(msg) + elif mem_size > 0.2 * total_gb: + logger.warning(msg) + else: + logger.info(msg) + + +@DeveloperAPI +class ReplayBuffer(ReplayBufferInterface, FaultAwareApply): + """The lowest-level replay buffer interface used by RLlib. + + This class implements a basic ring-type of buffer with random sampling. + ReplayBuffer is the base class for advanced types that add functionality while + retaining compatibility through inheritance. + + The following examples show how buffers behave with different storage_units + and capacities. This behaviour is generally similar for other buffers, although + they might not implement all storage_units. + + Examples: + + .. testcode:: + + from ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer + from ray.rllib.utils.replay_buffers.replay_buffer import StorageUnit + from ray.rllib.policy.sample_batch import SampleBatch + + # Store any batch as a whole + buffer = ReplayBuffer(capacity=10, storage_unit=StorageUnit.FRAGMENTS) + buffer.add(SampleBatch({"a": [1], "b": [2, 3, 4]})) + buffer.sample(1) + + # Store only complete episodes + buffer = ReplayBuffer(capacity=10, + storage_unit=StorageUnit.EPISODES) + buffer.add(SampleBatch({"c": [1, 2, 3, 4], + SampleBatch.T: [0, 1, 0, 1], + SampleBatch.TERMINATEDS: [False, True, False, True], + SampleBatch.EPS_ID: [0, 0, 1, 1]})) + buffer.sample(1) + + # Store single timesteps + buffer = ReplayBuffer(capacity=2, storage_unit=StorageUnit.TIMESTEPS) + buffer.add(SampleBatch({"a": [1, 2], SampleBatch.T: [0, 1]})) + buffer.sample(1) + + buffer.add(SampleBatch({"a": [3], SampleBatch.T: [2]})) + print(buffer._eviction_started) + buffer.sample(1) + + buffer = ReplayBuffer(capacity=10, storage_unit=StorageUnit.SEQUENCES) + buffer.add(SampleBatch({"c": [1, 2, 3], SampleBatch.SEQ_LENS: [1, 2]})) + buffer.sample(1) + + .. testoutput:: + + True + + `True` is not the output of the above testcode, but an artifact of unexpected + behaviour of sphinx doctests. + (see https://github.com/ray-project/ray/pull/32477#discussion_r1106776101) + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: Union[str, StorageUnit] = "timesteps", + **kwargs, + ): + """Initializes a (FIFO) ReplayBuffer instance. + + Args: + capacity: Max number of timesteps to store in this FIFO + buffer. After reaching this number, older samples will be + dropped to make space for new ones. + storage_unit: If not a StorageUnit, either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. + ``**kwargs``: Forward compatibility kwargs. + """ + + if storage_unit in ["timesteps", StorageUnit.TIMESTEPS]: + self.storage_unit = StorageUnit.TIMESTEPS + elif storage_unit in ["sequences", StorageUnit.SEQUENCES]: + self.storage_unit = StorageUnit.SEQUENCES + elif storage_unit in ["episodes", StorageUnit.EPISODES]: + self.storage_unit = StorageUnit.EPISODES + elif storage_unit in ["fragments", StorageUnit.FRAGMENTS]: + self.storage_unit = StorageUnit.FRAGMENTS + else: + raise ValueError( + f"storage_unit must be either '{StorageUnit.TIMESTEPS}', " + f"'{StorageUnit.SEQUENCES}', '{StorageUnit.EPISODES}' " + f"or '{StorageUnit.FRAGMENTS}', but is {storage_unit}" + ) + + # The actual storage (list of SampleBatches or MultiAgentBatches). + self._storage = [] + + # Caps the number of timesteps stored in this buffer + if capacity <= 0: + raise ValueError( + "Capacity of replay buffer has to be greater than zero " + "but was set to {}.".format(capacity) + ) + self.capacity = capacity + # The next index to override in the buffer. + self._next_idx = 0 + # len(self._hit_count) must always be less than len(capacity) + self._hit_count = np.zeros(self.capacity) + + # Whether we have already hit our capacity (and have therefore + # started to evict older samples). + self._eviction_started = False + + # Number of (single) timesteps that have been added to the buffer + # over its lifetime. Note that each added item (batch) may contain + # more than one timestep. + self._num_timesteps_added = 0 + self._num_timesteps_added_wrap = 0 + + # Number of (single) timesteps that have been sampled from the buffer + # over its lifetime. + self._num_timesteps_sampled = 0 + + self._evicted_hit_stats = WindowStat("evicted_hit", 1000) + self._est_size_bytes = 0 + + self.batch_size = None + + @override(ReplayBufferInterface) + def __len__(self) -> int: + return len(self._storage) + + @override(ReplayBufferInterface) + def add(self, batch: SampleBatchType, **kwargs) -> None: + """Adds a batch of experiences or other data to this buffer. + + Splits batch into chunks of timesteps, sequences or episodes, depending on + `self._storage_unit`. Calls `self._add_single_batch` to add resulting slices + to the buffer storage. + + Args: + batch: The batch to add. + ``**kwargs``: Forward compatibility kwargs. + """ + if not batch.count > 0: + return + + warn_replay_capacity(item=batch, num_items=self.capacity / batch.count) + + if self.storage_unit == StorageUnit.TIMESTEPS: + timeslices = batch.timeslices(1) + for t in timeslices: + self._add_single_batch(t, **kwargs) + + elif self.storage_unit == StorageUnit.SEQUENCES: + timestep_count = 0 + for seq_len in batch.get(SampleBatch.SEQ_LENS): + start_seq = timestep_count + end_seq = timestep_count + seq_len + self._add_single_batch(batch[start_seq:end_seq], **kwargs) + timestep_count = end_seq + + elif self.storage_unit == StorageUnit.EPISODES: + for eps in batch.split_by_episode(): + if eps.get(SampleBatch.T, [0])[0] == 0 and ( + eps.get(SampleBatch.TERMINATEDS, [True])[-1] + or eps.get(SampleBatch.TRUNCATEDS, [False])[-1] + ): + # Only add full episodes to the buffer + # Check only if info is available + self._add_single_batch(eps, **kwargs) + else: + if log_once("only_full_episodes"): + logger.info( + "This buffer uses episodes as a storage " + "unit and thus allows only full episodes " + "to be added to it (starting from T=0 and ending in " + "`terminateds=True` or `truncateds=True`. " + "Some samples may be dropped." + ) + + elif self.storage_unit == StorageUnit.FRAGMENTS: + self._add_single_batch(batch, **kwargs) + + @DeveloperAPI + def _add_single_batch(self, item: SampleBatchType, **kwargs) -> None: + """Add a SampleBatch of experiences to self._storage. + + An item consists of either one or more timesteps, a sequence or an + episode. Differs from add() in that it does not consider the storage + unit or type of batch and simply stores it. + + Args: + item: The batch to be added. + ``**kwargs``: Forward compatibility kwargs. + """ + self._num_timesteps_added += item.count + self._num_timesteps_added_wrap += item.count + + if self._next_idx >= len(self._storage): + self._storage.append(item) + self._est_size_bytes += item.size_bytes() + else: + item_to_be_removed = self._storage[self._next_idx] + self._est_size_bytes -= item_to_be_removed.size_bytes() + self._storage[self._next_idx] = item + self._est_size_bytes += item.size_bytes() + + # Eviction of older samples has already started (buffer is "full"). + if self._eviction_started: + self._evicted_hit_stats.push(self._hit_count[self._next_idx]) + self._hit_count[self._next_idx] = 0 + + # Wrap around storage as a circular buffer once we hit capacity. + if self._num_timesteps_added_wrap >= self.capacity: + self._eviction_started = True + self._num_timesteps_added_wrap = 0 + self._next_idx = 0 + else: + self._next_idx += 1 + + @override(ReplayBufferInterface) + def sample( + self, num_items: Optional[int] = None, **kwargs + ) -> Optional[SampleBatchType]: + """Samples `num_items` items from this buffer. + + The items depend on the buffer's storage_unit. + Samples in the results may be repeated. + + Examples for sampling results: + + 1) If storage unit 'timesteps' has been chosen and batches of + size 5 have been added, sample(5) will yield a concatenated batch of + 15 timesteps. + + 2) If storage unit 'sequences' has been chosen and sequences of + different lengths have been added, sample(5) will yield a concatenated + batch with a number of timesteps equal to the sum of timesteps in + the 5 sampled sequences. + + 3) If storage unit 'episodes' has been chosen and episodes of + different lengths have been added, sample(5) will yield a concatenated + batch with a number of timesteps equal to the sum of timesteps in + the 5 sampled episodes. + + Args: + num_items: Number of items to sample from this buffer. + ``**kwargs``: Forward compatibility kwargs. + + Returns: + Concatenated batch of items. + """ + if len(self) == 0: + raise ValueError("Trying to sample from an empty buffer.") + idxes = [random.randint(0, len(self) - 1) for _ in range(num_items)] + sample = self._encode_sample(idxes) + self._num_timesteps_sampled += sample.count + return sample + + @DeveloperAPI + def stats(self, debug: bool = False) -> dict: + """Returns the stats of this buffer. + + Args: + debug: If True, adds sample eviction statistics to the returned + stats dict. + + Returns: + A dictionary of stats about this buffer. + """ + data = { + "added_count": self._num_timesteps_added, + "added_count_wrapped": self._num_timesteps_added_wrap, + "eviction_started": self._eviction_started, + "sampled_count": self._num_timesteps_sampled, + "est_size_bytes": self._est_size_bytes, + "num_entries": len(self._storage), + } + if debug: + data.update(self._evicted_hit_stats.stats()) + return data + + @override(ReplayBufferInterface) + def get_state(self) -> Dict[str, Any]: + state = {"_storage": self._storage, "_next_idx": self._next_idx} + state.update(self.stats(debug=False)) + return state + + @override(ReplayBufferInterface) + def set_state(self, state: Dict[str, Any]) -> None: + # The actual storage. + self._storage = state["_storage"] + self._next_idx = state["_next_idx"] + # Stats and counts. + self._num_timesteps_added = state["added_count"] + self._num_timesteps_added_wrap = state["added_count_wrapped"] + self._eviction_started = state["eviction_started"] + self._num_timesteps_sampled = state["sampled_count"] + self._est_size_bytes = state["est_size_bytes"] + + @DeveloperAPI + def _encode_sample(self, idxes: List[int]) -> SampleBatchType: + """Fetches concatenated samples at given indices from the storage.""" + samples = [] + for i in idxes: + self._hit_count[i] += 1 + samples.append(self._storage[i]) + + if samples: + # We assume all samples are of same type + out = concat_samples(samples) + else: + out = SampleBatch() + out.decompress_if_needed() + return out diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/reservoir_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/reservoir_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..6cf098b1567ac23ea71b371a59867206159605a8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/reservoir_replay_buffer.py @@ -0,0 +1,132 @@ +from typing import Any, Dict +import random + +# Import ray before psutil will make sure we use psutil's bundled version +import ray # noqa F401 +import psutil # noqa E402 + +from ray.rllib.utils.annotations import ExperimentalAPI, override +from ray.rllib.utils.replay_buffers.replay_buffer import ( + ReplayBuffer, + warn_replay_capacity, +) +from ray.rllib.utils.typing import SampleBatchType + + +# __sphinx_doc_reservoir_buffer__begin__ +@ExperimentalAPI +class ReservoirReplayBuffer(ReplayBuffer): + """This buffer implements reservoir sampling. + + The algorithm has been described by Jeffrey S. Vitter in "Random sampling + with a reservoir". + """ + + def __init__( + self, capacity: int = 10000, storage_unit: str = "timesteps", **kwargs + ): + """Initializes a ReservoirBuffer instance. + + Args: + capacity: Max number of timesteps to store in the FIFO + buffer. After reaching this number, older samples will be + dropped to make space for new ones. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. + """ + ReplayBuffer.__init__(self, capacity, storage_unit) + self._num_add_calls = 0 + self._num_evicted = 0 + + @ExperimentalAPI + @override(ReplayBuffer) + def _add_single_batch(self, item: SampleBatchType, **kwargs) -> None: + """Add a SampleBatch of experiences to self._storage. + + An item consists of either one or more timesteps, a sequence or an + episode. Differs from add() in that it does not consider the storage + unit or type of batch and simply stores it. + + Args: + item: The batch to be added. + ``**kwargs``: Forward compatibility kwargs. + """ + self._num_timesteps_added += item.count + self._num_timesteps_added_wrap += item.count + + # Update add counts. + self._num_add_calls += 1 + # Update our timesteps counts. + + if self._num_timesteps_added < self.capacity: + self._storage.append(item) + self._est_size_bytes += item.size_bytes() + else: + # Eviction of older samples has already started (buffer is "full") + self._eviction_started = True + idx = random.randint(0, self._num_add_calls - 1) + if idx < len(self._storage): + self._num_evicted += 1 + self._evicted_hit_stats.push(self._hit_count[idx]) + self._hit_count[idx] = 0 + # This is a bit of a hack: ReplayBuffer always inserts at + # self._next_idx + self._next_idx = idx + self._evicted_hit_stats.push(self._hit_count[idx]) + self._hit_count[idx] = 0 + + item_to_be_removed = self._storage[idx] + self._est_size_bytes -= item_to_be_removed.size_bytes() + self._storage[idx] = item + self._est_size_bytes += item.size_bytes() + + assert item.count > 0, item + warn_replay_capacity(item=item, num_items=self.capacity / item.count) + + @ExperimentalAPI + @override(ReplayBuffer) + def stats(self, debug: bool = False) -> dict: + """Returns the stats of this buffer. + + Args: + debug: If True, adds sample eviction statistics to the returned + stats dict. + + Returns: + A dictionary of stats about this buffer. + """ + data = { + "num_evicted": self._num_evicted, + "num_add_calls": self._num_add_calls, + } + parent = ReplayBuffer.stats(self, debug) + parent.update(data) + return parent + + @ExperimentalAPI + @override(ReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + parent = ReplayBuffer.get_state(self) + parent.update(self.stats()) + return parent + + @ExperimentalAPI + @override(ReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be + obtained by calling `self.get_state()`. + """ + self._num_evicted = state["num_evicted"] + self._num_add_calls = state["num_add_calls"] + ReplayBuffer.set_state(self, state) + + +# __sphinx_doc_reservoir_buffer__end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/simple_replay_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/simple_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..16fa37d0626ff1cad5b617e8f17e5d4f0c5a5079 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/replay_buffers/utils.py @@ -0,0 +1,440 @@ +import logging +import psutil +from typing import Any, Dict, Optional + +import numpy as np + +from ray.rllib.utils import deprecation_warning +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.deprecation import DEPRECATED_VALUE +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.metrics import ALL_MODULES, TD_ERROR_KEY +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.replay_buffers import ( + EpisodeReplayBuffer, + MultiAgentPrioritizedReplayBuffer, + PrioritizedEpisodeReplayBuffer, + ReplayBuffer, + MultiAgentReplayBuffer, +) +from ray.rllib.policy.sample_batch import concat_samples, MultiAgentBatch, SampleBatch +from ray.rllib.utils.typing import ( + AlgorithmConfigDict, + ModuleID, + ResultDict, + SampleBatchType, + TensorType, +) +from ray.util import log_once +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +def update_priorities_in_episode_replay_buffer( + *, + replay_buffer: EpisodeReplayBuffer, + td_errors: Dict[ModuleID, TensorType], +) -> None: + # Only update priorities, if the buffer supports them. + if isinstance(replay_buffer, PrioritizedEpisodeReplayBuffer): + + # The `ResultDict` will be multi-agent. + for module_id, td_error in td_errors.items(): + # Skip the `"__all__"` keys. + if module_id in ["__all__", ALL_MODULES]: + continue + + # Warn once, if we have no TD-errors to update priorities. + if TD_ERROR_KEY not in td_error or td_error[TD_ERROR_KEY] is None: + if log_once( + "no_td_error_in_train_results_from_module_{}".format(module_id) + ): + logger.warning( + "Trying to update priorities for module with ID " + f"`{module_id}` in prioritized episode replay buffer without " + "providing `td_errors` in train_results. Priority update for " + "this policy is being skipped." + ) + continue + # TODO (simon): Implement multi-agent version. Remove, happens in buffer. + # assert len(td_error[TD_ERROR_KEY]) == len( + # replay_buffer._last_sampled_indices + # ) + # TODO (simon): Implement for stateful modules. + + replay_buffer.update_priorities(td_error[TD_ERROR_KEY], module_id) + + +@OldAPIStack +def update_priorities_in_replay_buffer( + replay_buffer: ReplayBuffer, + config: AlgorithmConfigDict, + train_batch: SampleBatchType, + train_results: ResultDict, +) -> None: + """Updates the priorities in a prioritized replay buffer, given training results. + + The `abs(TD-error)` from the loss (inside `train_results`) is used as new + priorities for the row-indices that were sampled for the train batch. + + Don't do anything if the given buffer does not support prioritized replay. + + Args: + replay_buffer: The replay buffer, whose priority values to update. This may also + be a buffer that does not support priorities. + config: The Algorithm's config dict. + train_batch: The batch used for the training update. + train_results: A train results dict, generated by e.g. the `train_one_step()` + utility. + """ + # Only update priorities if buffer supports them. + if isinstance(replay_buffer, MultiAgentPrioritizedReplayBuffer): + # Go through training results for the different policies (maybe multi-agent). + prio_dict = {} + for policy_id, info in train_results.items(): + # TODO(sven): This is currently structured differently for + # torch/tf. Clean up these results/info dicts across + # policies (note: fixing this in torch_policy.py will + # break e.g. DDPPO!). + td_error = info.get("td_error", info[LEARNER_STATS_KEY].get("td_error")) + + policy_batch = train_batch.policy_batches[policy_id] + # Set the get_interceptor to None in order to be able to access the numpy + # arrays directly (instead of e.g. a torch array). + policy_batch.set_get_interceptor(None) + # Get the replay buffer row indices that make up the `train_batch`. + batch_indices = policy_batch.get("batch_indexes") + + if SampleBatch.SEQ_LENS in policy_batch: + # Batch_indices are represented per column, in order to update + # priorities, we need one index per td_error + _batch_indices = [] + + # Sequenced batches have been zero padded to max_seq_len. + # Depending on how batches are split during learning, not all + # sequences have an associated td_error (trailing ones missing). + if policy_batch.zero_padded: + seq_lens = len(td_error) * [policy_batch.max_seq_len] + else: + seq_lens = policy_batch[SampleBatch.SEQ_LENS][: len(td_error)] + + # Go through all indices by sequence that they represent and shrink + # them to one index per sequences + sequence_sum = 0 + for seq_len in seq_lens: + _batch_indices.append(batch_indices[sequence_sum]) + sequence_sum += seq_len + batch_indices = np.array(_batch_indices) + + if td_error is None: + if log_once( + "no_td_error_in_train_results_from_policy_{}".format(policy_id) + ): + logger.warning( + "Trying to update priorities for policy with id `{}` in " + "prioritized replay buffer without providing td_errors in " + "train_results. Priority update for this policy is being " + "skipped.".format(policy_id) + ) + continue + + if batch_indices is None: + if log_once( + "no_batch_indices_in_train_result_for_policy_{}".format(policy_id) + ): + logger.warning( + "Trying to update priorities for policy with id `{}` in " + "prioritized replay buffer without providing batch_indices in " + "train_batch. Priority update for this policy is being " + "skipped.".format(policy_id) + ) + continue + + # Try to transform batch_indices to td_error dimensions + if len(batch_indices) != len(td_error): + T = replay_buffer.replay_sequence_length + assert ( + len(batch_indices) > len(td_error) and len(batch_indices) % T == 0 + ) + batch_indices = batch_indices.reshape([-1, T])[:, 0] + assert len(batch_indices) == len(td_error) + prio_dict[policy_id] = (batch_indices, td_error) + + # Make the actual buffer API call to update the priority weights on all + # policies. + replay_buffer.update_priorities(prio_dict) + + +@DeveloperAPI +def sample_min_n_steps_from_buffer( + replay_buffer: ReplayBuffer, min_steps: int, count_by_agent_steps: bool +) -> Optional[SampleBatchType]: + """Samples a minimum of n timesteps from a given replay buffer. + + This utility method is primarily used by the QMIX algorithm and helps with + sampling a given number of time steps which has stored samples in units + of sequences or complete episodes. Samples n batches from replay buffer + until the total number of timesteps reaches `train_batch_size`. + + Args: + replay_buffer: The replay buffer to sample from + num_timesteps: The number of timesteps to sample + count_by_agent_steps: Whether to count agent steps or env steps + + Returns: + A concatenated SampleBatch or MultiAgentBatch with samples from the + buffer. + """ + train_batch_size = 0 + train_batches = [] + while train_batch_size < min_steps: + batch = replay_buffer.sample(num_items=1) + batch_len = batch.agent_steps() if count_by_agent_steps else batch.env_steps() + if batch_len == 0: + # Replay has not started, so we can't accumulate timesteps here + return batch + train_batches.append(batch) + train_batch_size += batch_len + # All batch types are the same type, hence we can use any concat_samples() + train_batch = concat_samples(train_batches) + return train_batch + + +@DeveloperAPI +def validate_buffer_config(config: dict) -> None: + """Checks and fixes values in the replay buffer config. + + Checks the replay buffer config for common misconfigurations, warns or raises + error in case validation fails. The type "key" is changed into the inferred + replay buffer class. + + Args: + config: The replay buffer config to be validated. + + Raises: + ValueError: When detecting severe misconfiguration. + """ + if config.get("replay_buffer_config", None) is None: + config["replay_buffer_config"] = {} + + if config.get("worker_side_prioritization", DEPRECATED_VALUE) != DEPRECATED_VALUE: + deprecation_warning( + old="config['worker_side_prioritization']", + new="config['replay_buffer_config']['worker_side_prioritization']", + error=True, + ) + + prioritized_replay = config.get("prioritized_replay", DEPRECATED_VALUE) + if prioritized_replay != DEPRECATED_VALUE: + deprecation_warning( + old="config['prioritized_replay'] or config['replay_buffer_config'][" + "'prioritized_replay']", + help="Replay prioritization specified by config key. RLlib's new replay " + "buffer API requires setting `config[" + "'replay_buffer_config']['type']`, e.g. `config[" + "'replay_buffer_config']['type'] = " + "'MultiAgentPrioritizedReplayBuffer'` to change the default " + "behaviour.", + error=True, + ) + + capacity = config.get("buffer_size", DEPRECATED_VALUE) + if capacity == DEPRECATED_VALUE: + capacity = config["replay_buffer_config"].get("buffer_size", DEPRECATED_VALUE) + if capacity != DEPRECATED_VALUE: + deprecation_warning( + old="config['buffer_size'] or config['replay_buffer_config'][" + "'buffer_size']", + new="config['replay_buffer_config']['capacity']", + error=True, + ) + + replay_burn_in = config.get("burn_in", DEPRECATED_VALUE) + if replay_burn_in != DEPRECATED_VALUE: + config["replay_buffer_config"]["replay_burn_in"] = replay_burn_in + deprecation_warning( + old="config['burn_in']", + help="config['replay_buffer_config']['replay_burn_in']", + ) + + replay_batch_size = config.get("replay_batch_size", DEPRECATED_VALUE) + if replay_batch_size == DEPRECATED_VALUE: + replay_batch_size = config["replay_buffer_config"].get( + "replay_batch_size", DEPRECATED_VALUE + ) + if replay_batch_size != DEPRECATED_VALUE: + deprecation_warning( + old="config['replay_batch_size'] or config['replay_buffer_config'][" + "'replay_batch_size']", + help="Specification of replay_batch_size is not supported anymore but is " + "derived from `train_batch_size`. Specify the number of " + "items you want to replay upon calling the sample() method of replay " + "buffers if this does not work for you.", + error=True, + ) + + # Deprecation of old-style replay buffer args + # Warnings before checking of we need local buffer so that algorithms + # Without local buffer also get warned + keys_with_deprecated_positions = [ + "prioritized_replay_alpha", + "prioritized_replay_beta", + "prioritized_replay_eps", + "no_local_replay_buffer", + "replay_zero_init_states", + "replay_buffer_shards_colocated_with_driver", + ] + for k in keys_with_deprecated_positions: + if config.get(k, DEPRECATED_VALUE) != DEPRECATED_VALUE: + deprecation_warning( + old="config['{}']".format(k), + help="config['replay_buffer_config']['{}']" "".format(k), + error=False, + ) + # Copy values over to new location in config to support new + # and old configuration style. + if config.get("replay_buffer_config") is not None: + config["replay_buffer_config"][k] = config[k] + + learning_starts = config.get( + "learning_starts", + config.get("replay_buffer_config", {}).get("learning_starts", DEPRECATED_VALUE), + ) + if learning_starts != DEPRECATED_VALUE: + deprecation_warning( + old="config['learning_starts'] or" + "config['replay_buffer_config']['learning_starts']", + help="config['num_steps_sampled_before_learning_starts']", + error=True, + ) + config["num_steps_sampled_before_learning_starts"] = learning_starts + + # Can't use DEPRECATED_VALUE here because this is also a deliberate + # value set for some algorithms + # TODO: (Artur): Compare to DEPRECATED_VALUE on deprecation + replay_sequence_length = config.get("replay_sequence_length", None) + if replay_sequence_length is not None: + config["replay_buffer_config"][ + "replay_sequence_length" + ] = replay_sequence_length + deprecation_warning( + old="config['replay_sequence_length']", + help="Replay sequence length specified at new " + "location config['replay_buffer_config'][" + "'replay_sequence_length'] will be overwritten.", + error=True, + ) + + replay_buffer_config = config["replay_buffer_config"] + assert ( + "type" in replay_buffer_config + ), "Can not instantiate ReplayBuffer from config without 'type' key." + + # Check if old replay buffer should be instantiated + buffer_type = config["replay_buffer_config"]["type"] + + if isinstance(buffer_type, str) and buffer_type.find(".") == -1: + # Create valid full [module].[class] string for from_config + config["replay_buffer_config"]["type"] = ( + "ray.rllib.utils.replay_buffers." + buffer_type + ) + + # Instantiate a dummy buffer to fail early on misconfiguration and find out about + # inferred buffer class + dummy_buffer = from_config(buffer_type, config["replay_buffer_config"]) + + config["replay_buffer_config"]["type"] = type(dummy_buffer) + + if hasattr(dummy_buffer, "update_priorities"): + if ( + config["replay_buffer_config"].get("replay_mode", "independent") + == "lockstep" + ): + raise ValueError( + "Prioritized replay is not supported when replay_mode=lockstep." + ) + elif config["replay_buffer_config"].get("replay_sequence_length", 0) > 1: + raise ValueError( + "Prioritized replay is not supported when " + "replay_sequence_length > 1." + ) + else: + if config["replay_buffer_config"].get("worker_side_prioritization"): + raise ValueError( + "Worker side prioritization is not supported when " + "prioritized_replay=False." + ) + + +@DeveloperAPI +def warn_replay_buffer_capacity(*, item: SampleBatchType, capacity: int) -> None: + """Warn if the configured replay buffer capacity is too large for machine's memory. + + Args: + item: A (example) item that's supposed to be added to the buffer. + This is used to compute the overall memory footprint estimate for the + buffer. + capacity: The capacity value of the buffer. This is interpreted as the + number of items (such as given `item`) that will eventually be stored in + the buffer. + + Raises: + ValueError: If computed memory footprint for the buffer exceeds the machine's + RAM. + """ + if log_once("warn_replay_buffer_capacity"): + item_size = item.size_bytes() + psutil_mem = psutil.virtual_memory() + total_gb = psutil_mem.total / 1e9 + mem_size = capacity * item_size / 1e9 + msg = ( + "Estimated max memory usage for replay buffer is {} GB " + "({} batches of size {}, {} bytes each), " + "available system memory is {} GB".format( + mem_size, capacity, item.count, item_size, total_gb + ) + ) + if mem_size > total_gb: + raise ValueError(msg) + elif mem_size > 0.2 * total_gb: + logger.warning(msg) + else: + logger.info(msg) + + +def patch_buffer_with_fake_sampling_method( + buffer: ReplayBuffer, fake_sample_output: SampleBatchType +) -> None: + """Patch a ReplayBuffer such that we always sample fake_sample_output. + + Transforms fake_sample_output into a MultiAgentBatch if it is not a + MultiAgentBatch and the buffer is a MultiAgentBuffer. This is useful for testing + purposes if we need deterministic sampling. + + Args: + buffer: The buffer to be patched + fake_sample_output: The output to be sampled + + """ + if isinstance(buffer, MultiAgentReplayBuffer) and not isinstance( + fake_sample_output, MultiAgentBatch + ): + fake_sample_output = SampleBatch(fake_sample_output).as_multi_agent() + + def fake_sample(_: Any = None, **kwargs) -> Optional[SampleBatchType]: + """Always returns a predefined batch. + + Args: + _: dummy arg to match signature of sample() method + __: dummy arg to match signature of sample() method + ``**kwargs``: dummy args to match signature of sample() method + + Returns: + Predefined MultiAgentBatch fake_sample_output + """ + + return fake_sample_output + + buffer.sample = fake_sample diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2e0addc4ee8a0534f09d1d08e3d6088061d9b54 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/runner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5965b01f511d9c0e4ba537bccc644e0dc71362d1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/runner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/runner_group.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/runner_group.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..886970943bae09ddfaf4110c058d48be75602623 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/__pycache__/runner_group.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/runner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..c7193a6719d509964bdd3cb3db5df5b2b430ebd2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/runner.py @@ -0,0 +1,105 @@ +import abc +import logging + +from typing import Any, TYPE_CHECKING + +from ray.rllib.utils.actor_manager import FaultAwareApply +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.typing import DeviceType, TensorType + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +logger = logging.getLogger(__name__) + + +class Runner(FaultAwareApply, metaclass=abc.ABCMeta): + def __init__(self, *, config: "AlgorithmConfig", **kwargs): + """Initializes a `Runner` instance. + + Args: + config: The `AlgorithmConfig` to use to setup this `Runner`. + **kwargs: Forward compatibility `kwargs`. + """ + self.worker_index: int = kwargs.get("worker_index") + self.config: AlgorithmConfig = config.copy(copy_frozen=False) + # Set the device. + self.set_device() + # Generate the `RLModule`. + self.make_module() + self._weights_seq_no = 0 + + # Create a MetricsLogger object for logging custom stats. + self.metrics: MetricsLogger = MetricsLogger() + + # Initialize the `FaultAwareApply`. + super().__init__() + + @abc.abstractmethod + def assert_healthy(self): + """Checks that self.__init__() has been completed properly. + + Useful in case an `Runner` is run as @ray.remote (Actor) and the owner + would like to make sure the Ray Actor has been properly initialized. + + Raises: + AssertionError: If the `Runner` Actor has NOT been properly initialized. + """ + + @abc.abstractmethod + def make_module(self): + """Creates the `RLModule` for this `Runner` and assigns it to `self.module`. + + Note that users should be able to change the `Runner`'s config (e.g. change + `self.config.rl_module_spec`) and then call this method to create a new `RLModule` + with the updated configuration. + """ + pass + + @abc.abstractmethod + def run(self, **kwargs) -> Any: + """Runs the `Runner`. + + The exact logic of this method could have very different forms. + + Args: + **kwargs: Forward compatibility kwargs. + + Returns: + Anything. + """ + + @abc.abstractmethod + def get_metrics(self) -> Any: + """Returns metrics (in any form) of the logic run in this `Runner`. + + Returns: + Metrics of any form. + """ + + @abc.abstractmethod + def stop(self) -> None: + """Releases all resources used by this `Runner`. + + For example, when using a `gym.Env` in this `Runner`, you should make sure + that its `close()` method is called. + """ + + @property + @abc.abstractmethod + def _device(self) -> DeviceType: + """Returns the device of this `Runner`.""" + pass + + @abc.abstractmethod + def set_device(self) -> None: + """Sets the device for this `Runner`.""" + pass + + @abc.abstractmethod + def __del__(self) -> None: + """If this Actor is deleted, clears all resources used by it.""" + + @abc.abstractmethod + def _convert_to_tensor(self, struct) -> TensorType: + """Converts structs to a framework-specific tensor.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/runner_group.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/runner_group.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb01ab37823da374b49d3097153889022e3d42a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/runners/runner_group.py @@ -0,0 +1,752 @@ +import abc +import logging +import ray + +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Tuple, + TYPE_CHECKING, + TypeVar, + Union, +) + +from ray.actor import ActorHandle +from ray.exceptions import RayActorError +from ray.rllib.core import ( + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_LEARNER, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.learner.learner_group import LearnerGroup +from ray.rllib.utils.actor_manager import FaultTolerantActorManager +from ray.rllib.utils.metrics import NUM_ENV_STEPS_SAMPLED_LIFETIME, WEIGHTS_SEQ_NO +from ray.rllib.utils.runners.runner import Runner +from ray.rllib.utils.typing import PolicyID +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +logger = logging.getLogger(__name__) + +# Generic type var for `foreach_*` methods. +T = TypeVar("T") + + +@DeveloperAPI +class RunnerGroup(metaclass=abc.ABCMeta): + def __init__( + self, + config: "AlgorithmConfig", + # TODO (simon): Check, if this is needed. Derived classes could define + # this if needed. + # default_policy_class: Optional[Type[Policy]] + local_runner: Optional[bool] = False, + logdir: Optional[str] = None, + # TODO (simon): Check, if still needed. + tune_trial_id: Optional[str] = None, + pg_offset: int = 0, + _setup: bool = True, + **kwargs: Dict[str, Any], + ) -> None: + + # TODO (simon): Remove when old stack is deprecated. + self.config: AlgorithmConfig = ( + AlgorithmConfig.from_dict(config) + if isinstance(config, dict) + else (config or AlgorithmConfig()) + ) + + self._remote_config = config + self._remote_config_obj_ref = ray.put(self._remote_config) + + self._tune_trial_id = tune_trial_id + self._pg_offset = pg_offset + + self._logdir = logdir + + self._worker_manager = FaultTolerantActorManager( + max_remote_requests_in_flight_per_actor=self._max_requests_in_flight_per_runner, + init_id=1, + ) + + if _setup: + try: + self._setup( + config=config, + num_runners=self.num_runners, + local_runner=local_runner, + **kwargs, + ) + # `RunnerGroup` creation possibly fails, if some (remote) workers cannot + # be initialized properly (due to some errors in the `Runners`'s + # constructor). + except RayActorError as e: + # In case of an actor (remote worker) init failure, the remote worker + # may still exist and will be accessible, however, e.g. calling + # its `run.remote()` would result in strange "property not found" + # errors. + if e.actor_init_failed: + # Raise the original error here that the `Runners` raised + # during its construction process. This is to enforce transparency + # for the user (better to understand the real reason behind the + # failure). + # - e.args[0]: The `RayTaskError` (inside the caught `RayActorError`). + # - e.args[0].args[2]: The original `Exception` (e.g. a `ValueError` due + # to a config mismatch) thrown inside the actor. + raise e.args[0].args[2] + # In any other case, raise the `RayActorError` as-is. + else: + raise e + + def _setup( + self, + *, + config: Optional["AlgorithmConfig"] = None, + num_runners: int = 0, + local_runner: Optional[bool] = False, + validate: Optional[bool] = None, + **kwargs: Dict[str, Any], + ) -> None: + + # TODO (simon): Deprecate this as soon as we are deprecating the old stack. + self._local_runner = None + if num_runners == 0: + local_runner = True + + self.__local_config = config + + # Create a number of @ray.remote workers. + self.add_runners( + num_runners, + validate=validate + if validate is not None + else self._validate_runners_after_construction, + **kwargs, + ) + + if local_runner: + self._local_runner = self._make_runner( + runner_index=0, + num_runners=num_runners, + config=self._local_config, + **kwargs, + ) + + def add_runners(self, num_runners: int, validate: bool = False, **kwargs) -> None: + """Creates and adds a number of remote runners to this runner set.""" + + old_num_runners = self._worker_manager.num_actors() + new_runners = [ + self._make_runner( + runner_index=old_num_runners + i + 1, + num_runners=old_num_runners + num_runners, + # `self._remote_config` can be large and it's best practice to + # pass it by reference instead of value + # (https://docs.ray.io/en/latest/ray-core/patterns/pass-large-arg-by-value.html) # noqa + config=self._remote_config_obj_ref, + **kwargs, + ) + for i in range(num_runners) + ] + # Add the new workers to the worker manager. + self._worker_manager.add_actors(new_runners) + + # Validate here, whether all remote workers have been constructed properly + # and are "up and running". Establish initial states. + if validate: + self.validate() + + def validate(self) -> Exception: + for result in self._worker_manager.foreach_actor(lambda w: w.assert_healthy()): + # Simiply raise the error, which will get handled by the try-except + # clause around the _setup(). + if not result.ok: + e = result.get() + if self._ignore_ray_errors_on_runners: + logger.error( + f"Validation of {self.runner_cls.__name__} failed! Error={str(e)}" + ) + else: + raise e + + def _make_runner( + self, + *, + runner_index: int, + num_runners: int, + recreated_runner: bool = False, + config: "AlgorithmConfig", + **kwargs, + ) -> ActorHandle: + # TODO (simon): Change this in the `EnvRunner` API + # to `runner_*`. + kwargs = dict( + config=config, + worker_index=runner_index, + num_workers=num_runners, + recreated_worker=recreated_runner, + log_dir=self._logdir, + tune_trial_id=self._tune_trial_id, + **kwargs, + ) + + # If a local runner is requested just return a runner instance. + if runner_index == 0: + return self.runner_cls(**kwargs) + + # Otherwise define a bundle index and schedule the remote worker. + pg_bundle_idx = ( + -1 + if ray.util.get_current_placement_group() is None + else self._pg_offset + runner_index + ) + return ( + ray.remote(**self._remote_args)(self.runner_cls) + .options(placement_group_bundle_index=pg_bundle_idx) + .remote(**kwargs) + ) + + def sync_runner_states( + self, + *, + config: "AlgorithmConfig", + from_runner: Optional[Runner] = None, + env_steps_sampled: Optional[int] = None, + connector_states: Optional[List[Dict[str, Any]]] = None, + rl_module_state: Optional[Dict[str, Any]] = None, + runner_indices_to_update: Optional[List[int]] = None, + env_to_module=None, + module_to_env=None, + **kwargs, + ): + """Synchronizes the connectors of this `RunnerGroup`'s `Runner`s.""" + + # If no `Runner` is passed in synchronize through the local `Runner`. + from_runner = from_runner or self.local_runner + + merge = config.merge_runner_states or ( + config.merge_runner_states == "training_only" and config.in_evaluation + ) + + broadcast = config.broadcast_runner_states + + # Early out if the number of (healthy) remote workers is 0. In this case, the + # local worker is the only operating worker and thus of course always holds + # the reference connector state. + if self.num_healthy_remote_runners == 0 and self.local_runner: + self.local_runner.set_state( + { + **( + {NUM_ENV_STEPS_SAMPLED_LIFETIME: env_steps_sampled} + if env_steps_sampled is not None + else {} + ), + **(rl_module_state or {}), + } + ) + + # Also early out, if we don't merge AND don't broadcast. + if not merge and not broadcast: + return + + # Use states from all remote `Runner`s. + if merge: + if connector_states == []: + runner_states = {} + else: + if connector_states is None: + connector_states = self.foreach_runner( + lambda w: w.get_state( + components=[ + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + ] + ), + local_runner=False, + timeout_seconds=( + config.sync_filters_on_rollout_workers_timeout_s + ), + ) + env_to_module_states = [ + s[COMPONENT_ENV_TO_MODULE_CONNECTOR] + for s in connector_states + if COMPONENT_ENV_TO_MODULE_CONNECTOR in s + ] + module_to_env_states = [ + s[COMPONENT_MODULE_TO_ENV_CONNECTOR] + for s in connector_states + if COMPONENT_MODULE_TO_ENV_CONNECTOR in s + ] + + if ( + self.local_runner is not None + and hasattr(self.local_runner, "_env_to_module") + and hasattr(self.local_runner, "_module_to_env") + ): + assert env_to_module is None + env_to_module = self.local_runner._env_to_module + assert module_to_env is None + module_to_env = self.local_runner._module_to_env + + runner_states = {} + if env_to_module_states: + runner_states.update( + { + COMPONENT_ENV_TO_MODULE_CONNECTOR: ( + env_to_module.merge_states(env_to_module_states) + ), + } + ) + if module_to_env_states: + runner_states.update( + { + COMPONENT_MODULE_TO_ENV_CONNECTOR: ( + module_to_env.merge_states(module_to_env_states) + ), + } + ) + # Ignore states from remote `Runner`s (use the current `from_worker` states + # only). + else: + if from_runner is None: + runner_states = { + COMPONENT_ENV_TO_MODULE_CONNECTOR: env_to_module.get_state(), + COMPONENT_MODULE_TO_ENV_CONNECTOR: module_to_env.get_state(), + } + else: + runner_states = from_runner.get_state( + components=[ + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + ] + ) + + # Update the global number of environment steps, if necessary. + # Make sure to divide by the number of env runners (such that each `Runner` + # knows (roughly) its own(!) lifetime count and can infer the global lifetime + # count from it). + if env_steps_sampled is not None: + runner_states[NUM_ENV_STEPS_SAMPLED_LIFETIME] = env_steps_sampled // ( + config.num_runners or 1 + ) + + # If we do NOT want remote `Runner`s to get their Connector states updated, + # only update the local worker here (with all state components, except the model + # weights) and then remove the connector components. + if not broadcast: + if self.local_runner is not None: + self.local_runner.set_state(runner_states) + else: + env_to_module.set_state( + runner_states.get(COMPONENT_ENV_TO_MODULE_CONNECTOR), {} + ) + module_to_env.set_state( + runner_states.get(COMPONENT_MODULE_TO_ENV_CONNECTOR), {} + ) + runner_states.pop(COMPONENT_ENV_TO_MODULE_CONNECTOR, None) + runner_states.pop(COMPONENT_MODULE_TO_ENV_CONNECTOR, None) + + # If there are components in the state left -> Update remote workers with these + # state components (and maybe the local worker, if it hasn't been updated yet). + if runner_states: + # Update the local `Runner`, but NOT with the weights. If used at all for + # evaluation (through the user calling `self.evaluate`), RLlib would update + # the weights up front either way. + if self.local_runner is not None and broadcast: + self.local_runner.set_state(runner_states) + + # Send the model weights only to remote `Runner`s. + # In case the local `Runner` is ever needed for evaluation, + # RLlib updates its weight right before such an eval step. + if rl_module_state: + runner_states.update(rl_module_state) + + # Broadcast updated states back to all workers. + self.foreach_runner( + "set_state", # Call the `set_state()` remote method. + kwargs=dict(state=runner_states), + remote_worker_ids=runner_indices_to_update, + local_runner=False, + timeout_seconds=0.0, # This is a state update -> Fire-and-forget. + ) + + def sync_weights( + self, + policies: Optional[List[PolicyID]] = None, + from_worker_or_learner_group: Optional[Union[Runner, "LearnerGroup"]] = None, + to_worker_indices: Optional[List[int]] = None, + timeout_seconds: Optional[float] = 0.0, + inference_only: Optional[bool] = False, + **kwargs, + ) -> None: + """Syncs model weights from the given weight source to all remote workers. + + Weight source can be either a (local) rollout worker or a learner_group. It + should just implement a `get_weights` method. + + Args: + policies: Optional list of PolicyIDs to sync weights for. + If None (default), sync weights to/from all policies. + from_worker_or_learner_group: Optional (local) `Runner` instance or + LearnerGroup instance to sync from. If None (default), + sync from this `Runner`Group's local worker. + to_worker_indices: Optional list of worker indices to sync the + weights to. If None (default), sync to all remote workers. + global_vars: An optional global vars dict to set this + worker to. If None, do not update the global_vars. + timeout_seconds: Timeout in seconds to wait for the sync weights + calls to complete. Default is 0.0 (fire-and-forget, do not wait + for any sync calls to finish). Setting this to 0.0 might significantly + improve algorithm performance, depending on the algo's `training_step` + logic. + inference_only: Sync weights with workers that keep inference-only + modules. This is needed for algorithms in the new stack that + use inference-only modules. In this case only a part of the + parameters are synced to the workers. Default is False. + """ + if self.local_runner is None and from_worker_or_learner_group is None: + raise TypeError( + "No `local_runner` in `RunnerGroup`! Must provide " + "`from_worker_or_learner_group` arg in `sync_weights()`!" + ) + + # Only sync if we have remote workers or `from_worker_or_trainer` is provided. + rl_module_state = None + if self.num_remote_runners or from_worker_or_learner_group is not None: + weights_src = ( + from_worker_or_learner_group + if from_worker_or_learner_group is not None + else self.local_runner + ) + + if weights_src is None: + raise ValueError( + "`from_worker_or_trainer` is None. In this case, `RunnerGroup`^ " + "should have `local_runner`. But `local_runner` is also `None`." + ) + + modules = ( + [COMPONENT_RL_MODULE + "/" + p for p in policies] + if policies is not None + else [COMPONENT_RL_MODULE] + ) + # LearnerGroup has-a Learner, which has-a RLModule. + if isinstance(weights_src, LearnerGroup): + rl_module_state = weights_src.get_state( + components=[COMPONENT_LEARNER + "/" + m for m in modules], + inference_only=inference_only, + )[COMPONENT_LEARNER] + # `Runner` (new API stack). + else: + # Runner (remote) has a RLModule. + # TODO (sven): Replace this with a new ActorManager API: + # try_remote_request_till_success("get_state") -> tuple(int, + # remoteresult) + # `weights_src` could be the ActorManager, then. Then RLlib would know + # that it has to ping the manager to try all healthy actors until the + # first returns something. + if isinstance(weights_src, ActorHandle): + rl_module_state = ray.get( + weights_src.get_state.remote( + components=modules, + inference_only=inference_only, + ) + ) + # `Runner` (local) has an RLModule. + else: + rl_module_state = weights_src.get_state( + components=modules, + inference_only=inference_only, + ) + + # Make sure `rl_module_state` only contains the weights and the + # weight seq no, nothing else. + rl_module_state = { + k: v + for k, v in rl_module_state.items() + if k in [COMPONENT_RL_MODULE, WEIGHTS_SEQ_NO] + } + + # Move weights to the object store to avoid having to make n pickled + # copies of the weights dict for each worker. + rl_module_state_ref = ray.put(rl_module_state) + + # Sync to specified remote workers in this `Runner`Group. + self.foreach_runner( + func="set_state", + kwargs=dict(state=rl_module_state_ref), + local_runner=False, # Do not sync back to local worker. + remote_worker_ids=to_worker_indices, + timeout_seconds=timeout_seconds, + ) + + # If `from_worker_or_learner_group` is provided, also sync to this + # `RunnerGroup`'s local worker. + if self.local_runner is not None: + if from_worker_or_learner_group is not None: + self.local_runner.set_state(rl_module_state) + + def reset(self, new_remote_runners: List[ActorHandle]) -> None: + """Hard overrides the remote `Runner`s in this set with the provided ones. + + Args: + new_remote_workers: A list of new `Runner`s (as `ActorHandles`) to use as + new remote workers. + """ + self._worker_manager.clear() + self._worker_manager.add_actors(new_remote_runners) + + def stop(self) -> None: + """Calls `stop` on all `Runner`s (including the local one).""" + try: + # Make sure we stop all `Runner`s, include the ones that were just + # restarted / recovered or that are tagged unhealthy (at least, we should + # try). + self.foreach_runner( + lambda w: w.stop(), healthy_only=False, local_runner=True + ) + except Exception: + logger.exception("Failed to stop workers!") + finally: + self._worker_manager.clear() + + def foreach_runner( + self, + func: Union[Callable[[Runner], T], List[Callable[[Runner], T]], str, List[str]], + *, + kwargs=None, + local_runner: bool = True, + healthy_only: bool = True, + remote_worker_ids: List[int] = None, + timeout_seconds: Optional[float] = None, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> List[T]: + """Calls the given function with each `Runner` as its argument. + + Args: + func: The function to call for each `Runner`s. The only call argument is + the respective `Runner` instance. + local_env_runner: Whether to apply `func` to local `Runner`, too. + Default is True. + healthy_only: Apply `func` on known-to-be healthy `Runner`s only. + remote_worker_ids: Apply `func` on a selected set of remote `Runner`s. + Use None (default) for all remote `Runner`s. + timeout_seconds: Time to wait (in seconds) for results. Set this to 0.0 for + fire-and-forget. Set this to None (default) to wait infinitely (i.e. for + synchronous execution). + return_obj_refs: Whether to return `ObjectRef` instead of actual results. + Note, for fault tolerance reasons, these returned ObjectRefs should + never be resolved with ray.get() outside of this `RunnerGroup`. + mark_healthy: Whether to mark all those `Runner`s healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that `Runner`s are NOT set unhealthy, if they simply time out + (only if they return a `RayActorError`). + Also note that this setting is ignored if `healthy_only=True` (b/c + `mark_healthy` only affects `Runner`s that are currently tagged as + unhealthy). + + Returns: + The list of return values of all calls to `func([worker])`. + """ + assert ( + not return_obj_refs or not local_runner + ), "Can not return `ObjectRef` from local worker." + + local_result = [] + if local_runner and self.local_runner is not None: + if kwargs: + local_kwargs = kwargs[0] + kwargs = kwargs[1:] + else: + local_kwargs = {} + kwargs = kwargs + if isinstance(func, str): + local_result = [getattr(self.local_runner, func)(**local_kwargs)] + else: + local_result = [func(self.local_runner, **local_kwargs)] + + if not self._worker_manager.actor_ids(): + return local_result + + remote_results = self._worker_manager.foreach_actor( + func, + kwargs=kwargs, + healthy_only=healthy_only, + remote_actor_ids=remote_worker_ids, + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + FaultTolerantActorManager.handle_remote_call_result_errors( + remote_results, ignore_ray_errors=self._ignore_ray_errors_on_runners + ) + + # With application errors handled, return good results. + remote_results = [r.get() for r in remote_results.ignore_errors()] + + return local_result + remote_results + + def foreach_runner_async( + self, + func: Union[Callable[[Runner], T], List[Callable[[Runner], T]], str, List[str]], + *, + healthy_only: bool = True, + remote_worker_ids: List[int] = None, + ) -> int: + """Calls the given function asynchronously with each `Runner` as the argument. + + Does not return results directly. Instead, `fetch_ready_async_reqs()` can be + used to pull results in an async manner whenever they are available. + + Args: + func: The function to call for each `Runner`s. The only call argument is + the respective `Runner` instance. + healthy_only: Apply `func` on known-to-be healthy `Runner`s only. + remote_worker_ids: Apply `func` on a selected set of remote `Runner`s. + + Returns: + The number of async requests that have actually been made. This is the + length of `remote_worker_ids` (or self.num_remote_workers()` if + `remote_worker_ids` is None) minus the number of requests that were NOT + made b/c a remote `Runner` already had its + `max_remote_requests_in_flight_per_actor` counter reached. + """ + return self._worker_manager.foreach_actor_async( + func, + healthy_only=healthy_only, + remote_actor_ids=remote_worker_ids, + ) + + def fetch_ready_async_reqs( + self, + *, + timeout_seconds: Optional[float] = 0.0, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> List[Tuple[int, T]]: + """Get esults from outstanding asynchronous requests that are ready. + + Args: + timeout_seconds: Time to wait for results. Default is 0, meaning + those requests that are already ready. + return_obj_refs: Whether to return ObjectRef instead of actual results. + mark_healthy: Whether to mark all those workers healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that workers are NOT set unhealthy, if they simply time out + (only if they return a RayActorError). + Also note that this setting is ignored if `healthy_only=True` (b/c + `mark_healthy` only affects workers that are currently tagged as + unhealthy). + + Returns: + A list of results successfully returned from outstanding remote calls, + paired with the indices of the callee workers. + """ + remote_results = self._worker_manager.fetch_ready_async_reqs( + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + FaultTolerantActorManager.handle_remote_call_result_errors( + remote_results, + ignore_ray_errors=self._ignore_ray_errors_on_runners, + ) + + return [(r.actor_id, r.get()) for r in remote_results.ignore_errors()] + + def probe_unhealthy_runners(self) -> List[int]: + """Checks for unhealthy workers and tries restoring their states. + + Returns: + List of IDs of the workers that were restored. + """ + return self._worker_manager.probe_unhealthy_actors( + timeout_seconds=self.runner_health_probe_timeout_s, + mark_healthy=True, + ) + + @property + @abc.abstractmethod + def runner_health_probe_timeout_s(self): + """Number of seconds to wait for health probe calls to `Runner`s.""" + + @property + @abc.abstractmethod + def runner_cls(self) -> Callable: + """Class for each runner.""" + + @property + def _local_config(self) -> "AlgorithmConfig": + """Returns the config for a local `Runner`.""" + return self.__local_config + + @property + def local_runner(self) -> Runner: + """Returns the local `Runner`.""" + return self._local_runner + + @property + def healthy_runner_ids(self) -> List[int]: + """Returns the list of remote `Runner` IDs.""" + return self._worker_manager.healthy_actor_ids() + + @property + @abc.abstractmethod + def num_runners(self) -> int: + """Number of runners to schedule and manage.""" + + @property + def num_remote_runners(self) -> int: + """Number of remote `Runner`s.""" + return self._worker_manager.num_actors() + + @property + def num_healthy_remote_runners(self) -> int: + """Returns the number of healthy remote `Runner`s.""" + return self._worker_manager.num_healthy_actors() + + @property + def num_healthy_runners(self) -> int: + """Returns the number of healthy `Runner`s.""" + return int(bool(self._local_runner)) + self.num_healthy_remote_runners() + + @property + def num_in_flight_async_reqs(self) -> int: + """Returns the number of in-flight async requests.""" + return self._worker_manager.num_outstanding_async_reqs() + + @property + def num_remote_runner_restarts(self) -> int: + """Returns the number of times managed remote `Runner`s have been restarted.""" + return self._worker_manager.total_num_restarts() + + @property + @abc.abstractmethod + def _remote_args(self): + """Remote arguments for each runner.""" + + @property + @abc.abstractmethod + def _ignore_ray_errors_on_runners(self): + """If errors in runners should be ignored.""" + + @property + @abc.abstractmethod + def _max_requests_in_flight_per_runner(self): + """Maximum requests in flight per runner.""" + + @property + @abc.abstractmethod + def _validate_runners_after_construction(self): + """If runners should validated after constructed.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58503926968563c0dfcf6f1cf95ed04ca1a92cf1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__init__.py @@ -0,0 +1,15 @@ +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.schedules.constant_schedule import ConstantSchedule +from ray.rllib.utils.schedules.linear_schedule import LinearSchedule +from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule +from ray.rllib.utils.schedules.polynomial_schedule import PolynomialSchedule +from ray.rllib.utils.schedules.exponential_schedule import ExponentialSchedule + +__all__ = [ + "ConstantSchedule", + "ExponentialSchedule", + "LinearSchedule", + "Schedule", + "PiecewiseSchedule", + "PolynomialSchedule", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4acb0a4f8189c2f1aabfd1da6df0301e1a9cc86 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c4d6b4395ed656b5e47eb8d44138174959b42bb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4aecba525bc7c44c2805e0a5ff43cc974689bcb2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82f85b7d9055cb199a0a77d1baef8d241963447f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..946b385aabb5ec92cc1c02e091be0636a1eec04c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52775b56f508cac422e94a2258afb158a952dc25 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48ecef489002183a6c4f2ccebbaea3dc514e4a73 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28807f160a5980346ca4066422eda6353d4f7087 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/constant_schedule.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/constant_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad58e266f8d3e21144daae1c251cd2333b85907 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/constant_schedule.py @@ -0,0 +1,32 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class ConstantSchedule(Schedule): + """A Schedule where the value remains constant over time.""" + + def __init__(self, value: float, framework: Optional[str] = None): + """Initializes a ConstantSchedule instance. + + Args: + value: The constant value to return, independently of time. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + """ + super().__init__(framework=framework) + self._v = value + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + return self._v + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + return tf.constant(self._v) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/exponential_schedule.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/exponential_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..4aafac19470baa3081d06a5a3bc4cbd18d76e384 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/exponential_schedule.py @@ -0,0 +1,50 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +torch, _ = try_import_torch() + + +@OldAPIStack +class ExponentialSchedule(Schedule): + """Exponential decay schedule from `initial_p` to `final_p`. + + Reduces output over `schedule_timesteps`. After this many time steps + always returns `final_p`. + """ + + def __init__( + self, + schedule_timesteps: int, + framework: Optional[str] = None, + initial_p: float = 1.0, + decay_rate: float = 0.1, + ): + """Initializes a ExponentialSchedule instance. + + Args: + schedule_timesteps: Number of time steps for which to + linearly anneal initial_p to final_p. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + initial_p: Initial output value. + decay_rate: The percentage of the original value after + 100% of the time has been reached (see formula above). + >0.0: The smaller the decay-rate, the stronger the decay. + 1.0: No decay at all. + """ + super().__init__(framework=framework) + assert schedule_timesteps > 0 + self.schedule_timesteps = schedule_timesteps + self.initial_p = initial_p + self.decay_rate = decay_rate + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + """Returns the result of: initial_p * decay_rate ** (`t`/t_max).""" + if self.framework == "torch" and torch and isinstance(t, torch.Tensor): + t = t.float() + return self.initial_p * self.decay_rate ** (t / self.schedule_timesteps) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/linear_schedule.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/linear_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..d23647b9bbebf757f002444bb231a9b78d863a47 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/linear_schedule.py @@ -0,0 +1,18 @@ +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.schedules.polynomial_schedule import PolynomialSchedule + + +@OldAPIStack +class LinearSchedule(PolynomialSchedule): + """Linear interpolation between `initial_p` and `final_p`. + + Uses `PolynomialSchedule` with power=1.0. + + + The formula is: + value = `final_p` + (`initial_p` - `final_p`) * (1 - `t`/t_max) + """ + + def __init__(self, **kwargs): + """Initializes a LinearSchedule instance.""" + super().__init__(power=1.0, **kwargs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4b15478b3f21bfa8612bdd5e39f952d0801086 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py @@ -0,0 +1,105 @@ +from typing import Callable, List, Optional, Tuple + +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType +from ray.util.annotations import DeveloperAPI + +tf1, tf, tfv = try_import_tf() + + +def _linear_interpolation(left, right, alpha): + return left + alpha * (right - left) + + +@DeveloperAPI +class PiecewiseSchedule(Schedule): + """Implements a Piecewise Scheduler.""" + + def __init__( + self, + endpoints: List[Tuple[int, float]], + framework: Optional[str] = None, + interpolation: Callable[ + [TensorType, TensorType, TensorType], TensorType + ] = _linear_interpolation, + outside_value: Optional[float] = None, + ): + """Initializes a PiecewiseSchedule instance. + + Args: + endpoints: A list of tuples + `(t, value)` such that the output + is an interpolation (given by the `interpolation` callable) + between two values. + E.g. + t=400 and endpoints=[(0, 20.0),(500, 30.0)] + output=20.0 + 0.8 * (30.0 - 20.0) = 28.0 + NOTE: All the values for time must be sorted in an increasing + order. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + interpolation: A function that takes the left-value, + the right-value and an alpha interpolation parameter + (0.0=only left value, 1.0=only right value), which is the + fraction of distance from left endpoint to right endpoint. + outside_value: If t in call to `value` is + outside of all the intervals in `endpoints` this value is + returned. If None then an AssertionError is raised when outside + value is requested. + """ + super().__init__(framework=framework) + + idxes = [e[0] for e in endpoints] + assert idxes == sorted(idxes) + self.interpolation = interpolation + self.outside_value = outside_value + self.endpoints = [(int(e[0]), float(e[1])) for e in endpoints] + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + # Find t in our list of endpoints. + for (l_t, l), (r_t, r) in zip(self.endpoints[:-1], self.endpoints[1:]): + # When found, return an interpolation (default: linear). + if l_t <= t < r_t: + alpha = float(t - l_t) / (r_t - l_t) + return self.interpolation(l, r, alpha) + + # t does not belong to any of the pieces, return `self.outside_value`. + assert self.outside_value is not None + return self.outside_value + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + assert self.outside_value is not None, ( + "tf-version of PiecewiseSchedule requires `outside_value` to be " + "provided!" + ) + + endpoints = tf.cast(tf.stack([e[0] for e in self.endpoints] + [-1]), tf.int64) + + # Create all possible interpolation results. + results_list = [] + for (l_t, l), (r_t, r) in zip(self.endpoints[:-1], self.endpoints[1:]): + alpha = tf.cast(t - l_t, tf.float32) / tf.cast(r_t - l_t, tf.float32) + results_list.append(self.interpolation(l, r, alpha)) + # If t does not belong to any of the pieces, return `outside_value`. + results_list.append(self.outside_value) + results_list = tf.stack(results_list) + + # Return correct results tensor depending on where we find t. + def _cond(i, x): + x = tf.cast(x, tf.int64) + return tf.logical_not( + tf.logical_or( + tf.equal(endpoints[i + 1], -1), + tf.logical_and(endpoints[i] <= x, x < endpoints[i + 1]), + ) + ) + + def _body(i, x): + return (i + 1, t) + + idx_and_t = tf.while_loop(_cond, _body, [tf.constant(0, dtype=tf.int64), t]) + return results_list[idx_and_t[0]] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..17a2820d9af811d8c647f467501cd906f2bbdd9d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py @@ -0,0 +1,67 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class PolynomialSchedule(Schedule): + """Polynomial interpolation between `initial_p` and `final_p`. + + Over `schedule_timesteps`. After this many time steps, always returns + `final_p`. + """ + + def __init__( + self, + schedule_timesteps: int, + final_p: float, + framework: Optional[str], + initial_p: float = 1.0, + power: float = 2.0, + ): + """Initializes a PolynomialSchedule instance. + + Args: + schedule_timesteps: Number of time steps for which to + linearly anneal initial_p to final_p + final_p: Final output value. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + initial_p: Initial output value. + power: The exponent to use (default: quadratic). + """ + super().__init__(framework=framework) + assert schedule_timesteps > 0 + self.schedule_timesteps = schedule_timesteps + self.final_p = final_p + self.initial_p = initial_p + self.power = power + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + """Returns the result of: + final_p + (initial_p - final_p) * (1 - `t`/t_max) ** power + """ + if self.framework == "torch" and torch and isinstance(t, torch.Tensor): + t = t.float() + t = min(t, self.schedule_timesteps) + return ( + self.final_p + + (self.initial_p - self.final_p) + * (1.0 - (t / self.schedule_timesteps)) ** self.power + ) + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + t = tf.math.minimum(t, self.schedule_timesteps) + return ( + self.final_p + + (self.initial_p - self.final_p) + * (1.0 - (t / self.schedule_timesteps)) ** self.power + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/schedule.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5b113ff5a9c1d328cdc0db0ec8197d4efa8b0f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/schedule.py @@ -0,0 +1,73 @@ +from abc import ABCMeta, abstractmethod +from typing import Any, Union + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class Schedule(metaclass=ABCMeta): + """Schedule classes implement various time-dependent scheduling schemas. + + - Constant behavior. + - Linear decay. + - Piecewise decay. + - Exponential decay. + + Useful for backend-agnostic rate/weight changes for learning rates, + exploration epsilons, beta parameters for prioritized replay, loss weights + decay, etc.. + + Each schedule can be called directly with the `t` (absolute time step) + value and returns the value dependent on the Schedule and the passed time. + """ + + def __init__(self, framework): + self.framework = framework + + def value(self, t: Union[int, TensorType]) -> Any: + """Generates the value given a timestep (based on schedule's logic). + + Args: + t: The time step. This could be a tf.Tensor. + + Returns: + The calculated value depending on the schedule and `t`. + """ + if self.framework in ["tf2", "tf"]: + return self._tf_value_op(t) + return self._value(t) + + def __call__(self, t: Union[int, TensorType]) -> Any: + """Simply calls self.value(t). Implemented to make Schedules callable.""" + return self.value(t) + + @abstractmethod + def _value(self, t: Union[int, TensorType]) -> Any: + """ + Returns the value based on a time step input. + + Args: + t: The time step. This could be a tf.Tensor. + + Returns: + The calculated value depending on the schedule and `t`. + """ + raise NotImplementedError + + def _tf_value_op(self, t: TensorType) -> TensorType: + """ + Returns the tf-op that calculates the value based on a time step input. + + Args: + t: The time step op (int tf.Tensor). + + Returns: + The calculated value depending on the schedule and `t`. + """ + # By default (most of the time), tf should work with python code. + # Override only if necessary. + return self._value(t) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/scheduler.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..901b5c785acd42a6fd2e2f0a3c9061145e3f0d54 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/schedules/scheduler.py @@ -0,0 +1,175 @@ +from typing import Optional + +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule +from ray.rllib.utils.typing import LearningRateOrSchedule, TensorType +from ray.util.annotations import DeveloperAPI + + +_, tf, _ = try_import_tf() +torch, _ = try_import_torch() + + +@DeveloperAPI +class Scheduler: + """Class to manage a scheduled (framework-dependent) tensor variable. + + Uses the PiecewiseSchedule (for maximum configuration flexibility) + """ + + def __init__( + self, + fixed_value_or_schedule: LearningRateOrSchedule, + *, + framework: str = "torch", + device: Optional[str] = None, + ): + """Initializes a Scheduler instance. + + Args: + fixed_value_or_schedule: A fixed, constant value (in case no schedule should + be used) or a schedule configuration in the format of + [[timestep, value], [timestep, value], ...] + Intermediary timesteps will be assigned to linerarly interpolated + values. A schedule config's first entry must + start with timestep 0, i.e.: [[0, initial_value], [...]]. + framework: The framework string, for which to create the tensor variable + that hold the current value. This is the variable that can be used in + the graph, e.g. in a loss function. + device: Optional device (for torch) to place the tensor variable on. + """ + self.framework = framework + self.device = device + self.use_schedule = isinstance(fixed_value_or_schedule, (list, tuple)) + + if self.use_schedule: + # Custom schedule, based on list of + # ([ts], [value to be reached by ts])-tuples. + self._schedule = PiecewiseSchedule( + fixed_value_or_schedule, + outside_value=fixed_value_or_schedule[-1][-1], + framework=None, + ) + # As initial tensor valie, use the first timestep's (must be 0) value. + self._curr_value = self._create_tensor_variable( + initial_value=fixed_value_or_schedule[0][1] + ) + + # If no schedule, pin (fix) given value. + else: + self._curr_value = fixed_value_or_schedule + + @staticmethod + def validate( + *, + fixed_value_or_schedule: LearningRateOrSchedule, + setting_name: str, + description: str, + ) -> None: + """Performs checking of a certain schedule configuration. + + The first entry in `value_or_schedule` (if it's not a fixed value) must have a + timestep of 0. + + Args: + fixed_value_or_schedule: A fixed, constant value (in case no schedule should + be used) or a schedule configuration in the format of + [[timestep, value], [timestep, value], ...] + Intermediary timesteps will be assigned to linerarly interpolated + values. A schedule config's first entry must + start with timestep 0, i.e.: [[0, initial_value], [...]]. + setting_name: The property name of the schedule setting (within a config), + e.g. `lr` or `entropy_coeff`. + description: A full text description of the property that's being scheduled, + e.g. `learning rate`. + + Raises: + ValueError: In case, errors are found in the schedule's format. + """ + # Fixed (single) value. + if ( + isinstance(fixed_value_or_schedule, (int, float)) + or fixed_value_or_schedule is None + ): + return + + if not isinstance(fixed_value_or_schedule, (list, tuple)) or ( + len(fixed_value_or_schedule) < 2 + ): + raise ValueError( + f"Invalid `{setting_name}` ({fixed_value_or_schedule}) specified! " + f"Must be a list of 2 or more tuples, each of the form " + f"(`timestep`, `{description} to reach`), for example " + "`[(0, 0.001), (1e6, 0.0001), (2e6, 0.00005)]`." + ) + elif fixed_value_or_schedule[0][0] != 0: + raise ValueError( + f"When providing a `{setting_name}` schedule, the first timestep must " + f"be 0 and the corresponding lr value is the initial {description}! " + f"You provided ts={fixed_value_or_schedule[0][0]} {description}=" + f"{fixed_value_or_schedule[0][1]}." + ) + elif any(len(pair) != 2 for pair in fixed_value_or_schedule): + raise ValueError( + f"When providing a `{setting_name}` schedule, each tuple in the " + f"schedule list must have exctly 2 items of the form " + f"(`timestep`, `{description} to reach`), for example " + "`[(0, 0.001), (1e6, 0.0001), (2e6, 0.00005)]`." + ) + + def get_current_value(self) -> TensorType: + """Returns the current value (as a tensor variable). + + This method should be used in loss functions of other (in-graph) places + where the current value is needed. + + Returns: + The tensor variable (holding the current value to be used). + """ + return self._curr_value + + def update(self, timestep: int) -> float: + """Updates the underlying (framework specific) tensor variable. + + In case of a fixed value, this method does nothing and only returns the fixed + value as-is. + + Args: + timestep: The current timestep that the update might depend on. + + Returns: + The current value of the tensor variable as a python float. + """ + if self.use_schedule: + python_value = self._schedule.value(t=timestep) + if self.framework == "torch": + self._curr_value.data = torch.tensor(python_value) + else: + self._curr_value.assign(python_value) + else: + python_value = self._curr_value + + return python_value + + def _create_tensor_variable(self, initial_value: float) -> TensorType: + """Creates a framework-specific tensor variable to be scheduled. + + Args: + initial_value: The initial (float) value for the variable to hold. + + Returns: + The created framework-specific tensor variable. + """ + if self.framework == "torch": + return torch.tensor( + initial_value, + requires_grad=False, + dtype=torch.float32, + device=self.device, + ) + else: + return tf.Variable( + initial_value, + trainable=False, + dtype=tf.float32, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa2f6b8da30befc8629acc5ebc751061a8538b95 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/flexdict.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/flexdict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d679d846c3642b050927ba8b99f8a923dee37a9e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/flexdict.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/repeated.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/repeated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6198e459e44ddb0a8ae427946f382c3da09a8891 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/repeated.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/simplex.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/simplex.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca713eedebbf03dbf967dac72ecd1be4502ddd41 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/simplex.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/space_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/space_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51dc7e40aad0ae04ec8a054053805e9ffa768b87 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/__pycache__/space_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/flexdict.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/flexdict.py new file mode 100644 index 0000000000000000000000000000000000000000..905a05e2857b72856cee0bd142dd3af204029c07 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/flexdict.py @@ -0,0 +1,47 @@ +import gymnasium as gym + +from ray.rllib.utils.annotations import PublicAPI + + +@PublicAPI +class FlexDict(gym.spaces.Dict): + """Gym Dictionary with arbitrary keys updatable after instantiation + + Example: + space = FlexDict({}) + space['key'] = spaces.Box(4,) + See also: documentation for gym.spaces.Dict + """ + + def __init__(self, spaces=None, **spaces_kwargs): + err = "Use either Dict(spaces=dict(...)) or Dict(foo=x, bar=z)" + assert (spaces is None) or (not spaces_kwargs), err + + if spaces is None: + spaces = spaces_kwargs + + for space in spaces.values(): + self.assertSpace(space) + + super().__init__(spaces=spaces) + + def assertSpace(self, space): + err = "Values of the dict should be instances of gym.Space" + assert issubclass(type(space), gym.spaces.Space), err + + def sample(self): + return {k: space.sample() for k, space in self.spaces.items()} + + def __getitem__(self, key): + return self.spaces[key] + + def __setitem__(self, key, space): + self.assertSpace(space) + self.spaces[key] = space + + def __repr__(self): + return ( + "FlexDict(" + + ", ".join([str(k) + ":" + str(s) for k, s in self.spaces.items()]) + + ")" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/repeated.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/repeated.py new file mode 100644 index 0000000000000000000000000000000000000000..77beaff288e749b01780c9e9bf6b25e3f123b2d8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/repeated.py @@ -0,0 +1,38 @@ +import gymnasium as gym +import numpy as np + +from ray.rllib.utils.annotations import PublicAPI + + +@PublicAPI +class Repeated(gym.Space): + """Represents a variable-length list of child spaces. + + Example: + self.observation_space = spaces.Repeated(spaces.Box(4,), max_len=10) + --> from 0 to 10 boxes of shape (4,) + + See also: documentation for rllib.models.RepeatedValues, which shows how + the lists are represented as batched input for ModelV2 classes. + """ + + def __init__(self, child_space: gym.Space, max_len: int): + super().__init__() + self.child_space = child_space + self.max_len = max_len + + def sample(self): + return [ + self.child_space.sample() + for _ in range(self.np_random.integers(1, self.max_len + 1)) + ] + + def contains(self, x): + return ( + isinstance(x, (list, np.ndarray)) + and len(x) <= self.max_len + and all(self.child_space.contains(c) for c in x) + ) + + def __repr__(self): + return "Repeated({}, {})".format(self.child_space, self.max_len) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/simplex.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/simplex.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3b4c843ad0e4d0303f106b5621f88428f8b931 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/simplex.py @@ -0,0 +1,61 @@ +import gymnasium as gym +import numpy as np + +from ray.rllib.utils.annotations import PublicAPI + + +@PublicAPI +class Simplex(gym.Space): + """Represents a d - 1 dimensional Simplex in R^d. + + That is, all coordinates are in [0, 1] and sum to 1. + The dimension d of the simplex is assumed to be shape[-1]. + + Additionally one can specify the underlying distribution of + the simplex as a Dirichlet distribution by providing concentration + parameters. By default, sampling is uniform, i.e. concentration is + all 1s. + + Example usage: + self.action_space = spaces.Simplex(shape=(3, 4)) + --> 3 independent 4d Dirichlet with uniform concentration + """ + + def __init__(self, shape, concentration=None, dtype=np.float32): + assert type(shape) in [tuple, list] + + super().__init__(shape, dtype) + self.dim = self.shape[-1] + + if concentration is not None: + assert ( + concentration.shape[0] == shape[-1] + ), f"{concentration.shape[0]} vs {shape[-1]}" + self.concentration = concentration + else: + self.concentration = np.array([1] * self.dim) + + def sample(self): + return np.random.dirichlet(self.concentration, size=self.shape[:-1]).astype( + self.dtype + ) + + def contains(self, x): + return x.shape == self.shape and np.allclose( + np.sum(x, axis=-1), np.ones_like(x[..., 0]) + ) + + def to_jsonable(self, sample_n): + return np.array(sample_n).tolist() + + def from_jsonable(self, sample_n): + return [np.asarray(sample) for sample in sample_n] + + def __repr__(self): + return "Simplex({}; {})".format(self.shape, self.concentration) + + def __eq__(self, other): + return ( + np.allclose(self.concentration, other.concentration) + and self.shape == other.shape + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/space_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/space_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..921c174d5d82d66f2007a09e917f055c4cc4344b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/spaces/space_utils.py @@ -0,0 +1,562 @@ +import gymnasium as gym +from gymnasium.spaces import Tuple, Dict +from gymnasium.core import ActType, ObsType +import numpy as np +from ray.rllib.utils.annotations import DeveloperAPI +import tree # pip install dm_tree +from typing import Any, List, Optional, Union + + +@DeveloperAPI +class BatchedNdArray(np.ndarray): + """A ndarray-wrapper the usage of which indicates that there a batch dim exists. + + This is such that our `batch()` utility can distinguish between having to + stack n individual batch items (each one w/o any batch dim) vs having to + concatenate n already batched items (each one possibly with a different batch + dim, but definitely with some batch dim). + + TODO (sven): Maybe replace this by a list-override instead. + """ + + def __new__(cls, input_array): + # Use __new__ to create a new instance of our subclass. + obj = np.asarray(input_array).view(cls) + return obj + + +@DeveloperAPI +def get_original_space(space: gym.Space) -> gym.Space: + """Returns the original space of a space, if any. + + This function recursively traverses the given space and returns the original space + at the very end of the chain. + + Args: + space: The space to get the original space for. + + Returns: + The original space or the given space itself if no original space is found. + """ + if hasattr(space, "original_space"): + return get_original_space(space.original_space) + else: + return space + + +@DeveloperAPI +def is_composite_space(space: gym.Space) -> bool: + """Returns true, if the space is composite. + + Note, we follow here the glossary of `gymnasium` by which any spoace + that holds other spaces is defined as being 'composite'. + + Args: + space: The space to be checked for being composed of other spaces. + + Returns: + True, if the space is composed of other spaces, otherwise False. + """ + if type(space) in [ + gym.spaces.Dict, + gym.spaces.Graph, + gym.spaces.Sequence, + gym.spaces.Tuple, + ]: + return True + else: + return False + + +@DeveloperAPI +def to_jsonable_if_needed( + sample: Union[ActType, ObsType], space: gym.Space +) -> Union[ActType, ObsType, List]: + """Returns a jsonabled space sample, if the space is composite. + + Checks, if the space is composite and converts the sample to a jsonable + struct in this case. Otherwise return the sample as is. + + Args: + sample: Any action or observation type possible in `gymnasium`. + space: Any space defined in `gymnasium.spaces`. + + Returns: + The `sample` as-is, if the `space` is composite, otherwise converts the + composite sample to a JSONable data type. + """ + + if is_composite_space(space): + return space.to_jsonable([sample]) + else: + return sample + + +@DeveloperAPI +def from_jsonable_if_needed( + sample: Union[ActType, ObsType], space: gym.Space +) -> Union[ActType, ObsType, List]: + """Returns a jsonabled space sample, if the space is composite. + + Checks, if the space is composite and converts the sample to a JSONable + struct in this case. Otherwise return the sample as is. + + Args: + sample: Any action or observation type possible in `gymnasium`, or a + JSONable data type. + space: Any space defined in `gymnasium.spaces`. + + Returns: + The `sample` as-is, if the `space` is not composite, otherwise converts the + composite sample jsonable to an actual `space` sample.. + """ + + if is_composite_space(space): + return space.from_jsonable(sample)[0] + else: + return sample + + +@DeveloperAPI +def flatten_space(space: gym.Space) -> List[gym.Space]: + """Flattens a gym.Space into its primitive components. + + Primitive components are any non Tuple/Dict spaces. + + Args: + space: The gym.Space to flatten. This may be any + supported type (including nested Tuples and Dicts). + + Returns: + List[gym.Space]: The flattened list of primitive Spaces. This list + does not contain Tuples or Dicts anymore. + """ + + def _helper_flatten(space_, return_list): + from ray.rllib.utils.spaces.flexdict import FlexDict + + if isinstance(space_, Tuple): + for s in space_: + _helper_flatten(s, return_list) + elif isinstance(space_, (Dict, FlexDict)): + for k in sorted(space_.spaces): + _helper_flatten(space_[k], return_list) + else: + return_list.append(space_) + + ret = [] + _helper_flatten(space, ret) + return ret + + +@DeveloperAPI +def get_base_struct_from_space(space): + """Returns a Tuple/Dict Space as native (equally structured) py tuple/dict. + + Args: + space: The Space to get the python struct for. + + Returns: + Union[dict,tuple,gym.Space]: The struct equivalent to the given Space. + Note that the returned struct still contains all original + "primitive" Spaces (e.g. Box, Discrete). + + .. testcode:: + :skipif: True + + get_base_struct_from_space(Dict({ + "a": Box(), + "b": Tuple([Discrete(2), Discrete(3)]) + })) + + .. testoutput:: + + dict(a=Box(), b=tuple(Discrete(2), Discrete(3))) + """ + + def _helper_struct(space_): + if isinstance(space_, Tuple): + return tuple(_helper_struct(s) for s in space_) + elif isinstance(space_, Dict): + return {k: _helper_struct(space_[k]) for k in space_.spaces} + else: + return space_ + + return _helper_struct(space) + + +@DeveloperAPI +def get_dummy_batch_for_space( + space: gym.Space, + batch_size: int = 32, + *, + fill_value: Union[float, int, str] = 0.0, + time_size: Optional[int] = None, + time_major: bool = False, + one_hot_discrete: bool = False, +) -> np.ndarray: + """Returns batched dummy data (using `batch_size`) for the given `space`. + + Note: The returned batch will not pass a `space.contains(batch)` test + as an additional batch dimension has to be added at axis 0, unless `batch_size` is + set to 0. + + Args: + space: The space to get a dummy batch for. + batch_size: The required batch size (B). Note that this can also + be 0 (only if `time_size` is None!), which will result in a + non-batched sample for the given space (no batch dim). + fill_value: The value to fill the batch with + or "random" for random values. + time_size: If not None, add an optional time axis + of `time_size` size to the returned batch. This time axis might either + be inserted at axis=1 (default) or axis=0, if `time_major` is True. + time_major: If True AND `time_size` is not None, return batch + as shape [T x B x ...], otherwise as [B x T x ...]. If `time_size` + if None, ignore this setting and return [B x ...]. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) `space` + that are Discrete or MultiDiscrete. Note that in case `fill_value` is 0.0, + this will result in zero-hot vectors (where all slots have a value of 0.0). + + Returns: + The dummy batch of size `bqtch_size` matching the given space. + """ + # Complex spaces. Perform recursive calls of this function. + if isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple, dict, tuple)): + base_struct = space + if isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple)): + base_struct = get_base_struct_from_space(space) + return tree.map_structure( + lambda s: get_dummy_batch_for_space( + space=s, + batch_size=batch_size, + fill_value=fill_value, + time_size=time_size, + time_major=time_major, + one_hot_discrete=one_hot_discrete, + ), + base_struct, + ) + + if one_hot_discrete: + if isinstance(space, gym.spaces.Discrete): + space = gym.spaces.Box(0.0, 1.0, (space.n,), np.float32) + elif isinstance(space, gym.spaces.MultiDiscrete): + space = gym.spaces.Box(0.0, 1.0, (np.sum(space.nvec),), np.float32) + + # Primivite spaces: Box, Discrete, MultiDiscrete. + # Random values: Use gym's sample() method. + if fill_value == "random": + if time_size is not None: + assert batch_size > 0 and time_size > 0 + if time_major: + return np.array( + [ + [space.sample() for _ in range(batch_size)] + for t in range(time_size) + ], + dtype=space.dtype, + ) + else: + return np.array( + [ + [space.sample() for t in range(time_size)] + for _ in range(batch_size) + ], + dtype=space.dtype, + ) + else: + return np.array( + [space.sample() for _ in range(batch_size)] + if batch_size > 0 + else space.sample(), + dtype=space.dtype, + ) + # Fill value given: Use np.full. + else: + if time_size is not None: + assert batch_size > 0 and time_size > 0 + if time_major: + shape = [time_size, batch_size] + else: + shape = [batch_size, time_size] + else: + shape = [batch_size] if batch_size > 0 else [] + return np.full( + shape + list(space.shape), fill_value=fill_value, dtype=space.dtype + ) + + +@DeveloperAPI +def flatten_to_single_ndarray(input_): + """Returns a single np.ndarray given a list/tuple of np.ndarrays. + + Args: + input_ (Union[List[np.ndarray], np.ndarray]): The list of ndarrays or + a single ndarray. + + Returns: + np.ndarray: The result after concatenating all single arrays in input_. + + .. testcode:: + :skipif: True + + flatten_to_single_ndarray([ + np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]), + np.array([7, 8, 9]), + ]) + + .. testoutput:: + + np.array([ + 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 + ]) + """ + # Concatenate complex inputs. + if isinstance(input_, (list, tuple, dict)): + expanded = [] + for in_ in tree.flatten(input_): + expanded.append(np.reshape(in_, [-1])) + input_ = np.concatenate(expanded, axis=0).flatten() + return input_ + + +@DeveloperAPI +def batch( + list_of_structs: List[Any], + *, + individual_items_already_have_batch_dim: Union[bool, str] = False, +): + """Converts input from a list of (nested) structs to a (nested) struct of batches. + + Input: List of structs (each of these structs representing a single batch item). + [ + {"a": 1, "b": (4, 7.0)}, <- batch item 1 + {"a": 2, "b": (5, 8.0)}, <- batch item 2 + {"a": 3, "b": (6, 9.0)}, <- batch item 3 + ] + + Output: Struct of different batches (each batch has size=3 b/c there were 3 items + in the original list): + { + "a": np.array([1, 2, 3]), + "b": (np.array([4, 5, 6]), np.array([7.0, 8.0, 9.0])) + } + + Args: + list_of_structs: The list of (possibly nested) structs. Each item + in this list represents a single batch item. + individual_items_already_have_batch_dim: True, if the individual items in + `list_of_structs` already have a batch dim. In this case, we will + concatenate (instead of stack) at the end. In the example above, this would + look like this: Input: [{"a": [1], "b": ([4], [7.0])}, ...] -> Output: same + as in above example. + If the special value "auto" is used, + + Returns: + The struct of component batches. Each leaf item in this struct represents the + batch for a single component (in case struct is tuple/dict). If the input is a + simple list of primitive items, e.g. a list of floats, a np.array of floats + will be returned. + """ + if not list_of_structs: + raise ValueError("Input `list_of_structs` does not contain any items.") + + # TODO (sven): Maybe replace this by a list-override (usage of which indicated + # this method that concatenate should be used (not stack)). + if individual_items_already_have_batch_dim == "auto": + flat = tree.flatten(list_of_structs[0]) + individual_items_already_have_batch_dim = isinstance(flat[0], BatchedNdArray) + + np_func = np.concatenate if individual_items_already_have_batch_dim else np.stack + ret = tree.map_structure( + lambda *s: np.ascontiguousarray(np_func(s, axis=0)), *list_of_structs + ) + return ret + + +@DeveloperAPI +def unbatch(batches_struct): + """Converts input from (nested) struct of batches to batch of structs. + + Input: Struct of different batches (each batch has size=3): + { + "a": np.array([1, 2, 3]), + "b": (np.array([4, 5, 6]), np.array([7.0, 8.0, 9.0])) + } + Output: Batch (list) of structs (each of these structs representing a + single action): + [ + {"a": 1, "b": (4, 7.0)}, <- action 1 + {"a": 2, "b": (5, 8.0)}, <- action 2 + {"a": 3, "b": (6, 9.0)}, <- action 3 + ] + + Args: + batches_struct: The struct of component batches. Each leaf item + in this struct represents the batch for a single component + (in case struct is tuple/dict). + Alternatively, `batches_struct` may also simply be a batch of + primitives (non tuple/dict). + + Returns: + The list of individual structs. Each item in the returned list represents a + single (maybe complex) batch item. + """ + flat_batches = tree.flatten(batches_struct) + + out = [] + for batch_pos in range(len(flat_batches[0])): + out.append( + tree.unflatten_as( + batches_struct, + [flat_batches[i][batch_pos] for i in range(len(flat_batches))], + ) + ) + return out + + +@DeveloperAPI +def clip_action(action, action_space): + """Clips all components in `action` according to the given Space. + + Only applies to Box components within the action space. + + Args: + action: The action to be clipped. This could be any complex + action, e.g. a dict or tuple. + action_space: The action space struct, + e.g. `{"a": Distrete(2)}` for a space: Dict({"a": Discrete(2)}). + + Returns: + Any: The input action, but clipped by value according to the space's + bounds. + """ + + def map_(a, s): + if isinstance(s, gym.spaces.Box): + a = np.clip(a, s.low, s.high) + return a + + return tree.map_structure(map_, action, action_space) + + +@DeveloperAPI +def unsquash_action(action, action_space_struct): + """Unsquashes all components in `action` according to the given Space. + + Inverse of `normalize_action()`. Useful for mapping policy action + outputs (normalized between -1.0 and 1.0) to an env's action space. + Unsquashing results in cont. action component values between the + given Space's bounds (`low` and `high`). This only applies to Box + components within the action space, whose dtype is float32 or float64. + + Args: + action: The action to be unsquashed. This could be any complex + action, e.g. a dict or tuple. + action_space_struct: The action space struct, + e.g. `{"a": Box()}` for a space: Dict({"a": Box()}). + + Returns: + Any: The input action, but unsquashed, according to the space's + bounds. An unsquashed action is ready to be sent to the + environment (`BaseEnv.send_actions([unsquashed actions])`). + """ + + def map_(a, s): + if ( + isinstance(s, gym.spaces.Box) + and np.all(s.bounded_below) + and np.all(s.bounded_above) + ): + if s.dtype == np.float32 or s.dtype == np.float64: + # Assuming values are roughly between -1.0 and 1.0 -> + # unsquash them to the given bounds. + a = s.low + (a + 1.0) * (s.high - s.low) / 2.0 + # Clip to given bounds, just in case the squashed values were + # outside [-1.0, 1.0]. + a = np.clip(a, s.low, s.high) + elif np.issubdtype(s.dtype, np.integer): + # For Categorical and MultiCategorical actions, shift the selection + # into the proper range. + a = s.low + a + return a + + return tree.map_structure(map_, action, action_space_struct) + + +@DeveloperAPI +def normalize_action(action, action_space_struct): + """Normalizes all (Box) components in `action` to be in [-1.0, 1.0]. + + Inverse of `unsquash_action()`. Useful for mapping an env's action + (arbitrary bounded values) to a [-1.0, 1.0] interval. + This only applies to Box components within the action space, whose + dtype is float32 or float64. + + Args: + action: The action to be normalized. This could be any complex + action, e.g. a dict or tuple. + action_space_struct: The action space struct, + e.g. `{"a": Box()}` for a space: Dict({"a": Box()}). + + Returns: + Any: The input action, but normalized, according to the space's + bounds. + """ + + def map_(a, s): + if isinstance(s, gym.spaces.Box) and ( + s.dtype == np.float32 or s.dtype == np.float64 + ): + # Normalize values to be exactly between -1.0 and 1.0. + a = ((a - s.low) * 2.0) / (s.high - s.low) - 1.0 + return a + + return tree.map_structure(map_, action, action_space_struct) + + +@DeveloperAPI +def convert_element_to_space_type(element: Any, sampled_element: Any) -> Any: + """Convert all the components of the element to match the space dtypes. + + Args: + element: The element to be converted. + sampled_element: An element sampled from a space to be matched + to. + + Returns: + The input element, but with all its components converted to match + the space dtypes. + """ + + def map_(elem, s): + if isinstance(s, np.ndarray): + if not isinstance(elem, np.ndarray): + assert isinstance( + elem, (float, int) + ), f"ERROR: `elem` ({elem}) must be np.array, float or int!" + if s.shape == (): + elem = np.array(elem, dtype=s.dtype) + else: + raise ValueError( + "Element should be of type np.ndarray but is instead of \ + type {}".format( + type(elem) + ) + ) + elif s.dtype != elem.dtype: + elem = elem.astype(s.dtype) + + # Gymnasium now uses np.int_64 as the dtype of a Discrete action space + elif isinstance(s, int) or isinstance(s, np.int_): + if isinstance(elem, float) and elem.is_integer(): + elem = int(elem) + # Note: This does not check if the float element is actually an integer + if isinstance(elem, np.float_): + elem = np.int64(elem) + + return elem + + return tree.map_structure(map_, element, sampled_element, check_types=False) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/runtime_env/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/runtime_env/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2538aa108f3a702e5e702ef655235be96b776add Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/runtime_env/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/runtime_env/__pycache__/runtime_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/runtime_env/__pycache__/runtime_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8af8b8808480a31e5e1a397b34b6ef7a1423bb43 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/runtime_env/__pycache__/runtime_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/scripts/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/scripts/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f33c616fb7ae69e5bad19ccd016a048a8f02309b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/scripts/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/scripts/__pycache__/scripts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/scripts/__pycache__/scripts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90b502bc488bce1006e13c251570e2e8210eafd0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/scripts/__pycache__/scripts.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8ce350b9a47ca6508ec13d88bde9dc0dec1386f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..859dd3f07cb986e6930d40abe24a22bcc2b1a97b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/autoscaling_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/autoscaling_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41b3bb779395bf09f8a47eb4c20273e9d56e2e1c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/autoscaling_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/batching.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/batching.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c77f5c3c3bcd61c7101d0e6df1fba689166529b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/batching.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00596774e270597c4f718f5c3471edee16df7824 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bad51b8a5dc30c467be3298643338bd823127675 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/context.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/dag.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/dag.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acfd11f8b95e2c8d791aa6f71414ed4d402ebca3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/dag.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/deployment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/deployment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8d1ae98ef684ae56b8518afff0b6b325035d641 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/deployment.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/exceptions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d8838307abff99b7399b01a42437d7ed1778a99 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/exceptions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/gradio_integrations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/gradio_integrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a21b37cc7679ed720fe04b73650d0a4747ef9dea Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/gradio_integrations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/grpc_util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/grpc_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30d48d850fb332f28755811776af35e8d36c0a31 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/grpc_util.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/handle.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/handle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a90f9a99e120d24fab3da54071836f8ec8cf5a1d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/handle.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/metrics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16f899d19ac6e11d31a9bf727e393f24980e626d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/metrics.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/multiplex.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/multiplex.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2990a442f9f6ce6d97fa7f5d4593a1a7ea852b32 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/multiplex.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/request_router.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/request_router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ce77ee7e8312528ca9be4eb4f8f5cdd9823de57 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/request_router.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/schema.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..547c4ef47efcd1881ca4dcf8358b18e7b9046fa3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/schema.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/scripts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/scripts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e53176d9f7bdbfa5cd291d5257b3238170c7732 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/scripts.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/task_consumer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/task_consumer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e40bd31d9779726f77349b8b5d5239a09e2c80bb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/task_consumer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/task_processor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/task_processor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c61b22e887979f184ab3c67a33acaa2629517aed Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/__pycache__/task_processor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d21616bf6537a3cf4a075719a34023210c1ee5a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..288f39f2681e925390d39ebabb71962033dcb0f7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/application_state.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/application_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f636c65e5f3f51151e98f45a8b1074d925c70569 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/application_state.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/autoscaling_state.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/autoscaling_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afaa4290d42bd2dd4175494bb0f542ab9f6542e4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/autoscaling_state.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/build_app.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/build_app.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69d82378b8eab0ce83d1c30fb49b34c5e3305d1c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/build_app.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/client.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ad9716237218fc525ac119b3babd73af8f3d09b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/client.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/cluster_node_info_cache.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/cluster_node_info_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d109729ed9c773812707d94c50a1fae0e20bf075 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/cluster_node_info_cache.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38bfe602abe2d696d9205dbb829f8c5760c714eb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57c452743c75218b73f6d1645a38296f06a2725a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/constants.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f092cd2f98897c61f838b0f0762a747f1e881e2e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/constants.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/constants_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/constants_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e9949b33326d713540fd40766785019c0f095b9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/constants_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/controller.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/controller.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..627f77f1e1f5ab8ab850689313801adcaec82377 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/controller.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/controller_avatar.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/controller_avatar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbb979684f5fdfb6f830829b6735b719dd56fbf6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/controller_avatar.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/default_impl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/default_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cd19b99cd206ddacad068b0969d0d4cf4d5660d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/default_impl.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deploy_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deploy_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eb3bb4ece85fef8724187c866027f3dad0c2a82 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deploy_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_info.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..811c40c80587ff74ac580fe7b810e680b30d5041 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_info.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_node.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_node.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5ced30d21e36c3d3fc9655b22e56c918ee510db Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_node.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_scheduler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_scheduler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0fbb50ace52eb654ee1c13aaa917ad5f2a69151 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_scheduler.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88ca467e4ba51935ac239a4fd956d7be847bb24e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31f770e32074857a11ffbd462131bb2e6348cfaccce05bb25c72110467d56234 +size 130387 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/endpoint_state.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/endpoint_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ee1b6e03c3252475bd3dea5372e3cb020e3e1f2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/endpoint_state.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/grpc_util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/grpc_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8d3aa6cbf8c04312c80042f9e8db933b718caa2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/grpc_util.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/handle_options.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/handle_options.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20db71c8819911ce50a51b4c9c80037326d0f94b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/handle_options.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/http_util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/http_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b36d9e446a8d489d217ded9b5d25f0a43af0ef33 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/http_util.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/local_testing_mode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/local_testing_mode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfcbd55203d65ba21a5980b4d6e0ce24b4b55fb1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/local_testing_mode.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/logging_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/logging_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00b1c0a6124f3f5c19f2fcd461cbc8981c922954 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/logging_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/long_poll.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/long_poll.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a83f4672be8fe41e06ea195657060ebf16e5ff46 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/long_poll.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/metrics_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/metrics_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..876d0f0b8eb9d0d7069eebf17fb7bda59d464b23 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/metrics_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d7dcff250a13670536e2ad7f0f6e2bb0f42df97 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_request_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_request_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46e679e333f34b256bc62d90f0252cd07176ea3a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_request_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_response_generator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_response_generator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0af97468779dd6471280dcb53a3729e08422905 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_response_generator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_router.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49a460a8e0c8d075a75b77734f735517f4852e41 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_router.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_state.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0c31b77903fe18efa585369222d9300a3a6bdee Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/proxy_state.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/replica.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/replica.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd68074c3092d3197a343e91be9ba73f71c5ca03 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/replica.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/replica_result.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/replica_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..643db06ed2c79d9f87d1cb86d6f2ec2dd39a3a5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/replica_result.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/router.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b877ca8b543fa468fe489fba1a945414e8c5422 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/router.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/test_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/test_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4821a3bc16e0aea14d1ab693978bbcbcdda1ff60 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/test_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/usage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4431ead76b28cc2cffc76a921f13104bd26bdcec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/usage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..749649501136749c7fa9a95295eb81437658b021 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/version.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e5dcda3b707e60f48d143154cd051d805bddaa5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/version.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/api.py new file mode 100644 index 0000000000000000000000000000000000000000..60b097d4c001e7716d319ae6c5dfe00cd4598eb0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/api.py @@ -0,0 +1,281 @@ +import inspect +import logging +from types import FunctionType +from typing import Any, Dict, Union + +import ray +from ray._common.pydantic_compat import is_subclass_of_base_model +from ray._common.usage import usage_lib +from ray.actor import ActorHandle +from ray.serve._private.client import ServeControllerClient +from ray.serve._private.constants import ( + HTTP_PROXY_TIMEOUT, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.default_impl import get_controller_impl +from ray.serve.config import HTTPOptions, gRPCOptions +from ray.serve.context import _get_global_client, _set_global_client +from ray.serve.deployment import Application +from ray.serve.exceptions import RayServeException +from ray.serve.schema import LoggingConfig + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def _check_http_options( + client: ServeControllerClient, http_options: Union[dict, HTTPOptions] +) -> None: + if http_options: + client_http_options = client.http_config + new_http_options = ( + http_options + if isinstance(http_options, HTTPOptions) + else HTTPOptions.parse_obj(http_options) + ) + different_fields = [] + all_http_option_fields = new_http_options.__dict__ + for field in all_http_option_fields: + if getattr(new_http_options, field) != getattr(client_http_options, field): + different_fields.append(field) + + if len(different_fields): + logger.warning( + "The new client HTTP config differs from the existing one " + f"in the following fields: {different_fields}. " + "The new HTTP config is ignored." + ) + + +def _start_controller( + http_options: Union[None, dict, HTTPOptions] = None, + grpc_options: Union[None, dict, gRPCOptions] = None, + global_logging_config: Union[None, dict, LoggingConfig] = None, + **kwargs, +) -> ActorHandle: + """Start Ray Serve controller. + + The function makes sure controller is ready to start deploying apps + after it returns. + + Parameters are same as ray.serve._private.api.serve_start(). + + Returns: controller actor handle. + """ + + # Initialize ray if needed. + ray._private.worker.global_worker._filter_logs_by_job = False + if not ray.is_initialized(): + ray.init(namespace=SERVE_NAMESPACE) + + # Legacy http proxy actor check + http_deprecated_args = ["http_host", "http_port", "http_middlewares"] + for key in http_deprecated_args: + if key in kwargs: + raise ValueError( + f"{key} is deprecated, please use serve.start(http_options=" + f'{{"{key}": {kwargs[key]}}}) instead.' + ) + + if isinstance(http_options, dict): + http_options = HTTPOptions.parse_obj(http_options) + if http_options is None: + http_options = HTTPOptions() + + if isinstance(grpc_options, dict): + grpc_options = gRPCOptions(**grpc_options) + + if global_logging_config is None: + global_logging_config = LoggingConfig() + elif isinstance(global_logging_config, dict): + global_logging_config = LoggingConfig(**global_logging_config) + + controller_impl = get_controller_impl() + controller = controller_impl.remote( + http_options=http_options, + grpc_options=grpc_options, + global_logging_config=global_logging_config, + ) + + proxy_handles = ray.get(controller.get_proxies.remote()) + if len(proxy_handles) > 0: + try: + ray.get( + [handle.ready.remote() for handle in proxy_handles.values()], + timeout=HTTP_PROXY_TIMEOUT, + ) + except ray.exceptions.GetTimeoutError: + raise TimeoutError( + f"HTTP proxies not available after {HTTP_PROXY_TIMEOUT}s." + ) + return controller + + +async def serve_start_async( + http_options: Union[None, dict, HTTPOptions] = None, + grpc_options: Union[None, dict, gRPCOptions] = None, + global_logging_config: Union[None, dict, LoggingConfig] = None, + **kwargs, +) -> ServeControllerClient: + """Initialize a serve instance asynchronously. + + This function is not thread-safe. The caller should maintain the async lock in order + to start the serve instance asynchronously. + + This function has the same functionality as ray.serve._private.api.serve_start(). + + Parameters & Returns are same as ray.serve._private.api.serve_start(). + """ + + usage_lib.record_library_usage("serve") + + try: + client = _get_global_client(_health_check_controller=True) + logger.info( + f'Connecting to existing Serve app in namespace "{SERVE_NAMESPACE}".' + " New http options will not be applied." + ) + if http_options: + _check_http_options(client, http_options) + return client + except RayServeException: + pass + + controller = ( + await ray.remote(_start_controller) + .options(num_cpus=0) + .remote(http_options, grpc_options, global_logging_config, **kwargs) + ) + + client = ServeControllerClient( + controller, + ) + _set_global_client(client) + logger.info(f'Started Serve in namespace "{SERVE_NAMESPACE}".') + return client + + +def serve_start( + http_options: Union[None, dict, HTTPOptions] = None, + grpc_options: Union[None, dict, gRPCOptions] = None, + global_logging_config: Union[None, dict, LoggingConfig] = None, + **kwargs, +) -> ServeControllerClient: + """Initialize a serve instance. + + By default, the instance will be scoped to the lifetime of the returned + Client object (or when the script exits). This is + only relevant if connecting to a long-running Ray cluster (e.g., with + ray.init(address="auto") or ray.init("ray://")). + + Args: + http_options (Optional[Dict, serve.HTTPOptions]): Configuration options + for HTTP proxy. You can pass in a dictionary or HTTPOptions object + with fields: + + - host(str, None): Host for HTTP servers to listen on. Defaults to + "127.0.0.1". To expose Serve publicly, you probably want to set + this to "0.0.0.0". + - port(int): Port for HTTP server. Defaults to 8000. + - root_path(str): Root path to mount the serve application + (for example, "/serve"). All deployment routes will be prefixed + with this path. Defaults to "". + - middlewares(list): A list of Starlette middlewares that will be + applied to the HTTP servers in the cluster. Defaults to []. + - location(str, serve.config.DeploymentMode): The deployment + location of HTTP servers: + + - "HeadOnly": start one HTTP server on the head node. Serve + assumes the head node is the node you executed serve.start + on. This is the default. + - "EveryNode": start one HTTP server per node. + - "NoServer" or None: disable HTTP server. + - num_cpus (int): The number of CPU cores to reserve for each + internal Serve HTTP proxy actor. Defaults to 0. + grpc_options: [Experimental] Configuration options for gRPC proxy. + You can pass in a gRPCOptions object with fields: + + - port(int): Port for gRPC server. Defaults to 9000. + - grpc_servicer_functions(list): List of import paths for gRPC + `add_servicer_to_server` functions to add to Serve's gRPC proxy. + Default empty list, meaning not to start the gRPC server. + """ + + usage_lib.record_library_usage("serve") + + try: + client = _get_global_client(_health_check_controller=True) + logger.info( + f'Connecting to existing Serve app in namespace "{SERVE_NAMESPACE}".' + " New http options will not be applied." + ) + if http_options: + _check_http_options(client, http_options) + return client + except RayServeException: + pass + + controller = _start_controller( + http_options, grpc_options, global_logging_config, **kwargs + ) + + client = ServeControllerClient( + controller, + ) + _set_global_client(client) + logger.info(f'Started Serve in namespace "{SERVE_NAMESPACE}".') + return client + + +def call_user_app_builder_with_args_if_necessary( + builder: Union[Application, FunctionType], + args: Dict[str, Any], +) -> Application: + """Calls a user-provided function that returns Serve application. + + If an Application object is passed, this is a no-op. + + Else, we validate the signature of the function, convert the args dictionary to + the user-annotated Pydantic model if provided, and call the function. + + The output of the function is returned (must be an Application). + """ + if isinstance(builder, Application): + if len(args) > 0: + raise ValueError( + "Arguments can only be passed to an application builder function, " + "not an already built application." + ) + return builder + elif not isinstance(builder, FunctionType): + raise TypeError( + "Expected a built Serve application or an application builder function " + f"but got: {type(builder)}." + ) + + # Check that the builder only takes a single argument. + # TODO(edoakes): we may want to loosen this to allow optional kwargs in the future. + signature = inspect.signature(builder) + if len(signature.parameters) != 1: + raise TypeError( + "Application builder functions should take exactly one parameter, " + "a dictionary containing the passed arguments." + ) + + # If the sole argument to the builder is a pydantic model, convert the args dict to + # that model. This will perform standard pydantic validation (e.g., raise an + # exception if required fields are missing). + param = signature.parameters[list(signature.parameters.keys())[0]] + if inspect.isclass(param.annotation) and is_subclass_of_base_model( + param.annotation + ): + args = param.annotation.parse_obj(args) + + app = builder(args) + if not isinstance(app, Application): + raise TypeError( + "Application builder functions must return an `Application` returned " + f"`from `Deployment.bind()`, but got: {type(app)}." + ) + + return app diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/application_state.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/application_state.py new file mode 100644 index 0000000000000000000000000000000000000000..41108f62edd469ae2525a6fda500f579a326a25a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/application_state.py @@ -0,0 +1,1358 @@ +import inspect +import json +import logging +import os +import time +import traceback +from copy import deepcopy +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Dict, List, Optional, Tuple + +import ray +from ray import cloudpickle +from ray._common.utils import import_attr +from ray.exceptions import RuntimeEnvSetupError +from ray.serve._private.build_app import BuiltApplication, build_app +from ray.serve._private.common import ( + DeploymentID, + DeploymentStatus, + DeploymentStatusInfo, + DeploymentStatusTrigger, + EndpointInfo, + TargetCapacityDirection, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import RAY_SERVE_ENABLE_TASK_EVENTS, SERVE_LOGGER_NAME +from ray.serve._private.deploy_utils import ( + deploy_args_to_deployment_info, + get_app_code_version, + get_deploy_args, +) +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.deployment_state import DeploymentStateManager +from ray.serve._private.endpoint_state import EndpointState +from ray.serve._private.logging_utils import configure_component_logger +from ray.serve._private.storage.kv_store import KVStoreBase +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + DEFAULT, + check_obj_ref_ready_nowait, + override_runtime_envs_except_env_vars, + validate_route_prefix, +) +from ray.serve.api import ASGIAppReplicaWrapper +from ray.serve.config import AutoscalingConfig +from ray.serve.exceptions import RayServeException +from ray.serve.generated.serve_pb2 import ( + ApplicationStatus as ApplicationStatusProto, + ApplicationStatusInfo as ApplicationStatusInfoProto, + DeploymentLanguage, + DeploymentStatusInfoList as DeploymentStatusInfoListProto, + StatusOverview as StatusOverviewProto, +) +from ray.serve.schema import ( + APIType, + ApplicationStatus, + DeploymentDetails, + LoggingConfig, + ServeApplicationSchema, +) +from ray.types import ObjectRef + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +CHECKPOINT_KEY = "serve-application-state-checkpoint" + + +class BuildAppStatus(Enum): + """Status of the build application task.""" + + NO_TASK_IN_PROGRESS = 1 + IN_PROGRESS = 2 + SUCCEEDED = 3 + FAILED = 4 + + +@dataclass +class BuildAppTaskInfo: + """Stores info on the current in-progress build app task. + + We use a class instead of only storing the task object ref because + when a new config is deployed, there can be an outdated in-progress + build app task. We attach the code version to the task info to + distinguish outdated build app tasks. + """ + + obj_ref: ObjectRef + code_version: str + config: ServeApplicationSchema + target_capacity: Optional[float] + target_capacity_direction: Optional[TargetCapacityDirection] + finished: bool + + +@dataclass(eq=True) +class ApplicationStatusInfo: + status: ApplicationStatus + message: str = "" + deployment_timestamp: float = 0 + + def debug_string(self): + return json.dumps(asdict(self), indent=4) + + def to_proto(self): + return ApplicationStatusInfoProto( + status=f"APPLICATION_STATUS_{self.status.name}", + message=self.message, + deployment_timestamp=self.deployment_timestamp, + ) + + @classmethod + def from_proto(cls, proto: ApplicationStatusInfoProto): + status = ApplicationStatusProto.Name(proto.status)[len("APPLICATION_STATUS_") :] + return cls( + status=ApplicationStatus(status), + message=proto.message, + deployment_timestamp=proto.deployment_timestamp, + ) + + +@dataclass(eq=True) +class StatusOverview: + app_status: ApplicationStatusInfo + name: str = "" + deployment_statuses: List[DeploymentStatusInfo] = field(default_factory=list) + + def debug_string(self): + return json.dumps(asdict(self), indent=4) + + def get_deployment_status(self, name: str) -> Optional[DeploymentStatusInfo]: + """Get a deployment's status by name. + + Args: + name: Deployment's name. + + Returns: + Optional[DeploymentStatusInfo]: The status of the deployment if it exists, + otherwise None. + """ + + for deployment_status in self.deployment_statuses: + if name == deployment_status.name: + return deployment_status + + return None + + def to_proto(self): + # Create a protobuf for the Serve Application info + app_status_proto = self.app_status.to_proto() + + # Create protobufs for all individual deployment statuses + deployment_status_protos = map( + lambda status: status.to_proto(), self.deployment_statuses + ) + + # Create a protobuf list containing all the deployment status protobufs + deployment_status_proto_list = DeploymentStatusInfoListProto() + deployment_status_proto_list.deployment_status_infos.extend( + deployment_status_protos + ) + + # Return protobuf encapsulating application and deployment protos + return StatusOverviewProto( + name=self.name, + app_status=app_status_proto, + deployment_statuses=deployment_status_proto_list, + ) + + @classmethod + def from_proto(cls, proto: StatusOverviewProto) -> "StatusOverview": + # Recreate Serve Application info + app_status = ApplicationStatusInfo.from_proto(proto.app_status) + + # Recreate deployment statuses + deployment_statuses = [] + for info_proto in proto.deployment_statuses.deployment_status_infos: + deployment_statuses.append(DeploymentStatusInfo.from_proto(info_proto)) + + # Recreate StatusInfo + return cls( + app_status=app_status, + deployment_statuses=deployment_statuses, + name=proto.name, + ) + + +@dataclass +class ApplicationTargetState: + """Defines target state of application. + + Target state can become inconsistent if the code version doesn't + match that of the config. When that happens, a new build app task + should be kicked off to reconcile the inconsistency. + + deployment_infos: map of deployment name to deployment info. This is + - None if a config was deployed but the app hasn't finished + building yet, + - An empty dict if the app is deleting. + code_version: Code version of all deployments in target state. None + if application was deployed through serve.run. + config: application config deployed by user. None if application was + deployed through serve.run. + target_capacity: the target_capacity to use when adjusting num_replicas. + target_capacity_direction: the scale direction to use when + running the Serve autoscaler. + deleting: whether the application is being deleted. + """ + + deployment_infos: Optional[Dict[str, DeploymentInfo]] + code_version: Optional[str] + config: Optional[ServeApplicationSchema] + target_capacity: Optional[float] + target_capacity_direction: Optional[TargetCapacityDirection] + deleting: bool + api_type: APIType + + +class ApplicationState: + """Manage single application states with all operations""" + + def __init__( + self, + name: str, + deployment_state_manager: DeploymentStateManager, + endpoint_state: EndpointState, + logging_config: LoggingConfig, + ): + """ + Args: + name: Application name. + deployment_state_manager: State manager for all deployments + in the cluster. + endpoint_state: State manager for endpoints in the system. + """ + + self._name = name + self._status_msg = "" + self._deployment_state_manager = deployment_state_manager + self._endpoint_state = endpoint_state + self._route_prefix: Optional[str] = None + self._ingress_deployment_name: Optional[str] = None + + self._status: ApplicationStatus = ApplicationStatus.DEPLOYING + self._deployment_timestamp = time.time() + + self._build_app_task_info: Optional[BuildAppTaskInfo] = None + # Before a deploy app task finishes, we don't know what the + # target deployments are, so set deployment_infos=None + self._target_state: ApplicationTargetState = ApplicationTargetState( + deployment_infos=None, + code_version=None, + config=None, + target_capacity=None, + target_capacity_direction=None, + deleting=False, + api_type=APIType.UNKNOWN, + ) + self._logging_config = logging_config + + @property + def route_prefix(self) -> Optional[str]: + return self._route_prefix + + @property + def docs_path(self) -> Optional[str]: + # get the docs path from the running deployments + # we are making an assumption that the docs path can only be set + # on ingress deployments with fastapi. + ingress_deployment = DeploymentID(self._ingress_deployment_name, self._name) + return self._deployment_state_manager.get_deployment_docs_path( + ingress_deployment + ) + + @property + def status(self) -> ApplicationStatus: + """Status of the application. + + DEPLOYING: The build task is still running, or the deployments + have started deploying but aren't healthy yet. + RUNNING: All deployments are healthy. + DEPLOY_FAILED: The build task failed or one or more deployments + became unhealthy in the process of deploying + UNHEALTHY: While the application was running, one or more + deployments transition from healthy to unhealthy. + DELETING: Application and its deployments are being deleted. + """ + return self._status + + @property + def deployment_timestamp(self) -> float: + return self._deployment_timestamp + + @property + def target_deployments(self) -> List[str]: + """List of target deployment names in application.""" + if self._target_state.deployment_infos is None: + return [] + return list(self._target_state.deployment_infos.keys()) + + @property + def ingress_deployment(self) -> Optional[str]: + return self._ingress_deployment_name + + @property + def api_type(self) -> APIType: + return self._target_state.api_type + + def recover_target_state_from_checkpoint( + self, checkpoint_data: ApplicationTargetState + ): + logger.info( + f"Recovering target state for application '{self._name}' from checkpoint." + ) + self._set_target_state( + checkpoint_data.deployment_infos, + api_type=checkpoint_data.api_type, + code_version=checkpoint_data.code_version, + target_config=checkpoint_data.config, + target_capacity=checkpoint_data.target_capacity, + target_capacity_direction=checkpoint_data.target_capacity_direction, + deleting=checkpoint_data.deleting, + ) + + # Restore route prefix and docs path from checkpointed deployments when + # the imperatively started application is restarting with controller. + if checkpoint_data.deployment_infos is not None: + self._route_prefix = self._check_routes(checkpoint_data.deployment_infos) + + def _set_target_state( + self, + deployment_infos: Optional[Dict[str, DeploymentInfo]], + *, + api_type: APIType, + code_version: Optional[str], + target_config: Optional[ServeApplicationSchema], + target_capacity: Optional[float] = None, + target_capacity_direction: Optional[TargetCapacityDirection] = None, + deleting: bool = False, + ): + """Set application target state. + + While waiting for build task to finish, this should be + (None, False) + When build task has finished and during normal operation, this should be + (target_deployments, False) + When a request to delete the application has been received, this should be + ({}, True) + """ + if deleting: + self._update_status(ApplicationStatus.DELETING) + else: + self._update_status(ApplicationStatus.DEPLOYING) + + if deployment_infos is None: + self._ingress_deployment_name = None + else: + for name, info in deployment_infos.items(): + if info.ingress: + self._ingress_deployment_name = name + + target_state = ApplicationTargetState( + deployment_infos, + code_version, + target_config, + target_capacity, + target_capacity_direction, + deleting, + api_type=api_type, + ) + + self._target_state = target_state + + def _set_target_state_deleting(self): + """Set target state to deleting. + + Wipes the target deployment infos, code version, and config. + """ + self._set_target_state( + deployment_infos={}, + api_type=self._target_state.api_type, + code_version=None, + target_config=None, + deleting=True, + ) + + def _clear_target_state_and_store_config( + self, + target_config: Optional[ServeApplicationSchema], + ): + """Clears the target state and stores the config. + + NOTE: this currently assumes that this method is *only* called when managing + apps deployed with the declarative API. + """ + self._set_target_state( + deployment_infos=None, + api_type=APIType.DECLARATIVE, + code_version=None, + target_config=target_config, + deleting=False, + ) + + def _delete_deployment(self, name): + id = DeploymentID(name=name, app_name=self._name) + self._endpoint_state.delete_endpoint(id) + self._deployment_state_manager.delete_deployment(id) + + def delete(self): + """Delete the application""" + if self._status != ApplicationStatus.DELETING: + logger.info( + f"Deleting app '{self._name}'.", + extra={"log_to_stderr": False}, + ) + self._set_target_state_deleting() + + def is_deleted(self) -> bool: + """Check whether the application is already deleted. + + For an application to be considered deleted, the target state has to be set to + deleting and all deployments have to be deleted. + """ + return self._target_state.deleting and len(self._get_live_deployments()) == 0 + + def apply_deployment_info( + self, + deployment_name: str, + deployment_info: DeploymentInfo, + ) -> None: + """Deploys a deployment in the application.""" + route_prefix = deployment_info.route_prefix + if route_prefix is not None and not route_prefix.startswith("/"): + raise RayServeException( + f'Invalid route prefix "{route_prefix}", it must start with "/"' + ) + + deployment_id = DeploymentID(name=deployment_name, app_name=self._name) + + self._deployment_state_manager.deploy(deployment_id, deployment_info) + + if deployment_info.route_prefix is not None: + config = deployment_info.deployment_config + self._endpoint_state.update_endpoint( + deployment_id, + # The current meaning of the "is_cross_language" field is ambiguous. + # We will work on optimizing and removing this field in the future. + # Instead of using the "is_cross_language" field, we will directly + # compare if the replica is Python, which will assist the Python + # router in determining if the replica invocation is a cross-language + # operation. + EndpointInfo( + route=deployment_info.route_prefix, + app_is_cross_language=config.deployment_language + != DeploymentLanguage.PYTHON, + ), + ) + else: + self._endpoint_state.delete_endpoint(deployment_id) + + def deploy_app(self, deployment_infos: Dict[str, DeploymentInfo]): + """(Re-)deploy the application from list of deployment infos. + + This function should only be called to deploy an app from an + imperative API (i.e., `serve.run` or Java API). + + Raises: RayServeException if there is more than one route prefix + or docs path. + """ + + self._check_ingress_deployments(deployment_infos) + # Check routes are unique in deployment infos + self._route_prefix = self._check_routes(deployment_infos) + + self._set_target_state( + deployment_infos=deployment_infos, + api_type=APIType.IMPERATIVE, + code_version=None, + target_config=None, + target_capacity=None, + target_capacity_direction=None, + ) + + def apply_app_config( + self, + config: ServeApplicationSchema, + target_capacity: Optional[float], + target_capacity_direction: Optional[TargetCapacityDirection], + deployment_time: float, + ) -> None: + """Apply the config to the application. + + If the code version matches that of the current live deployments + then it only applies the updated config to the deployment state + manager. If the code version doesn't match, this will re-build + the application. + + This function should only be called to (re-)deploy an app from + the declarative API (i.e., through the REST API). + """ + + self._deployment_timestamp = deployment_time + + config_version = get_app_code_version(config) + if config_version == self._target_state.code_version: + try: + overrided_infos = override_deployment_info( + self._target_state.deployment_infos, + config, + ) + self._route_prefix = self._check_routes(overrided_infos) + self._set_target_state( + # Code version doesn't change. + code_version=self._target_state.code_version, + api_type=APIType.DECLARATIVE, + # Everything else must reflect the new config. + deployment_infos=overrided_infos, + target_config=config, + target_capacity=target_capacity, + target_capacity_direction=target_capacity_direction, + ) + except (TypeError, ValueError, RayServeException): + self._clear_target_state_and_store_config(config) + self._update_status( + ApplicationStatus.DEPLOY_FAILED, traceback.format_exc() + ) + except Exception: + self._clear_target_state_and_store_config(config) + self._update_status( + ApplicationStatus.DEPLOY_FAILED, + ( + f"Unexpected error occurred while applying config for " + f"application '{self._name}': \n{traceback.format_exc()}" + ), + ) + else: + # If there is an in progress build task, cancel it. + if self._build_app_task_info and not self._build_app_task_info.finished: + logger.info( + f"Received new config for application '{self._name}'. " + "Cancelling previous request." + ) + ray.cancel(self._build_app_task_info.obj_ref) + + # Halt reconciliation of target deployments. A new target state + # will be set once the new app has finished building. + self._clear_target_state_and_store_config(config) + + # Record telemetry for container runtime env feature + if self._target_state.config.runtime_env.get( + "container" + ) or self._target_state.config.runtime_env.get("image_uri"): + ServeUsageTag.APP_CONTAINER_RUNTIME_ENV_USED.record("1") + + # Kick off new build app task + logger.info(f"Importing and building app '{self._name}'.") + build_app_obj_ref = build_serve_application.options( + runtime_env=config.runtime_env, + enable_task_events=RAY_SERVE_ENABLE_TASK_EVENTS, + ).remote( + config.import_path, + config_version, + config.name, + config.args, + self._logging_config, + ) + self._build_app_task_info = BuildAppTaskInfo( + obj_ref=build_app_obj_ref, + code_version=config_version, + config=config, + target_capacity=target_capacity, + target_capacity_direction=target_capacity_direction, + finished=False, + ) + + def _get_live_deployments(self) -> List[str]: + return self._deployment_state_manager.get_deployments_in_application(self._name) + + def _determine_app_status(self) -> Tuple[ApplicationStatus, str]: + """Check deployment statuses and target state, and determine the + corresponding application status. + + Returns: + Status (ApplicationStatus): + RUNNING: all deployments are healthy or autoscaling. + DEPLOYING: there is one or more updating deployments, + and there are no unhealthy deployments. + DEPLOY_FAILED: one or more deployments became unhealthy + while the application was deploying. + UNHEALTHY: one or more deployments became unhealthy + while the application was running. + DELETING: the application is being deleted. + Error message (str): + Non-empty string if status is DEPLOY_FAILED or UNHEALTHY + """ + + if self._target_state.deleting: + return ApplicationStatus.DELETING, "" + + # Get the lowest rank, i.e. highest priority, deployment status info object + # The deployment status info with highest priority determines the corresponding + # application status to set. + deployment_statuses = self.get_deployments_statuses() + lowest_rank_status = min(deployment_statuses, key=lambda info: info.rank) + if lowest_rank_status.status == DeploymentStatus.DEPLOY_FAILED: + failed_deployments = [ + s.name + for s in deployment_statuses + if s.status == DeploymentStatus.DEPLOY_FAILED + ] + return ( + ApplicationStatus.DEPLOY_FAILED, + f"Failed to update the deployments {failed_deployments}.", + ) + elif lowest_rank_status.status == DeploymentStatus.UNHEALTHY: + unhealthy_deployment_names = [ + s.name + for s in deployment_statuses + if s.status == DeploymentStatus.UNHEALTHY + ] + return ( + ApplicationStatus.UNHEALTHY, + f"The deployments {unhealthy_deployment_names} are UNHEALTHY.", + ) + elif lowest_rank_status.status == DeploymentStatus.UPDATING: + return ApplicationStatus.DEPLOYING, "" + elif ( + lowest_rank_status.status + in [DeploymentStatus.UPSCALING, DeploymentStatus.DOWNSCALING] + and lowest_rank_status.status_trigger + == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED + ): + return ApplicationStatus.DEPLOYING, "" + else: + return ApplicationStatus.RUNNING, "" + + def _reconcile_build_app_task(self) -> Tuple[Optional[Dict], BuildAppStatus, str]: + """If necessary, reconcile the in-progress build task. + + Returns: + Deploy arguments (Dict[str, DeploymentInfo]): + The deploy arguments returned from the build app task + and their code version. + Status (BuildAppStatus): + NO_TASK_IN_PROGRESS: There is no build task to reconcile. + SUCCEEDED: Task finished successfully. + FAILED: An error occurred during execution of build app task + IN_PROGRESS: Task hasn't finished yet. + Error message (str): + Non-empty string if status is DEPLOY_FAILED or UNHEALTHY + """ + if self._build_app_task_info is None or self._build_app_task_info.finished: + return None, BuildAppStatus.NO_TASK_IN_PROGRESS, "" + + if not check_obj_ref_ready_nowait(self._build_app_task_info.obj_ref): + return None, BuildAppStatus.IN_PROGRESS, "" + + # Retrieve build app task result + self._build_app_task_info.finished = True + try: + args, err = ray.get(self._build_app_task_info.obj_ref) + if err is None: + logger.info(f"Imported and built app '{self._name}' successfully.") + else: + return ( + None, + BuildAppStatus.FAILED, + f"Deploying app '{self._name}' failed with exception:\n{err}", + ) + except RuntimeEnvSetupError: + error_msg = ( + f"Runtime env setup for app '{self._name}' failed:\n" + + traceback.format_exc() + ) + return None, BuildAppStatus.FAILED, error_msg + except Exception: + error_msg = ( + f"Unexpected error occurred while deploying application " + f"'{self._name}': \n{traceback.format_exc()}" + ) + return None, BuildAppStatus.FAILED, error_msg + + # Convert serialized deployment args (returned by build app task) + # to deployment infos and apply option overrides from config + try: + deployment_infos = { + params["deployment_name"]: deploy_args_to_deployment_info( + **params, app_name=self._name + ) + for params in args + } + overrided_infos = override_deployment_info( + deployment_infos, self._build_app_task_info.config + ) + self._route_prefix = self._check_routes(overrided_infos) + return overrided_infos, BuildAppStatus.SUCCEEDED, "" + except (TypeError, ValueError, RayServeException): + return None, BuildAppStatus.FAILED, traceback.format_exc() + except Exception: + error_msg = ( + f"Unexpected error occurred while applying config for application " + f"'{self._name}': \n{traceback.format_exc()}" + ) + return None, BuildAppStatus.FAILED, error_msg + + def _check_ingress_deployments( + self, deployment_infos: Dict[str, DeploymentInfo] + ) -> None: + """Check @serve.ingress of deployments in app. + + Raises: RayServeException if more than one @serve.ingress + is found among deployments. + """ + num_ingress_deployments = 0 + for info in deployment_infos.values(): + if inspect.isclass(info.replica_config.deployment_def) and issubclass( + info.replica_config.deployment_def, ASGIAppReplicaWrapper + ): + num_ingress_deployments += 1 + + if num_ingress_deployments > 1: + raise RayServeException( + f'Found multiple FastAPI deployments in application "{self._name}".' + "Please only include one deployment with @serve.ingress" + "in your application to avoid this issue." + ) + + def _check_routes( + self, deployment_infos: Dict[str, DeploymentInfo] + ) -> Tuple[str, str]: + """Check route prefixes of deployments in app. + + There should only be one non-null route prefix. If there is one, + set it as the application route prefix. This function must be + run every control loop iteration because the target config could + be updated without kicking off a new task. + + Returns: route prefix. + Raises: RayServeException if more than one route prefix is found among deployments. + """ + num_route_prefixes = 0 + route_prefix = None + for info in deployment_infos.values(): + # Update route prefix of application, which may be updated + # through a redeployed config. + if info.route_prefix is not None: + route_prefix = info.route_prefix + num_route_prefixes += 1 + + if num_route_prefixes > 1: + raise RayServeException( + f'Found multiple route prefixes from application "{self._name}",' + " Please specify only one route prefix for the application " + "to avoid this issue." + ) + + return route_prefix + + def _reconcile_target_deployments(self) -> None: + """Reconcile target deployments in application target state. + + Ensure each deployment is running on up-to-date info, and + remove outdated deployments from the application. + """ + + # Set target state for each deployment + for deployment_name, info in self._target_state.deployment_infos.items(): + deploy_info = deepcopy(info) + + # Apply the target capacity information to the deployment info. + deploy_info.set_target_capacity( + new_target_capacity=self._target_state.target_capacity, + new_target_capacity_direction=( + self._target_state.target_capacity_direction + ), + ) + + # Apply the application logging config to the deployment logging config + # if it is not set. + if ( + self._target_state.config + and self._target_state.config.logging_config + and deploy_info.deployment_config.logging_config is None + ): + deploy_info.deployment_config.logging_config = ( + self._target_state.config.logging_config + ) + self.apply_deployment_info(deployment_name, deploy_info) + + # Delete outdated deployments + for deployment_name in self._get_live_deployments(): + if deployment_name not in self.target_deployments: + self._delete_deployment(deployment_name) + + def update(self) -> bool: + """Attempts to reconcile this application to match its target state. + + Updates the application status and status message based on the + current state of the system. + + Returns: + A boolean indicating whether the application is ready to be + deleted. + """ + + infos, task_status, msg = self._reconcile_build_app_task() + if task_status == BuildAppStatus.SUCCEEDED: + self._set_target_state( + deployment_infos=infos, + code_version=self._build_app_task_info.code_version, + api_type=self._target_state.api_type, + target_config=self._build_app_task_info.config, + target_capacity=self._build_app_task_info.target_capacity, + target_capacity_direction=( + self._build_app_task_info.target_capacity_direction + ), + ) + elif task_status == BuildAppStatus.FAILED: + self._update_status(ApplicationStatus.DEPLOY_FAILED, msg) + + # Only reconcile deployments when the build app task is finished. If + # it's not finished, we don't know what the target list of deployments + # is, so we don't perform any reconciliation. + if self._target_state.deployment_infos is not None: + self._reconcile_target_deployments() + status, status_msg = self._determine_app_status() + self._update_status(status, status_msg) + + # Check if app is ready to be deleted + if self._target_state.deleting: + return self.is_deleted() + return False + + def get_checkpoint_data(self) -> ApplicationTargetState: + return self._target_state + + def get_deployments_statuses(self) -> List[DeploymentStatusInfo]: + """Return all deployment status information""" + deployments = [ + DeploymentID(name=deployment, app_name=self._name) + for deployment in self.target_deployments + ] + return self._deployment_state_manager.get_deployment_statuses(deployments) + + def get_application_status_info(self) -> ApplicationStatusInfo: + """Return the application status information""" + return ApplicationStatusInfo( + self._status, + message=self._status_msg, + deployment_timestamp=self._deployment_timestamp, + ) + + def list_deployment_details(self) -> Dict[str, DeploymentDetails]: + """Gets detailed info on all live deployments in this application. + (Does not include deleted deployments.) + + Returns: + A dictionary of deployment infos. The set of deployment info returned + may not be the full list of deployments that are part of the application. + This can happen when the application is still deploying and bringing up + deployments, or when the application is deleting and some deployments have + been deleted. + """ + details = { + deployment_name: self._deployment_state_manager.get_deployment_details( + DeploymentID(name=deployment_name, app_name=self._name) + ) + for deployment_name in self.target_deployments + } + return {k: v for k, v in details.items() if v is not None} + + def _update_status(self, status: ApplicationStatus, status_msg: str = "") -> None: + if ( + status_msg + and status + in [ + ApplicationStatus.DEPLOY_FAILED, + ApplicationStatus.UNHEALTHY, + ] + and status_msg != self._status_msg + ): + logger.error(status_msg) + + self._status = status + self._status_msg = status_msg + + +class ApplicationStateManager: + def __init__( + self, + deployment_state_manager: DeploymentStateManager, + endpoint_state: EndpointState, + kv_store: KVStoreBase, + logging_config: LoggingConfig, + ): + self._deployment_state_manager = deployment_state_manager + self._endpoint_state = endpoint_state + self._kv_store = kv_store + self._logging_config = logging_config + + self._shutting_down = False + + self._application_states: Dict[str, ApplicationState] = {} + self._recover_from_checkpoint() + + def _recover_from_checkpoint(self): + checkpoint = self._kv_store.get(CHECKPOINT_KEY) + if checkpoint is not None: + application_state_info = cloudpickle.loads(checkpoint) + + for app_name, checkpoint_data in application_state_info.items(): + app_state = ApplicationState( + app_name, + self._deployment_state_manager, + self._endpoint_state, + self._logging_config, + ) + app_state.recover_target_state_from_checkpoint(checkpoint_data) + self._application_states[app_name] = app_state + + def delete_app(self, name: str) -> None: + """Delete application by name""" + if name not in self._application_states: + return + self._application_states[name].delete() + + def deploy_apps(self, name_to_deployment_args: Dict[str, List[Dict]]) -> None: + live_route_prefixes: Dict[str, str] = { + app_state.route_prefix: app_name + for app_name, app_state in self._application_states.items() + if app_state.route_prefix is not None + and not app_state.status == ApplicationStatus.DELETING + } + + for name, deployment_args in name_to_deployment_args.items(): + for deploy_param in deployment_args: + # Make sure route_prefix is not being used by other application. + deploy_app_prefix = deploy_param.get("route_prefix") + if deploy_app_prefix is None: + continue + + existing_app_name = live_route_prefixes.get(deploy_app_prefix) + # It's ok to redeploy an app with the same prefix + # if it has the same name as the app already using that prefix. + if existing_app_name is not None and existing_app_name != name: + raise RayServeException( + f"Prefix {deploy_app_prefix} is being used by application " + f'"{existing_app_name}". Failed to deploy application "{name}".' + ) + + # We might be deploying more than one app, + # so we need to add this app's prefix to the + # set of live route prefixes that we're checking + # against during this batch operation. + live_route_prefixes[deploy_app_prefix] = name + + if name not in self._application_states: + self._application_states[name] = ApplicationState( + name, + self._deployment_state_manager, + self._endpoint_state, + self._logging_config, + ) + ServeUsageTag.NUM_APPS.record(str(len(self._application_states))) + + deployment_infos = { + params["deployment_name"]: deploy_args_to_deployment_info( + **params, app_name=name + ) + for params in deployment_args + } + self._application_states[name].deploy_app(deployment_infos) + + def deploy_app(self, name: str, deployment_args: List[Dict]) -> None: + """Deploy the specified app to the list of deployment arguments. + + This function should only be called if the app is being deployed + through serve.run instead of from a config. + + Args: + name: application name + deployment_args_list: arguments for deploying a list of deployments. + + Raises: + RayServeException: If the list of deployments is trying to + use a route prefix that is already used by another application + """ + self.deploy_apps({name: deployment_args}) + + def apply_app_configs( + self, + app_configs: List[ServeApplicationSchema], + *, + deployment_time: float = 0, + target_capacity: Optional[float] = None, + target_capacity_direction: Optional[TargetCapacityDirection] = None, + ): + """Declaratively apply the list of application configs. + + The applications will be reconciled to match the target state of the config. + + Any applications previously deployed declaratively that are *not* present in + the list will be deleted. + """ + for app_config in app_configs: + if app_config.name not in self._application_states: + logger.info(f"Deploying new app '{app_config.name}'.") + self._application_states[app_config.name] = ApplicationState( + app_config.name, + self._deployment_state_manager, + endpoint_state=self._endpoint_state, + logging_config=self._logging_config, + ) + + self._application_states[app_config.name].apply_app_config( + app_config, + target_capacity, + target_capacity_direction, + deployment_time=deployment_time, + ) + + # Delete all apps that were previously deployed via the declarative API + # but are not in the config being applied. + existing_apps = { + name + for name, app_state in self._application_states.items() + if app_state.api_type == APIType.DECLARATIVE + } + apps_in_config = {app_config.name for app_config in app_configs} + for app_to_delete in existing_apps - apps_in_config: + self.delete_app(app_to_delete) + + ServeUsageTag.NUM_APPS.record(str(len(self._application_states))) + + def get_deployments(self, app_name: str) -> List[str]: + """Return all deployment names by app name""" + if app_name not in self._application_states: + return [] + return self._application_states[app_name].target_deployments + + def get_deployments_statuses(self, app_name: str) -> List[DeploymentStatusInfo]: + """Return all deployment statuses by app name""" + if app_name not in self._application_states: + return [] + return self._application_states[app_name].get_deployments_statuses() + + def get_app_status(self, name: str) -> ApplicationStatus: + if name not in self._application_states: + return ApplicationStatus.NOT_STARTED + + return self._application_states[name].status + + def get_app_status_info(self, name: str) -> ApplicationStatusInfo: + if name not in self._application_states: + return ApplicationStatusInfo( + ApplicationStatus.NOT_STARTED, + message=f"Application {name} doesn't exist", + deployment_timestamp=0, + ) + return self._application_states[name].get_application_status_info() + + def get_docs_path(self, app_name: str) -> Optional[str]: + return self._application_states[app_name].docs_path + + def get_route_prefix(self, name: str) -> Optional[str]: + return self._application_states[name].route_prefix + + def get_ingress_deployment_name(self, name: str) -> Optional[str]: + if name not in self._application_states: + return None + + return self._application_states[name].ingress_deployment + + def get_app_source(self, name: str) -> APIType: + return self._application_states[name].api_type + + def list_app_statuses(self) -> Dict[str, ApplicationStatusInfo]: + """Return a dictionary with {app name: application info}""" + return { + name: self._application_states[name].get_application_status_info() + for name in self._application_states + } + + def list_deployment_details(self, name: str) -> Dict[str, DeploymentDetails]: + """Gets detailed info on all deployments in specified application.""" + if name not in self._application_states: + return {} + return self._application_states[name].list_deployment_details() + + def update(self): + """Update each application state""" + apps_to_be_deleted = [] + for name, app in self._application_states.items(): + ready_to_be_deleted = app.update() + if ready_to_be_deleted: + apps_to_be_deleted.append(name) + logger.debug(f"Application '{name}' deleted successfully.") + + if len(apps_to_be_deleted) > 0: + for app_name in apps_to_be_deleted: + del self._application_states[app_name] + ServeUsageTag.NUM_APPS.record(str(len(self._application_states))) + + def shutdown(self) -> None: + self._shutting_down = True + + for app_state in self._application_states.values(): + app_state.delete() + + self._kv_store.delete(CHECKPOINT_KEY) + + def is_ready_for_shutdown(self) -> bool: + """Return whether all applications have shut down. + + Iterate through all application states and check if all their applications + are deleted. + """ + return self._shutting_down and all( + app_state.is_deleted() for app_state in self._application_states.values() + ) + + def save_checkpoint(self) -> None: + """Write a checkpoint of all application states.""" + if self._shutting_down: + # Once we're told to shut down, stop writing checkpoints. + # Calling .shutdown() deletes any existing checkpoint. + return + + application_state_info = { + app_name: app_state.get_checkpoint_data() + for app_name, app_state in self._application_states.items() + } + + self._kv_store.put( + CHECKPOINT_KEY, + cloudpickle.dumps(application_state_info), + ) + + +@ray.remote(num_cpus=0, max_calls=1) +def build_serve_application( + import_path: str, + code_version: str, + name: str, + args: Dict, + logging_config: LoggingConfig, +) -> Tuple[Optional[List[Dict]], Optional[str]]: + """Import and build a Serve application. + + Args: + import_path: import path to top-level bound deployment. + code_version: code version inferred from app config. All + deployment versions are set to this code version. + name: application name. If specified, application will be deployed + without removing existing applications. + args: Arguments to be passed to the application builder. + logging_config: the logging config for the build app task. + Returns: + Deploy arguments: a list of deployment arguments if application + was built successfully, otherwise None. + Error message: a string if an error was raised, otherwise None. + """ + configure_component_logger( + component_name="controller", + component_id=f"build_{name}_{os.getpid()}", + logging_config=logging_config, + ) + + try: + from ray.serve._private.api import call_user_app_builder_with_args_if_necessary + + # Import and build the application. + args_info_str = f" with arguments {args}" if args else "" + logger.info(f"Importing application '{name}'{args_info_str}.") + + app = call_user_app_builder_with_args_if_necessary( + import_attr(import_path), args + ) + + deploy_args_list = [] + built_app: BuiltApplication = build_app( + app, + name=name, + default_runtime_env=ray.get_runtime_context().runtime_env, + ) + num_ingress_deployments = 0 + for deployment in built_app.deployments: + if inspect.isclass(deployment.func_or_class) and issubclass( + deployment.func_or_class, ASGIAppReplicaWrapper + ): + num_ingress_deployments += 1 + is_ingress = deployment.name == built_app.ingress_deployment_name + deploy_args_list.append( + get_deploy_args( + name=deployment._name, + replica_config=deployment._replica_config, + ingress=is_ingress, + deployment_config=deployment._deployment_config, + version=code_version, + route_prefix="/" if is_ingress else None, + ) + ) + if num_ingress_deployments > 1: + return None, ( + f'Found multiple FastAPI deployments in application "{built_app.name}". ' + "Please only include one deployment with @serve.ingress " + "in your application to avoid this issue." + ) + return deploy_args_list, None + except KeyboardInterrupt: + # Error is raised when this task is canceled with ray.cancel(), which + # happens when deploy_apps() is called. + logger.info( + "Existing config deployment request terminated because of keyboard " + "interrupt." + ) + return None, None + except Exception: + logger.error( + f"Exception importing application '{name}'.\n{traceback.format_exc()}" + ) + return None, traceback.format_exc() + + +def override_deployment_info( + deployment_infos: Dict[str, DeploymentInfo], + override_config: Optional[ServeApplicationSchema], +) -> Dict[str, DeploymentInfo]: + """Override deployment infos with options from app config. + + Args: + app_name: application name + deployment_infos: deployment info loaded from code + override_config: application config deployed by user with + options to override those loaded from code. + + Returns: the updated deployment infos. + + Raises: + ValueError: If config options have invalid values. + TypeError: If config options have invalid types. + """ + + deployment_infos = deepcopy(deployment_infos) + if override_config is None: + return deployment_infos + + config_dict = override_config.dict(exclude_unset=True) + deployment_override_options = config_dict.get("deployments", []) + + # Override options for each deployment listed in the config. + for options in deployment_override_options: + if "max_ongoing_requests" in options: + options["max_ongoing_requests"] = options.get("max_ongoing_requests") + + deployment_name = options["name"] + if deployment_name not in deployment_infos: + raise ValueError( + f"Deployment '{deployment_name}' does not exist. " + f"Available: {list(deployment_infos.keys())}" + ) + + info = deployment_infos[deployment_name] + original_options = info.deployment_config.dict() + original_options["user_configured_option_names"].update(set(options)) + + # Override `max_ongoing_requests` and `autoscaling_config` if + # `num_replicas="auto"` + if options.get("num_replicas") == "auto": + options["num_replicas"] = None + + new_config = AutoscalingConfig.default().dict() + # If `autoscaling_config` is specified, its values override + # the default `num_replicas="auto"` configuration + autoscaling_config = ( + options.get("autoscaling_config") + or info.deployment_config.autoscaling_config + ) + if autoscaling_config: + new_config.update(autoscaling_config) + + options["autoscaling_config"] = AutoscalingConfig(**new_config) + + ServeUsageTag.AUTO_NUM_REPLICAS_USED.record("1") + + # What to pass to info.update + override_options = {} + + # Merge app-level and deployment-level runtime_envs. + replica_config = info.replica_config + app_runtime_env = override_config.runtime_env + if "ray_actor_options" in options: + # If specified, get ray_actor_options from config + override_actor_options = options.pop("ray_actor_options", {}) + else: + # Otherwise, get options from application code (and default to {} + # if the code sets options to None). + override_actor_options = replica_config.ray_actor_options or {} + + override_placement_group_bundles = options.pop( + "placement_group_bundles", replica_config.placement_group_bundles + ) + override_placement_group_strategy = options.pop( + "placement_group_strategy", replica_config.placement_group_strategy + ) + + override_max_replicas_per_node = options.pop( + "max_replicas_per_node", replica_config.max_replicas_per_node + ) + + # Record telemetry for container runtime env feature at deployment level + if override_actor_options.get("runtime_env") and ( + override_actor_options["runtime_env"].get("container") + or override_actor_options["runtime_env"].get("image_uri") + ): + ServeUsageTag.DEPLOYMENT_CONTAINER_RUNTIME_ENV_USED.record("1") + + merged_env = override_runtime_envs_except_env_vars( + app_runtime_env, override_actor_options.get("runtime_env", {}) + ) + override_actor_options.update({"runtime_env": merged_env}) + + replica_config.update( + ray_actor_options=override_actor_options, + placement_group_bundles=override_placement_group_bundles, + placement_group_strategy=override_placement_group_strategy, + max_replicas_per_node=override_max_replicas_per_node, + ) + override_options["replica_config"] = replica_config + + # Override deployment config options + options.pop("name", None) + original_options.update(options) + override_options["deployment_config"] = DeploymentConfig(**original_options) + deployment_infos[deployment_name] = info.update(**override_options) + + deployment_config = deployment_infos[deployment_name].deployment_config + if ( + deployment_config.autoscaling_config is not None + and deployment_config.max_ongoing_requests + < deployment_config.autoscaling_config.get_target_ongoing_requests() + ): + logger.warning( + "Autoscaling will never happen, " + "because 'max_ongoing_requests' is less than " + "'target_ongoing_requests' now." + ) + + # Overwrite ingress route prefix + app_route_prefix = config_dict.get("route_prefix", DEFAULT.VALUE) + validate_route_prefix(app_route_prefix) + for deployment in list(deployment_infos.values()): + if ( + app_route_prefix is not DEFAULT.VALUE + and deployment.route_prefix is not None + ): + deployment.route_prefix = app_route_prefix + + return deployment_infos diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/autoscaling_state.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/autoscaling_state.py new file mode 100644 index 0000000000000000000000000000000000000000..c95abfa6cb5c5ec5631e35aa5946dcc38ec8645e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/autoscaling_state.py @@ -0,0 +1,478 @@ +import logging +import time +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Set + +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + ReplicaID, + TargetCapacityDirection, +) +from ray.serve._private.constants import ( + RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S, + SERVE_LOGGER_NAME, +) +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.utils import get_capacity_adjusted_num_replicas + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@dataclass +class HandleMetricReport: + """Report from a deployment handle on queued and ongoing requests. + + Args: + actor_id: If the deployment handle (from which this metric was + sent) lives on an actor, the actor ID of that actor. + handle_source: Describes what kind of entity holds this + deployment handle: a Serve proxy, a Serve replica, or + unknown. + queued_requests: The current number of queued requests at the + handle, i.e. requests that haven't been assigned to any + replica yet. + running_requests: A map of replica ID to the average number of + requests, assigned through the handle, running at that + replica. + timestamp: The time at which this report was received. + """ + + actor_id: Optional[str] + handle_source: DeploymentHandleSource + queued_requests: float + running_requests: Dict[ReplicaID, float] + timestamp: float + + @property + def total_requests(self) -> float: + """Total number of queued and running requests.""" + return self.queued_requests + sum(self.running_requests.values()) + + @property + def is_serve_component_source(self) -> bool: + """Whether the handle source is a Serve actor. + + More specifically, this returns whether a Serve actor tracked + by the controller holds the deployment handle that sent this + report. If the deployment handle lives on a driver, a Ray task, + or an actor that's not a Serve replica, then this returns False. + """ + return self.handle_source in [ + DeploymentHandleSource.PROXY, + DeploymentHandleSource.REPLICA, + ] + + +@dataclass +class ReplicaMetricReport: + """Report from a replica on ongoing requests. + + Args: + running_requests: Average number of running requests at the + replica. + timestamp: The time at which this report was received. + """ + + running_requests: float + timestamp: float + + +@dataclass +class AutoscalingContext: + """Rich context provided to custom autoscaling policies.""" + + # Deployment information + deployment_id: DeploymentID + deployment_name: str + app_name: Optional[str] + + # Current state + current_num_replicas: int + target_num_replicas: int + running_replicas: List[ReplicaID] + + # Built-in metrics + total_num_requests: float + queued_requests: Optional[float] + requests_per_replica: Dict[ReplicaID, float] + + # Custom metrics + aggregated_metrics: Dict[str, Dict[ReplicaID, float]] + raw_metrics: Dict[str, Dict[ReplicaID, List[float]]] + + # Capacity and bounds + capacity_adjusted_min_replicas: int + capacity_adjusted_max_replicas: int + + # Policy state + policy_state: Dict[str, Any] + + # Timing + last_scale_up_time: Optional[float] + last_scale_down_time: Optional[float] + current_time: Optional[float] + + # Config + config: Optional[Any] + + +class AutoscalingState: + """Manages autoscaling for a single deployment.""" + + def __init__(self, deployment_id: DeploymentID): + self._deployment_id = deployment_id + + # Map from handle ID to handle request metric report. Metrics + # are removed from this dict either when the actor on which the + # handle lived dies, or after a period of no updates. + self._handle_requests: Dict[str, HandleMetricReport] = dict() + # Map from replica ID to replica request metric report. Metrics + # are removed from this dict when a replica is stopped. + self._replica_requests: Dict[ReplicaID, ReplicaMetricReport] = dict() + + self._deployment_info = None + self._config = None + self._policy = None + self._running_replicas: List[ReplicaID] = [] + self._target_capacity: Optional[float] = None + self._target_capacity_direction: Optional[TargetCapacityDirection] = None + + def register(self, info: DeploymentInfo, curr_target_num_replicas: int) -> int: + """Registers an autoscaling deployment's info. + + Returns the number of replicas the target should be set to. + """ + + config = info.deployment_config.autoscaling_config + if ( + self._deployment_info is None or self._deployment_info.config_changed(info) + ) and config.initial_replicas is not None: + target_num_replicas = config.initial_replicas + else: + target_num_replicas = curr_target_num_replicas + + self._deployment_info = info + self._config = config + self._policy = self._config.get_policy() + self._target_capacity = info.target_capacity + self._target_capacity_direction = info.target_capacity_direction + self._policy_state = {} + + return self.apply_bounds(target_num_replicas) + + def on_replica_stopped(self, replica_id: ReplicaID): + if replica_id in self._replica_requests: + del self._replica_requests[replica_id] + + def get_num_replicas_lower_bound(self) -> int: + if self._config.initial_replicas is not None and ( + self._target_capacity_direction == TargetCapacityDirection.UP + ): + return get_capacity_adjusted_num_replicas( + self._config.initial_replicas, + self._target_capacity, + ) + else: + return get_capacity_adjusted_num_replicas( + self._config.min_replicas, + self._target_capacity, + ) + + def get_num_replicas_upper_bound(self) -> int: + return get_capacity_adjusted_num_replicas( + self._config.max_replicas, + self._target_capacity, + ) + + def update_running_replica_ids(self, running_replicas: List[ReplicaID]): + """Update cached set of running replica IDs for this deployment.""" + self._running_replicas = running_replicas + + def is_within_bounds(self, num_replicas_running_at_target_version: int): + """Whether or not this deployment is within the autoscaling bounds. + + Returns: True if the number of running replicas for the current + deployment version is within the autoscaling bounds. False + otherwise. + """ + + return ( + self.apply_bounds(num_replicas_running_at_target_version) + == num_replicas_running_at_target_version + ) + + def apply_bounds(self, num_replicas: int) -> int: + """Clips a replica count with current autoscaling bounds. + + This takes into account target capacity. + """ + + return max( + self.get_num_replicas_lower_bound(), + min(self.get_num_replicas_upper_bound(), num_replicas), + ) + + def record_request_metrics_for_replica( + self, replica_id: ReplicaID, window_avg: Optional[float], send_timestamp: float + ) -> None: + """Records average number of ongoing requests at a replica.""" + + if window_avg is None: + return + + if ( + replica_id not in self._replica_requests + or send_timestamp > self._replica_requests[replica_id].timestamp + ): + self._replica_requests[replica_id] = ReplicaMetricReport( + running_requests=window_avg, + timestamp=send_timestamp, + ) + + def record_request_metrics_for_handle( + self, + *, + handle_id: str, + actor_id: Optional[str], + handle_source: DeploymentHandleSource, + queued_requests: float, + running_requests: Dict[ReplicaID, float], + send_timestamp: float, + ) -> None: + """Records average number of queued and running requests at a handle for this + deployment. + """ + + if ( + handle_id not in self._handle_requests + or send_timestamp > self._handle_requests[handle_id].timestamp + ): + self._handle_requests[handle_id] = HandleMetricReport( + actor_id=actor_id, + handle_source=handle_source, + queued_requests=queued_requests, + running_requests=running_requests, + timestamp=send_timestamp, + ) + + def drop_stale_handle_metrics(self, alive_serve_actor_ids: Set[str]) -> None: + """Drops handle metrics that are no longer valid. + + This includes handles that live on Serve Proxy or replica actors + that have died AND handles from which the controller hasn't + received an update for too long. + """ + + timeout_s = max( + 2 * self._config.metrics_interval_s, + RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S, + ) + for handle_id, handle_metric in list(self._handle_requests.items()): + # Drop metrics for handles that are on Serve proxy/replica + # actors that have died + if ( + handle_metric.is_serve_component_source + and handle_metric.actor_id is not None + and handle_metric.actor_id not in alive_serve_actor_ids + ): + del self._handle_requests[handle_id] + if handle_metric.total_requests > 0: + logger.debug( + f"Dropping metrics for handle '{handle_id}' because the Serve " + f"actor it was on ({handle_metric.actor_id}) is no longer " + f"alive. It had {handle_metric.total_requests} ongoing requests" + ) + # Drop metrics for handles that haven't sent an update in a while. + # This is expected behavior for handles that were on replicas or + # proxies that have been shut down. + elif time.time() - handle_metric.timestamp >= timeout_s: + del self._handle_requests[handle_id] + if handle_metric.total_requests > 0: + actor_id = handle_metric.actor_id + actor_info = f"on actor '{actor_id}' " if actor_id else "" + logger.info( + f"Dropping stale metrics for handle '{handle_id}' {actor_info}" + f"because no update was received for {timeout_s:.1f}s. " + f"Ongoing requests was: {handle_metric.total_requests}." + ) + + def get_decision_num_replicas( + self, curr_target_num_replicas: int, _skip_bound_check: bool = False + ) -> int: + """Decide the target number of replicas to autoscale to. + + The decision is based off of the number of requests received + for this deployment. After the decision number of replicas is + returned by the policy, it is then bounded by the bounds min + and max adjusted by the target capacity and returned. If + `_skip_bound_check` is True, then the bounds are not applied. + """ + + autoscaling_context: AutoscalingContext = AutoscalingContext( + deployment_id=self._deployment_id, + deployment_name=self._deployment_id.name, + app_name=self._deployment_id.app_name, + current_num_replicas=len(self._running_replicas), + target_num_replicas=curr_target_num_replicas, + running_replicas=self._running_replicas, + total_num_requests=self.get_total_num_requests(), + capacity_adjusted_min_replicas=self.get_num_replicas_lower_bound(), + capacity_adjusted_max_replicas=self.get_num_replicas_upper_bound(), + policy_state=self._policy_state.copy(), + current_time=time.time(), + config=self._config, + queued_requests=None, + requests_per_replica=None, + aggregated_metrics=None, + raw_metrics=None, + last_scale_up_time=None, + last_scale_down_time=None, + ) + + decision_num_replicas, self._policy_state = self._policy(autoscaling_context) + + if _skip_bound_check: + return decision_num_replicas + + return self.apply_bounds(decision_num_replicas) + + def get_total_num_requests(self) -> float: + """Get average total number of requests aggregated over the past + `look_back_period_s` number of seconds. + + If there are 0 running replicas, then returns the total number + of requests queued at handles + + This code assumes that the metrics are either emmited on handles + or on replicas, but not both. Its the responsibility of the writer + to ensure enclusivity of the metrics. + """ + + total_requests = 0 + + for id in self._running_replicas: + if id in self._replica_requests: + total_requests += self._replica_requests[id].running_requests + + metrics_collected_on_replicas = total_requests > 0 + for handle_metric in self._handle_requests.values(): + total_requests += handle_metric.queued_requests + + if not metrics_collected_on_replicas: + for id in self._running_replicas: + if id in handle_metric.running_requests: + total_requests += handle_metric.running_requests[id] + + return total_requests + + +class AutoscalingStateManager: + """Manages all things autoscaling related. + + Keeps track of request metrics for each deployment and decides on + the target number of replicas to autoscale to based on those metrics. + """ + + def __init__(self): + self._autoscaling_states: Dict[DeploymentID, AutoscalingState] = {} + + def register_deployment( + self, + deployment_id: DeploymentID, + info: DeploymentInfo, + curr_target_num_replicas: int, + ) -> int: + """Register autoscaling deployment info.""" + assert info.deployment_config.autoscaling_config + if deployment_id not in self._autoscaling_states: + self._autoscaling_states[deployment_id] = AutoscalingState(deployment_id) + return self._autoscaling_states[deployment_id].register( + info, curr_target_num_replicas + ) + + def deregister_deployment(self, deployment_id: DeploymentID): + """Remove deployment from tracking.""" + self._autoscaling_states.pop(deployment_id, None) + + def update_running_replica_ids( + self, deployment_id: DeploymentID, running_replicas: List[ReplicaID] + ): + self._autoscaling_states[deployment_id].update_running_replica_ids( + running_replicas + ) + + def on_replica_stopped(self, replica_id: ReplicaID): + deployment_id = replica_id.deployment_id + if deployment_id in self._autoscaling_states: + self._autoscaling_states[deployment_id].on_replica_stopped(replica_id) + + def get_metrics(self) -> Dict[DeploymentID, float]: + return { + deployment_id: self.get_total_num_requests(deployment_id) + for deployment_id in self._autoscaling_states + } + + def get_target_num_replicas( + self, deployment_id: DeploymentID, curr_target_num_replicas: int + ) -> int: + return self._autoscaling_states[deployment_id].get_decision_num_replicas( + curr_target_num_replicas=curr_target_num_replicas, + ) + + def get_total_num_requests(self, deployment_id: DeploymentID) -> float: + return self._autoscaling_states[deployment_id].get_total_num_requests() + + def is_within_bounds( + self, deployment_id: DeploymentID, num_replicas_running_at_target_version: int + ) -> bool: + return self._autoscaling_states[deployment_id].is_within_bounds( + num_replicas_running_at_target_version + ) + + def record_request_metrics_for_replica( + self, replica_id: ReplicaID, window_avg: Optional[float], send_timestamp: float + ) -> None: + deployment_id = replica_id.deployment_id + # Defensively guard against delayed replica metrics arriving + # after the deployment's been deleted + if deployment_id in self._autoscaling_states: + self._autoscaling_states[deployment_id].record_request_metrics_for_replica( + replica_id=replica_id, + window_avg=window_avg, + send_timestamp=send_timestamp, + ) + + def record_request_metrics_for_handle( + self, + *, + deployment_id: str, + handle_id: str, + actor_id: Optional[str], + handle_source: DeploymentHandleSource, + queued_requests: float, + running_requests: Dict[ReplicaID, float], + send_timestamp: float, + ) -> None: + """Update request metric for a specific handle.""" + + if deployment_id in self._autoscaling_states: + self._autoscaling_states[deployment_id].record_request_metrics_for_handle( + handle_id=handle_id, + actor_id=actor_id, + handle_source=handle_source, + queued_requests=queued_requests, + running_requests=running_requests, + send_timestamp=send_timestamp, + ) + + def drop_stale_handle_metrics(self, alive_serve_actor_ids: Set[str]) -> None: + """Drops handle metrics that are no longer valid. + + This includes handles that live on Serve Proxy or replica actors + that have died AND handles from which the controller hasn't + received an update for too long. + """ + + for autoscaling_state in self._autoscaling_states.values(): + autoscaling_state.drop_stale_handle_metrics(alive_serve_actor_ids) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..735e40b389cca938ff698f74a2b2b35eacfd5813 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b271bb004469922e6230ac585241df66ad0701d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_noop_latency.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_noop_latency.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..198714a9639c48e93921060e5ff43ce846c838a4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_noop_latency.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_throughput.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_throughput.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a0926f6395470d1b0f452bd5b4cdaaa0388a0bb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_throughput.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/http_noop_latency.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/http_noop_latency.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8c5ab59c12a6d6d61f1db7f31b8ea17454ea899 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/http_noop_latency.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/microbenchmark.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/microbenchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0801b34e25e8f9e9715ddcd1ab14742ac0ecc770 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/microbenchmark.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/proxy_benchmark.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/proxy_benchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89ed768e48a4605d503ca2145f18e6f9cfe20a42 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/__pycache__/proxy_benchmark.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/common.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/common.py new file mode 100644 index 0000000000000000000000000000000000000000..1c51801662f758cd902b272688880a25e0a1d272 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/common.py @@ -0,0 +1,313 @@ +import asyncio +import inspect +import logging +import random +import string +import time +from functools import partial +from typing import Any, Callable, Coroutine, List, Optional, Tuple + +import aiohttp +import aiohttp.client_exceptions +import grpc +import numpy as np +import pandas as pd +from starlette.responses import StreamingResponse +from tqdm import tqdm + +from ray import serve +from ray.serve.generated import serve_pb2, serve_pb2_grpc +from ray.serve.handle import DeploymentHandle + + +async def run_latency_benchmark( + f: Callable, num_requests: int, *, num_warmup_requests: int = 100 +) -> pd.Series: + if inspect.iscoroutinefunction(f): + to_call = f + else: + + async def to_call(): + f() + + latencies = [] + for i in tqdm(range(num_requests + num_warmup_requests)): + start = time.perf_counter() + await to_call() + end = time.perf_counter() + + # Don't include warm-up requests. + if i >= num_warmup_requests: + latencies.append(1000 * (end - start)) + + return pd.Series(latencies) + + +async def run_throughput_benchmark( + fn: Callable[[], List[float]], + multiplier: int = 1, + num_trials: int = 10, + trial_runtime: float = 1, +) -> Tuple[float, float, pd.Series]: + """Benchmarks throughput of a function. + + Args: + fn: The function to benchmark. If this returns anything, it must + return a list of latencies. + multiplier: The number of requests or tokens (or whatever unit + is appropriate for this throughput benchmark) that is + completed in one call to `fn`. + num_trials: The number of trials to run. + trial_runtime: How long each trial should run for. During the + duration of one trial, `fn` will be repeatedly called. + + Returns (mean, stddev, latencies). + """ + # Warmup + start = time.time() + while time.time() - start < 0.1: + await fn() + + # Benchmark + stats = [] + latencies = [] + for _ in tqdm(range(num_trials)): + start = time.perf_counter() + count = 0 + while time.perf_counter() - start < trial_runtime: + res = await fn() + if res: + latencies.extend(res) + + count += 1 + end = time.perf_counter() + stats.append(multiplier * count / (end - start)) + + return round(np.mean(stats), 2), round(np.std(stats), 2), pd.Series(latencies) + + +async def do_single_http_batch( + *, + batch_size: int = 100, + url: str = "http://localhost:8000", + stream: bool = False, +) -> List[float]: + """Sends a batch of http requests and returns e2e latencies.""" + + # By default, aiohttp limits the number of client connections to 100. + # We need to use TCPConnector to configure the limit if batch size + # is greater than 100. + connector = aiohttp.TCPConnector(limit=batch_size) + async with aiohttp.ClientSession( + connector=connector, raise_for_status=True + ) as session: + + async def do_query(): + start = time.perf_counter() + try: + if stream: + async with session.get(url) as r: + async for chunk, _ in r.content.iter_chunks(): + pass + else: + await session.get(url) + except aiohttp.client_exceptions.ClientConnectionError: + pass + + end = time.perf_counter() + return 1000 * (end - start) + + return await asyncio.gather(*[do_query() for _ in range(batch_size)]) + + +async def do_single_grpc_batch( + *, batch_size: int = 100, target: str = "localhost:9000" +): + channel = grpc.aio.insecure_channel(target) + stub = serve_pb2_grpc.RayServeBenchmarkServiceStub(channel) + payload = serve_pb2.StringData(data="") + + async def do_query(): + start = time.perf_counter() + + await stub.grpc_call(payload) + + end = time.perf_counter() + return 1000 * (end - start) + + return await asyncio.gather(*[do_query() for _ in range(batch_size)]) + + +async def collect_profile_events(coro: Coroutine): + """Collects profiling events using Viztracer""" + + from viztracer import VizTracer + + tracer = VizTracer() + tracer.start() + + await coro + + tracer.stop() + tracer.save() + + +def generate_payload(size: int = 100, chars=string.ascii_uppercase + string.digits): + return "".join(random.choice(chars) for _ in range(size)) + + +class Blackhole: + def sink(self, o): + pass + + +@serve.deployment +class Noop: + def __init__(self): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + def __call__(self, *args, **kwargs): + return b"" + + +@serve.deployment +class ModelComp: + def __init__(self, child): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._child = child + + async def __call__(self, *args, **kwargs): + return await self._child.remote() + + +@serve.deployment +class GrpcDeployment: + def __init__(self): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + async def grpc_call(self, user_message): + return serve_pb2.ModelOutput(output=9) + + async def call_with_string(self, user_message): + return serve_pb2.ModelOutput(output=9) + + +@serve.deployment +class GrpcModelComp: + def __init__(self, child): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._child = child + + async def grpc_call(self, user_message): + await self._child.remote() + return serve_pb2.ModelOutput(output=9) + + async def call_with_string(self, user_message): + await self._child.remote() + return serve_pb2.ModelOutput(output=9) + + +@serve.deployment +class Streamer: + def __init__(self, tokens_per_request: int, inter_token_delay_ms: int = 10): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._tokens_per_request = tokens_per_request + self._inter_token_delay_s = inter_token_delay_ms / 1000 + + async def stream(self): + for _ in range(self._tokens_per_request): + await asyncio.sleep(self._inter_token_delay_s) + yield b"hi" + + async def __call__(self): + return StreamingResponse(self.stream()) + + +@serve.deployment +class IntermediateRouter: + def __init__(self, handle: DeploymentHandle): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._handle = handle.options(stream=True) + + async def stream(self): + async for token in self._handle.stream.remote(): + yield token + + def __call__(self): + return StreamingResponse(self.stream()) + + +@serve.deployment +class Benchmarker: + def __init__( + self, + handle: DeploymentHandle, + stream: bool = False, + ): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._handle = handle.options(stream=stream) + self._stream = stream + + async def do_single_request(self, payload: Any = None) -> float: + """Completes a single unary request. Returns e2e latency in ms.""" + start = time.perf_counter() + + if payload is None: + await self._handle.remote() + else: + await self._handle.remote(payload) + + end = time.perf_counter() + return 1000 * (end - start) + + async def _do_single_stream(self) -> float: + """Consumes a single streaming request. Returns e2e latency in ms.""" + start = time.perf_counter() + + async for r in self._handle.stream.remote(): + pass + + end = time.perf_counter() + return 1000 * (end - start) + + async def _do_single_batch(self, batch_size: int) -> List[float]: + if self._stream: + return await asyncio.gather( + *[self._do_single_stream() for _ in range(batch_size)] + ) + else: + return await asyncio.gather( + *[self.do_single_request() for _ in range(batch_size)] + ) + + async def run_latency_benchmark( + self, *, num_requests: int, payload: Any = None + ) -> pd.Series: + async def f(): + await self.do_single_request(payload) + + return await run_latency_benchmark(f, num_requests=num_requests) + + async def run_throughput_benchmark( + self, + *, + batch_size: int, + num_trials: int, + trial_runtime: float, + tokens_per_request: Optional[float] = None, + ) -> Tuple[float, float]: + if self._stream: + assert tokens_per_request + multiplier = tokens_per_request * batch_size + else: + multiplier = batch_size + + return await run_throughput_benchmark( + fn=partial( + self._do_single_batch, + batch_size=batch_size, + ), + multiplier=multiplier, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/handle_noop_latency.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/handle_noop_latency.py new file mode 100644 index 0000000000000000000000000000000000000000..313e467c6ff0e38f3da21c3dcb40e8b700f9cddf --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/handle_noop_latency.py @@ -0,0 +1,34 @@ +import time + +import click +import pandas as pd + +from ray import serve +from ray.serve._private.benchmarks.common import Benchmarker, Noop +from ray.serve.handle import DeploymentHandle + + +@click.command(help="Benchmark no-op DeploymentHandle latency.") +@click.option("--num-replicas", type=int, default=1) +@click.option("--num-requests", type=int, default=100) +def main(num_replicas: int, num_requests: int): + h: DeploymentHandle = serve.run( + Benchmarker.bind(Noop.options(num_replicas=num_replicas).bind()) + ) + + latencies: pd.Series = h.run_latency_benchmark.remote( + num_requests, + ).result() + + # Let the logs flush to avoid interwoven output. + time.sleep(1) + + print( + "Latency (ms) for noop DeploymentHandle requests " + f"(num_replicas={num_replicas},num_requests={num_requests}):" + ) + print(latencies.describe(percentiles=[0.5, 0.9, 0.95, 0.99])) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/handle_throughput.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/handle_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..08aa3c215224745cae5bdf7432798dae933b182e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/handle_throughput.py @@ -0,0 +1,62 @@ +import click + +from ray import serve +from ray.serve._private.benchmarks.common import Benchmarker, Hello +from ray.serve.handle import DeploymentHandle + + +@click.command(help="Benchmark deployment handle throughput.") +@click.option( + "--batch-size", + type=int, + default=100, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=1, + help="Duration to run each trial of the benchmark for (seconds).", +) +def main( + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, +): + app = Benchmarker.bind( + Hello.options( + num_replicas=num_replicas, ray_actor_options={"num_cpus": 0} + ).bind(), + ) + h: DeploymentHandle = serve.run(app) + + mean, stddev = h.run_throughput_benchmark.remote( + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ).result() + + print( + "DeploymentHandle throughput {}: {} +- {} requests/s".format( + f"(num_replicas={num_replicas}, batch_size={batch_size})", + mean, + stddev, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/http_noop_latency.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/http_noop_latency.py new file mode 100644 index 0000000000000000000000000000000000000000..ab85f5f882da6ace9d771eb2185154fedd90ffd0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/http_noop_latency.py @@ -0,0 +1,32 @@ +import asyncio + +import click +import pandas as pd +import requests + +from ray import serve +from ray.serve._private.benchmarks.common import Noop, run_latency_benchmark + + +@click.command(help="Benchmark no-op HTTP latency.") +@click.option("--num-replicas", type=int, default=1) +@click.option("--num-requests", type=int, default=100) +def main(num_replicas: int, num_requests: int): + serve.run(Noop.options(num_replicas=num_replicas).bind()) + + latencies: pd.Series = asyncio.new_event_loop().run_until_complete( + run_latency_benchmark( + lambda: requests.get("http://localhost:8000"), + num_requests=num_requests, + ) + ) + + print( + "Latency (ms) for noop HTTP requests " + f"(num_replicas={num_replicas},num_requests={num_requests}):" + ) + print(latencies.describe(percentiles=[0.5, 0.9, 0.95, 0.99])) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/microbenchmark.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/microbenchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..176298d0f26dd979bc93366e24605a73bd3c85c5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/microbenchmark.py @@ -0,0 +1,182 @@ +# Runs several scenarios with varying max batch size, max concurrent queries, +# number of replicas, and with intermediate serve handles (to simulate ensemble +# models) either on or off. + +import asyncio +import logging +from pprint import pprint +from typing import Dict, Union + +import aiohttp +from starlette.requests import Request + +import ray +from ray import serve +from ray.serve._private.benchmarks.common import run_throughput_benchmark +from ray.serve.handle import DeploymentHandle + +NUM_CLIENTS = 8 +CALLS_PER_BATCH = 100 + + +async def fetch(session, data): + async with session.get("http://localhost:8000/", data=data) as response: + response = await response.text() + assert response == "ok", response + + +@ray.remote +class Client: + def ready(self): + return "ok" + + async def do_queries(self, num, data): + async with aiohttp.ClientSession() as session: + for _ in range(num): + await fetch(session, data) + + +def build_app( + intermediate_handles: bool, + num_replicas: int, + max_batch_size: int, + max_ongoing_requests: int, +): + @serve.deployment(max_ongoing_requests=1000) + class Upstream: + def __init__(self, handle: DeploymentHandle): + self._handle = handle + + # Turn off access log. + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + async def __call__(self, req: Request): + return await self._handle.remote(await req.body()) + + @serve.deployment( + num_replicas=num_replicas, + max_ongoing_requests=max_ongoing_requests, + ) + class Downstream: + def __init__(self): + # Turn off access log. + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + @serve.batch(max_batch_size=max_batch_size) + async def batch(self, reqs): + return [b"ok"] * len(reqs) + + async def __call__(self, req: Union[bytes, Request]): + if max_batch_size > 1: + return await self.batch(req) + else: + return b"ok" + + if intermediate_handles: + return Upstream.bind(Downstream.bind()) + else: + return Downstream.bind() + + +async def trial( + intermediate_handles: bool, + num_replicas: int, + max_batch_size: int, + max_ongoing_requests: int, + data_size: str, +) -> Dict[str, float]: + results = {} + + trial_key_base = ( + f"replica:{num_replicas}/batch_size:{max_batch_size}/" + f"concurrent_queries:{max_ongoing_requests}/" + f"data_size:{data_size}/intermediate_handle:{intermediate_handles}" + ) + + print( + f"intermediate_handles={intermediate_handles}," + f"num_replicas={num_replicas}," + f"max_batch_size={max_batch_size}," + f"max_ongoing_requests={max_ongoing_requests}," + f"data_size={data_size}" + ) + + app = build_app( + intermediate_handles, num_replicas, max_batch_size, max_ongoing_requests + ) + serve.run(app) + + if data_size == "small": + data = None + elif data_size == "large": + data = b"a" * 1024 * 1024 + else: + raise ValueError("data_size should be 'small' or 'large'.") + + async with aiohttp.ClientSession() as session: + + async def single_client(): + for _ in range(CALLS_PER_BATCH): + await fetch(session, data) + + single_client_avg_tps, single_client_std_tps = await run_throughput_benchmark( + single_client, + multiplier=CALLS_PER_BATCH, + ) + print( + "\t{} {} +- {} requests/s".format( + "single client {} data".format(data_size), + single_client_avg_tps, + single_client_std_tps, + ) + ) + key = f"num_client:1/{trial_key_base}" + results[key] = single_client_avg_tps + + clients = [Client.remote() for _ in range(NUM_CLIENTS)] + ray.get([client.ready.remote() for client in clients]) + + async def many_clients(): + ray.get([a.do_queries.remote(CALLS_PER_BATCH, data) for a in clients]) + + multi_client_avg_tps, _ = await run_throughput_benchmark( + many_clients, + multiplier=CALLS_PER_BATCH * len(clients), + ) + + results[f"num_client:{len(clients)}/{trial_key_base}"] = multi_client_avg_tps + return results + + +async def main(): + results = {} + for intermediate_handles in [False, True]: + for num_replicas in [1, 8]: + for max_batch_size, max_ongoing_requests in [ + (1, 1), + (1, 10000), + (10000, 10000), + ]: + # TODO(edoakes): large data causes broken pipe errors. + for data_size in ["small"]: + results.update( + await trial( + intermediate_handles, + num_replicas, + max_batch_size, + max_ongoing_requests, + data_size, + ) + ) + + print("Results from all conditions:") + pprint(results) + return results + + +if __name__ == "__main__": + ray.init() + serve.start() + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + loop.run_until_complete(main()) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/proxy_benchmark.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/proxy_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3eca322f29c1c030637195f89308ea1a3e1238 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/proxy_benchmark.py @@ -0,0 +1,294 @@ +# Runs some request ping to compare HTTP and gRPC performances in TPS and latency. +# Note: this takes around 1 hour to run. + +import asyncio +import json +import logging +import time +from random import random +from typing import Callable, Dict + +import aiohttp +import numpy as np +import pandas as pd +from grpc import aio +from starlette.requests import Request + +import ray +from ray import serve +from ray.serve._private.common import RequestProtocol +from ray.serve.config import gRPCOptions +from ray.serve.generated import serve_pb2, serve_pb2_grpc +from ray.serve.handle import DeploymentHandle + +CALLS_PER_BATCH = 100 +DELTA = 10**-7 + + +async def get_query_tps(name: str, fn: Callable, multiplier: int = CALLS_PER_BATCH): + """Get query TPS. + + Run the function for 0.5 seconds 10 times to calculate how many requests can + be completed. And use those stats to calculate the mean and std of TPS. + """ + # warmup + start = time.time() + while time.time() - start < 0.1: + await fn() + # real run + stats = [] + for _ in range(10): + count = 0 + start = time.time() + while time.time() - start < 0.5: + await fn() + count += 1 + end = time.time() + stats.append(multiplier * count / (end - start)) + tps_mean = round(np.mean(stats), 2) + tps_std = round(np.std(stats), 2) + print(f"\t{name} {tps_mean} +- {tps_std} requests/s") + + return tps_mean, tps_std + + +async def get_query_latencies(name: str, fn: Callable): + """Get query latencies. + + Take all the latencies from the function and calculate the mean and std. + """ + many_client_results = np.asarray(await fn()) + many_client_results.flatten() + latency_ms_mean = round(np.mean(many_client_results) * 1000, 2) + latency_ms_std = round(np.std(many_client_results) * 1000, 2) + print(f"\t{name} {latency_ms_mean} +- {latency_ms_std} ms") + + return latency_ms_mean, latency_ms_std + + +async def fetch_http(session, data): + data_json = {"nums": data} + response = await session.get("http://localhost:8000/", json=data_json) + response_text = await response.read() + float(response_text.decode()) + + +async def fetch_grpc(stub, data): + result = await stub.grpc_call(serve_pb2.RawData(nums=data)) + _ = result.output + + +@ray.remote +class HTTPClient: + def ready(self): + return "ok" + + async def do_queries(self, num, data): + async with aiohttp.ClientSession() as session: + for _ in range(num): + await fetch_http(session, data) + + async def time_queries(self, num, data): + stats = [] + async with aiohttp.ClientSession() as session: + for _ in range(num): + start = time.time() + await fetch_http(session, data) + end = time.time() + stats.append(end - start) + + return stats + + +@ray.remote +class gRPCClient: + def __init__(self): + channel = aio.insecure_channel("localhost:9000") + self.stub = serve_pb2_grpc.RayServeBenchmarkServiceStub(channel) + + def ready(self): + return "ok" + + async def do_queries(self, num, data): + for _ in range(num): + await fetch_grpc(self.stub, data) + + async def time_queries(self, num, data): + stats = [] + for _ in range(num): + start = time.time() + await fetch_grpc(self.stub, data) + end = time.time() + stats.append(end - start) + return stats + + +def build_app( + num_replicas: int, + max_ongoing_requests: int, + data_size: int, +): + @serve.deployment(max_ongoing_requests=1000) + class DataPreprocessing: + def __init__(self, handle: DeploymentHandle): + self._handle = handle + + # Turn off access log. + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + def normalize(self, raw: np.ndarray) -> np.ndarray: + return (raw - np.min(raw)) / (np.max(raw) - np.min(raw) + DELTA) + + async def __call__(self, req: Request): + """HTTP entrypoint. + + It parses the request, normalize the data, and send to model for inference. + """ + body = json.loads(await req.body()) + raw = np.asarray(body["nums"]) + processed = self.normalize(raw) + return await self._handle.remote(processed) + + async def grpc_call(self, raq_data): + """gRPC entrypoint. + + It parses the request, normalize the data, and send to model for inference. + """ + raw = np.asarray(raq_data.nums) + processed = self.normalize(raw) + output = await self._handle.remote(processed) + return serve_pb2.ModelOutput(output=output) + + async def call_with_string(self, raq_data): + """gRPC entrypoint.""" + return serve_pb2.ModelOutput(output=0) + + @serve.deployment( + num_replicas=num_replicas, + max_ongoing_requests=max_ongoing_requests, + ) + class ModelInference: + def __init__(self): + # Turn off access log. + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._model = np.random.randn(data_size, data_size) + + async def __call__(self, processed: np.ndarray) -> float: + # Run a dot product with a random matrix to simulate a model inference. + model_output = np.dot(processed, self._model) + return sum(model_output) + + return DataPreprocessing.bind(ModelInference.bind()) + + +async def trial( + num_replicas: int, + max_ongoing_requests: int, + data_size: int, + num_clients: int, + proxy: RequestProtocol, +) -> Dict[str, float]: + # Generate input data as array of random floats. + data = [random() for _ in range(data_size)] + + # Build and deploy the app. + app = build_app( + num_replicas=num_replicas, + max_ongoing_requests=max_ongoing_requests, + data_size=data_size, + ) + serve.run(app) + + # Start clients. + if proxy == RequestProtocol.GRPC: + clients = [gRPCClient.remote() for _ in range(num_clients)] + elif proxy == RequestProtocol.HTTP: + clients = [HTTPClient.remote() for _ in range(num_clients)] + ray.get([client.ready.remote() for client in clients]) + + async def client_time_queries(): + return ray.get([a.time_queries.remote(CALLS_PER_BATCH, data) for a in clients]) + + async def client_do_queries(): + ray.get([a.do_queries.remote(CALLS_PER_BATCH, data) for a in clients]) + + trial_key_base = ( + f"proxy:{proxy}/" + f"num_client:{num_clients}/" + f"replica:{num_replicas}/" + f"concurrent_queries:{max_ongoing_requests}/" + f"data_size:{data_size}" + ) + tps_mean, tps_sdt = await get_query_tps( + trial_key_base, + client_do_queries, + ) + latency_ms_mean, latency_ms_std = await get_query_latencies( + trial_key_base, + client_time_queries, + ) + + results = { + "proxy": proxy.value, + "num_client": num_clients, + "replica": num_replicas, + "concurrent_queries": max_ongoing_requests, + "data_size": data_size, + "tps_mean": tps_mean, + "tps_sdt": tps_sdt, + "latency_ms_mean": latency_ms_mean, + "latency_ms_std": latency_ms_std, + } + + return results + + +async def main(): + start_time = time.time() + results = [] + for num_replicas in [1, 8]: + for max_ongoing_requests in [1, 10_000]: + for data_size in [1, 100, 10_000]: + for num_clients in [1, 8]: + for proxy in [RequestProtocol.GRPC, RequestProtocol.HTTP]: + results.append( + await trial( + num_replicas=num_replicas, + max_ongoing_requests=max_ongoing_requests, + data_size=data_size, + num_clients=num_clients, + proxy=proxy, + ) + ) + + print(f"Total time: {time.time() - start_time}s") + print("results", results) + + df = pd.DataFrame.from_dict(results) + df = df.sort_values( + by=["proxy", "num_client", "replica", "concurrent_queries", "data_size"] + ) + print("Results from all conditions:") + # Print the results in with tab separated so we can copy into google sheets. + for i in range(len(df.index)): + row = list(df.iloc[i]) + print("\t".join(map(str, row))) + + +if __name__ == "__main__": + ray.init() + + grpc_port = 9000 + grpc_servicer_functions = [ + "ray.serve.generated.serve_pb2_grpc." + "add_RayServeBenchmarkServiceServicer_to_server", + ] + serve.start( + grpc_options=gRPCOptions( + port=grpc_port, + grpc_servicer_functions=grpc_servicer_functions, + ) + ) + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + loop.run_until_complete(main()) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4edd052d59c2c432f1ac3729f05ba8b560e69e3e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..020006b903f3aa9aefb8128386280a32461f3643 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/serialization_benchmark.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/serialization_benchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2603bac2df4cd1ed12318d2317ef62287542b6a0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/serialization_benchmark.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/common.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/common.py new file mode 100644 index 0000000000000000000000000000000000000000..41d535ceaf365044226661c9244312f14d2b260a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/common.py @@ -0,0 +1,29 @@ +from dataclasses import dataclass +from typing import List, Optional + +from pydantic import BaseModel + +# +# NOTE: PLEASE READ CAREFULLY BEFORE CHANGING +# +# Payloads in this module are purposefully extracted from benchmark file to force +# Ray's cloudpickle behavior when it does NOT serialize the class definition itself +# along with its payload (instead relying on it being imported) +# + + +class PayloadPydantic(BaseModel): + text: Optional[str] = None + floats: Optional[List[float]] = None + ints: Optional[List[int]] = None + ts: Optional[float] = None + reason: Optional[str] = None + + +@dataclass +class PayloadDataclass: + text: Optional[str] = None + floats: Optional[List[float]] = None + ints: Optional[List[int]] = None + ts: Optional[float] = None + reason: Optional[str] = None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/serialization_benchmark.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/serialization_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..12e600758c2213b9c000c2cdc041433f2dff3323 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/serialization/serialization_benchmark.py @@ -0,0 +1,163 @@ +import asyncio +import enum +import pickle +import time +from typing import Any, Callable + +import click +import msgpack + +from ray._private.serialization import SerializationContext +from ray.cloudpickle import cloudpickle_fast +from ray.serve._private.benchmarks.common import ( + collect_profile_events, + run_latency_benchmark, +) +from ray.serve._private.benchmarks.serialization.common import ( + PayloadDataclass, + PayloadPydantic, +) + + +class PayloadType(enum.Enum): + PYDANTIC = "pydantic" + DATACLASS = "dataclass" + + +class SerializerType(enum.Enum): + RAY = "ray" + PICKLE = "pickle" + CLOUDPICKLE = "cloudpickle" + MSGPACK = "msgpack" + + +_PERCENTILES = [0.5, 0.99] + + +sc = SerializationContext(None) + + +def _create_model(cls): + return cls( + text="Test output", + floats=[float(f) for f in range(1, 100)], + ints=list(range(1, 100)), + ts=time.time(), + reason="Success!", + ) + + +def _blackhole(o): + """Placeholder to be used in the benchmark to make sure runtime + doesn't optimize out unused results""" + pass + + +async def run_serializer_benchmark( + model, serializer: Callable[[Any], bytes], iterations: int +): + def _serde_loop(): + bs = serializer(model) + _blackhole(bs) + + pd = await run_latency_benchmark(_serde_loop, iterations) + + print("Latencies (ms):\n", pd.describe(percentiles=_PERCENTILES)) + + +@click.command(help="Benchmark serialization latency") +@click.option( + "--trials", + type=int, + default=1000, + help="Total number of trials to run in a single benchmark run", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Controls how many objects are contained in a serialized batch", +) +@click.option( + "--payload-type", + type=PayloadType, + help="Target type of the payload to be benchmarked (supported: pydantic, " + "dataclass)", +) +@click.option( + "--serializer", + type=SerializerType, + help="Target type of the serializer to be benchmarked (supported: ray, pickle, " + "cloudpickle, msgpack)", +) +@click.option( + "--profile-events", + type=bool, + default=False, +) +def main( + trials: int, + batch_size: int, + payload_type: PayloadType, + serializer: SerializerType, + profile_events: bool, +): + if serializer == SerializerType.RAY: + + def _serialize(obj): + so = sc.serialize(obj) + bs = so.to_bytes() + return bs + + elif serializer == SerializerType.CLOUDPICKLE: + + def _serialize(obj): + bs = cloudpickle_fast.dumps(obj) + return bs + + elif serializer == SerializerType.PICKLE: + + def _serialize(obj): + bs = pickle.dumps(obj) + return bs + + elif serializer == SerializerType.MSGPACK: + + def _dumps(obj): + bs = msgpack.dumps(obj.__dict__) + # print(f"Bytes ({len(bs)}): ", bs) + return bs + + def _loads(bs): + dict = msgpack.loads(bs) + return PayloadPydantic(**dict) + + sc._register_cloudpickle_serializer(PayloadPydantic, _dumps, _loads) + + def _serialize(obj): + so = sc.serialize(obj) + bs = so.to_bytes() + return bs + + else: + raise NotImplementedError(serializer) + + if payload_type == PayloadType.PYDANTIC: + model = _create_model(PayloadPydantic) + elif payload_type == PayloadType.DATACLASS: + model = _create_model(PayloadDataclass) + else: + raise NotImplementedError(f"Not supported ({payload_type})") + + payload = [model.copy(deep=True) for _ in range(batch_size)] + + routine = run_serializer_benchmark(payload, _serialize, trials) + + if profile_events: + routine = collect_profile_events(routine) + + asyncio.run(routine) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9285bbbde540ce6226b1db0735978387b52df2dc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a861d56fae6724d03397285e8b3933f55656b5e7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_core_throughput.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_core_throughput.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9248bf566b36d88f4604b03bcc94cc5282e175a4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_core_throughput.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_grpc_throughput.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_grpc_throughput.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7191da089ef93970a43001b5395c4b7ca2cf743b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_grpc_throughput.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_handle_throughput.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_handle_throughput.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..328a5d7df7f4e2d59396ab2a6fe60384100d29d5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_handle_throughput.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_http_throughput.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_http_throughput.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12aea535f9839b1d55af1727bbfe0d0ffedbd4c8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_http_throughput.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d9b77bc853df11903fa8b74c5770bddd523fd4d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/grpc_server.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/grpc_server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd88a783c523a76d7df7a3d428aa179d3e87e411 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/grpc_server.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/test_server_pb2_grpc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/test_server_pb2_grpc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba463ff998d13e4b5b0c03a440c8a60b9bce9aae Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/test_server_pb2_grpc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/grpc_server.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/grpc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..40f183216c79c545e623b1e3158c3de9138c439a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/grpc_server.py @@ -0,0 +1,60 @@ +import grpc + +from ray.serve._private.benchmarks.streaming._grpc import ( + test_server_pb2, + test_server_pb2_grpc, +) + + +async def _async_list(async_iterator): + items = [] + async for item in async_iterator: + items.append(item) + + return items + + +class TestGRPCServer(test_server_pb2_grpc.GRPCTestServerServicer): + def __init__(self, tokens_per_request): + self._tokens_per_request = tokens_per_request + + async def Unary(self, request, context): + if request.request_data == "error": + await context.abort( + code=grpc.StatusCode.INTERNAL, + details="unary rpc error", + ) + + return test_server_pb2.Response(response_data="OK") + + async def ClientStreaming(self, request_iterator, context): + data = await _async_list(request_iterator) + + if data and data[0].request_data == "error": + await context.abort( + code=grpc.StatusCode.INTERNAL, + details="client streaming rpc error", + ) + + return test_server_pb2.Response(response_data="OK") + + async def ServerStreaming(self, request, context): + if request.request_data == "error": + await context.abort( + code=grpc.StatusCode.INTERNAL, + details="OK", + ) + + for i in range(self._tokens_per_request): + yield test_server_pb2.Response(response_data="OK") + + async def BidiStreaming(self, request_iterator, context): + data = await _async_list(request_iterator) + if data and data[0].request_data == "error": + await context.abort( + code=grpc.StatusCode.INTERNAL, + details="bidi-streaming rpc error", + ) + + for i in range(self._tokens_per_request): + yield test_server_pb2.Response(response_data="OK") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/test_server_pb2_grpc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/test_server_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..96d5ebfbfd531cdb730b3f5e77b38c8982a09d57 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/test_server_pb2_grpc.py @@ -0,0 +1,216 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +from ray.serve._private.benchmarks.streaming._grpc import ( + test_server_pb2 as backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2, +) + + +class GRPCTestServerStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Unary = channel.unary_unary( + "/GRPCTestServer/Unary", + request_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + response_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + ) + self.ClientStreaming = channel.stream_unary( + "/GRPCTestServer/ClientStreaming", + request_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + response_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + ) + self.ServerStreaming = channel.unary_stream( + "/GRPCTestServer/ServerStreaming", + request_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + response_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + ) + self.BidiStreaming = channel.stream_stream( + "/GRPCTestServer/BidiStreaming", + request_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + response_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + ) + + +class GRPCTestServerServicer(object): + """Missing associated documentation comment in .proto file.""" + + def Unary(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def ClientStreaming(self, request_iterator, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def ServerStreaming(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def BidiStreaming(self, request_iterator, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + +def add_GRPCTestServerServicer_to_server(servicer, server): + rpc_method_handlers = { + "Unary": grpc.unary_unary_rpc_method_handler( + servicer.Unary, + request_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.FromString, + response_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.SerializeToString, + ), + "ClientStreaming": grpc.stream_unary_rpc_method_handler( + servicer.ClientStreaming, + request_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.FromString, + response_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.SerializeToString, + ), + "ServerStreaming": grpc.unary_stream_rpc_method_handler( + servicer.ServerStreaming, + request_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.FromString, + response_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.SerializeToString, + ), + "BidiStreaming": grpc.stream_stream_rpc_method_handler( + servicer.BidiStreaming, + request_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.FromString, + response_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + "GRPCTestServer", rpc_method_handlers + ) + server.add_generic_rpc_handlers((generic_handler,)) + + +# This class is part of an EXPERIMENTAL API. +class GRPCTestServer(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def Unary( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_unary( + request, + target, + "/GRPCTestServer/Unary", + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def ClientStreaming( + request_iterator, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.stream_unary( + request_iterator, + target, + "/GRPCTestServer/ClientStreaming", + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def ServerStreaming( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_stream( + request, + target, + "/GRPCTestServer/ServerStreaming", + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def BidiStreaming( + request_iterator, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.stream_stream( + request_iterator, + target, + "/GRPCTestServer/BidiStreaming", + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/common.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/common.py new file mode 100644 index 0000000000000000000000000000000000000000..f5378565f0f089568c530b43167b770ed7db4315 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/common.py @@ -0,0 +1,123 @@ +import abc +import asyncio +import enum +import logging +import time +from typing import Tuple, Union + +import numpy as np + +from ray.actor import ActorHandle +from ray.runtime_env import RuntimeEnv +from ray.serve._private.benchmarks.common import Blackhole, run_throughput_benchmark +from ray.serve._private.benchmarks.serialization.common import PayloadPydantic +from ray.serve.handle import DeploymentHandle + +GRPC_DEBUG_RUNTIME_ENV = RuntimeEnv( + env_vars={"GRPC_TRACE": "http", "GRPC_VERBOSITY": "debug"}, +) + + +class IOMode(enum.Enum): + SYNC = "SYNC" + ASYNC = "ASYNC" + + +class Endpoint: + def __init__(self, tokens_per_request: int): + self._tokens_per_request = tokens_per_request + # Switch off logging to minimize its impact + logging.getLogger("ray").setLevel(logging.WARNING) + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + def stream(self): + payload = PayloadPydantic( + text="Test output", + floats=[float(f) for f in range(1, 100)], + ints=list(range(1, 100)), + ts=time.time(), + reason="Success!", + ) + + for i in range(self._tokens_per_request): + yield payload + + async def aio_stream(self): + payload = PayloadPydantic( + text="Test output", + floats=[float(f) for f in range(1, 100)], + ints=list(range(1, 100)), + ts=time.time(), + reason="Success!", + ) + + for i in range(self._tokens_per_request): + yield payload + + +class Caller(Blackhole): + def __init__( + self, + downstream: Union[ActorHandle, DeploymentHandle], + *, + mode: IOMode, + tokens_per_request: int, + batch_size: int, + num_trials: int, + trial_runtime: float, + ): + self._h = downstream + self._mode = mode + self._tokens_per_request = tokens_per_request + self._batch_size = batch_size + self._num_trials = num_trials + self._trial_runtime = trial_runtime + self._durations = [] + + # Switch off logging to minimize its impact + logging.getLogger("ray").setLevel(logging.WARNING) + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + def _get_remote_method(self): + if self._mode == IOMode.SYNC: + return self._h.stream + elif self._mode == IOMode.ASYNC: + return self._h.aio_stream + else: + raise NotImplementedError(f"Streaming mode not supported ({self._mode})") + + @abc.abstractmethod + async def _consume_single_stream(self): + pass + + async def _do_single_batch(self): + durations = await asyncio.gather( + *[ + self._execute(self._consume_single_stream) + for _ in range(self._batch_size) + ] + ) + + self._durations.extend(durations) + + async def _execute(self, fn): + start = time.monotonic() + await fn() + dur_s = time.monotonic() - start + return dur_s * 1000 # ms + + async def run_benchmark(self) -> Tuple[float, float]: + coro = run_throughput_benchmark( + fn=self._do_single_batch, + multiplier=self._batch_size * self._tokens_per_request, + num_trials=self._num_trials, + trial_runtime=self._trial_runtime, + ) + # total_runtime = await collect_profile_events(coro) + total_runtime = await coro + + p50, p75, p99 = np.percentile(self._durations, [50, 75, 99]) + + print(f"Individual request quantiles:\n\tP50={p50}\n\tP75={p75}\n\tP99={p99}") + + return total_runtime diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_core_throughput.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_core_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..4447d9996caab67918c8760964e6d5e8ee9de0c1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_core_throughput.py @@ -0,0 +1,95 @@ +import click + +import ray +from ray.serve._private.benchmarks.streaming.common import Caller, Endpoint, IOMode + + +# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV) +@ray.remote +class EndpointActor(Endpoint): + pass + + +# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV) +@ray.remote +class CallerActor(Caller): + async def _consume_single_stream(self): + method = self._get_remote_method() + async for ref in method.options(num_returns="streaming").remote(): + r = ray.get(ref) + + # self.sink(str(r, 'utf-8')) + self.sink(r) + + +@click.command(help="Benchmark streaming deployment handle throughput.") +@click.option( + "--tokens-per-request", + type=int, + default=1000, + help="Number of tokens (per request) to stream from downstream deployment", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Number of requests to send to downstream deployment in each batch.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=5, + help="Duration to run each trial of the benchmark for (seconds).", +) +@click.option( + "--io-mode", + type=str, + default="async", + help="Controls mode of the streaming generation (either 'sync' or 'async')", +) +def main( + tokens_per_request: int, + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, + io_mode: str, +): + h = CallerActor.remote( + EndpointActor.remote( + tokens_per_request=tokens_per_request, + ), + mode=IOMode(io_mode.upper()), + tokens_per_request=tokens_per_request, + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + + mean, stddev = ray.get(h.run_benchmark.remote()) + print( + "Core Actors streaming throughput ({}) {}: {} +- {} tokens/s".format( + io_mode.upper(), + f"(num_replicas={num_replicas}, " + f"tokens_per_request={tokens_per_request}, " + f"batch_size={batch_size})", + mean, + stddev, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_grpc_throughput.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_grpc_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6e264437cd939ed6139d2a7f126c090a825f8f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_grpc_throughput.py @@ -0,0 +1,218 @@ +import asyncio +import logging +import time +from concurrent import futures +from tempfile import TemporaryDirectory + +import click +import grpc + +import ray +from ray.serve._private.benchmarks.streaming._grpc import ( + test_server_pb2, + test_server_pb2_grpc, +) +from ray.serve._private.benchmarks.streaming._grpc.grpc_server import TestGRPCServer +from ray.serve._private.benchmarks.streaming.common import Caller, IOMode + + +# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV) +@ray.remote +class EndpointActor: + async def __init__(self, tokens_per_request, socket_type, tempdir): + # Switch off logging to minimize its impact + logging.getLogger("ray").setLevel(logging.WARNING) + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + self.server = await self.start_server(tokens_per_request, socket_type, tempdir) + + print("gRPC server started!") + + @staticmethod + async def start_server(tokens_per_request, socket_type, tempdir): + server = grpc.aio.server(futures.ThreadPoolExecutor(max_workers=1)) + + addr, server_creds, _ = _gen_addr_creds(socket_type, tempdir) + + server.add_secure_port(addr, server_creds) + + await server.start() + + test_server_pb2_grpc.add_GRPCTestServerServicer_to_server( + TestGRPCServer(tokens_per_request), server + ) + + return server + + +# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV) +@ray.remote +class GrpcCallerActor(Caller): + def __init__( + self, + tempdir, + socket_type, + *, + mode: IOMode, + tokens_per_request: int, + batch_size: int, + num_trials: int, + trial_runtime: float, + ): + super().__init__( + self.create_downstream(socket_type, tempdir), + mode=mode, + tokens_per_request=tokens_per_request, + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + + @staticmethod + def create_downstream(socket_type, tempdir): + addr, _, channel_creds = _gen_addr_creds(socket_type, tempdir) + + channel = grpc.aio.secure_channel( + addr, credentials=channel_creds, interceptors=[] + ) + + return test_server_pb2_grpc.GRPCTestServerStub(channel) + + async def _consume_single_stream(self): + try: + async for r in self._h.ServerStreaming(test_server_pb2.Request()): + self.sink(r) + except Exception as e: + print(str(e)) + + +def _gen_addr_creds(socket_type, tempdir): + if socket_type == "uds": + addr = f"unix://{tempdir}/server.sock" + server_creds = grpc.local_server_credentials(grpc.LocalConnectionType.UDS) + channel_creds = grpc.local_channel_credentials(grpc.LocalConnectionType.UDS) + elif socket_type == "local_tcp": + addr = "127.0.0.1:5432" + server_creds = grpc.local_server_credentials(grpc.LocalConnectionType.LOCAL_TCP) + channel_creds = grpc.local_channel_credentials( + grpc.LocalConnectionType.LOCAL_TCP + ) + else: + raise NotImplementedError(f"Not supported socket type ({socket_type})") + + return addr, server_creds, channel_creds + + +async def run_grpc_benchmark( + batch_size, + io_mode, + socket_type, + num_replicas, + num_trials, + tokens_per_request, + trial_runtime, +): + with TemporaryDirectory() as tempdir: + _ = EndpointActor.remote( + tokens_per_request=tokens_per_request, + socket_type=socket_type, + tempdir=tempdir, + ) + + ca = GrpcCallerActor.remote( + tempdir, + socket_type, + mode=IOMode(io_mode.upper()), + tokens_per_request=tokens_per_request, + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + + # TODO make starting server a method (to make synchronization explicit) + time.sleep(5) + + mean, stddev = await ca.run_benchmark.remote() + + print( + "gRPC streaming throughput ({}) {}: {} +- {} tokens/s".format( + io_mode.upper(), + f"(num_replicas={num_replicas}, " + f"tokens_per_request={tokens_per_request}, " + f"batch_size={batch_size})", + mean, + stddev, + ) + ) + + +@click.command(help="Benchmark streaming deployment handle throughput.") +@click.option( + "--tokens-per-request", + type=int, + default=1000, + help="Number of tokens (per request) to stream from downstream deployment", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Number of requests to send to downstream deployment in each batch.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=5, + help="Duration to run each trial of the benchmark for (seconds).", +) +@click.option( + "--io-mode", + type=str, + default="async", + help="Controls mode of the streaming generation (either 'sync' or 'async')", +) +@click.option( + "--socket-type", + type=str, + default="local_tcp", + help="Controls type of socket used as underlying transport (either 'uds' or " + "'local_tcp')", +) +def main( + tokens_per_request: int, + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, + io_mode: str, + socket_type: grpc.LocalConnectionType, +): + """Reference benchmark for vanilla Python (w/ C-based core) gRPC implementation""" + + asyncio.run( + run_grpc_benchmark( + batch_size, + io_mode, + socket_type, + num_replicas, + num_trials, + tokens_per_request, + trial_runtime, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_handle_throughput.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_handle_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..77ed697053b3bdb5437aa28ee7aff24bf5a1e317 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_handle_throughput.py @@ -0,0 +1,94 @@ +import click + +from ray import serve +from ray.serve._private.benchmarks.streaming.common import Caller, Endpoint, IOMode + + +@serve.deployment(ray_actor_options={"num_cpus": 0}) +class EndpointDeployment(Endpoint): + pass + + +@serve.deployment +class CallerDeployment(Caller): + async def _consume_single_stream(self): + method = self._get_remote_method().options( + stream=True, + ) + + async for r in method.remote(): + # Blackhole the response + # self.sink(str(r, 'utf-8')) + self.sink(r) + + +@click.command(help="Benchmark streaming deployment handle throughput.") +@click.option( + "--tokens-per-request", + type=int, + default=1000, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=1, + help="Duration to run each trial of the benchmark for (seconds).", +) +@click.option( + "--io-mode", + type=str, + default="async", + help="Controls mode of the streaming generation (either 'sync' or 'async')", +) +def main( + tokens_per_request: int, + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, + io_mode: str, +): + app = CallerDeployment.bind( + EndpointDeployment.options(num_replicas=num_replicas).bind(tokens_per_request), + mode=IOMode(io_mode.upper()), + tokens_per_request=tokens_per_request, + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + h = serve.run(app) + + mean, stddev = h.run_benchmark.remote().result() + print( + "DeploymentHandle streaming throughput ({}) {}: {} +- {} tokens/s".format( + io_mode.upper(), + f"(num_replicas={num_replicas}, " + f"tokens_per_request={tokens_per_request}, " + f"batch_size={batch_size})", + mean, + stddev, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_http_throughput.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_http_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..b80b5e5b5dac41059362a1b13e762114efcd1717 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/benchmarks/streaming/streaming_http_throughput.py @@ -0,0 +1,140 @@ +import asyncio +import logging +from typing import Tuple + +import aiohttp +import click +from starlette.responses import StreamingResponse + +from ray import serve +from ray.serve._private.benchmarks.common import run_throughput_benchmark +from ray.serve.handle import DeploymentHandle + + +@serve.deployment(ray_actor_options={"num_cpus": 0}) +class Downstream: + def __init__(self, tokens_per_request: int): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + self._tokens_per_request = tokens_per_request + + async def stream(self): + for i in range(self._tokens_per_request): + yield "hi" + + def __call__(self, *args): + return StreamingResponse(self.stream()) + + +@serve.deployment(ray_actor_options={"num_cpus": 0}) +class Intermediate: + def __init__(self, downstream: DeploymentHandle): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + self._h = downstream.options(stream=True) + + async def stream(self): + async for token in self._h.stream.remote(): + yield token + + def __call__(self, *args): + return StreamingResponse(self.stream()) + + +async def _consume_single_stream(): + async with aiohttp.ClientSession(raise_for_status=True) as session: + async with session.get("http://localhost:8000") as r: + async for line in r.content: + pass + + +async def run_benchmark( + tokens_per_request: int, + batch_size: int, + num_trials: int, + trial_runtime: float, +) -> Tuple[float, float]: + async def _do_single_batch(): + await asyncio.gather(*[_consume_single_stream() for _ in range(batch_size)]) + + return await run_throughput_benchmark( + fn=_do_single_batch, + multiplier=batch_size * tokens_per_request, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + + +@click.command(help="Benchmark streaming HTTP throughput.") +@click.option( + "--tokens-per-request", + type=int, + default=1000, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=1, + help="Duration to run each trial of the benchmark for (seconds).", +) +@click.option( + "--use-intermediate-deployment", + is_flag=True, + default=False, + help="Whether to run an intermediate deployment proxying the requests.", +) +def main( + tokens_per_request: int, + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, + use_intermediate_deployment: bool, +): + app = Downstream.options(num_replicas=num_replicas).bind(tokens_per_request) + if use_intermediate_deployment: + app = Intermediate.bind(app) + + serve.run(app) + + mean, stddev = asyncio.new_event_loop().run_until_complete( + run_benchmark( + tokens_per_request, + batch_size, + num_trials, + trial_runtime, + ) + ) + print( + "HTTP streaming throughput {}: {} +- {} tokens/s".format( + f"(num_replicas={num_replicas}, " + f"tokens_per_request={tokens_per_request}, " + f"batch_size={batch_size}, " + f"use_intermediate_deployment={use_intermediate_deployment})", + mean, + stddev, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/build_app.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/build_app.py new file mode 100644 index 0000000000000000000000000000000000000000..b52cca21812b1330130d732cd70b8eaf7e7ca77a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/build_app.py @@ -0,0 +1,237 @@ +import logging +from copy import deepcopy +from dataclasses import dataclass +from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union + +from ray.dag.py_obj_scanner import _PyObjScanner +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve.deployment import Application, Deployment +from ray.serve.handle import DeploymentHandle +from ray.serve.schema import LoggingConfig + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +K = TypeVar("K") +V = TypeVar("V") + + +class IDDict(dict, Generic[K, V]): + """Dictionary that uses id() for keys instead of hash(). + + This is necessary because Application objects aren't hashable and we want each + instance to map to a unique key. + """ + + def __getitem__(self, key: K) -> V: + if not isinstance(key, int): + key = id(key) + return super().__getitem__(key) + + def __setitem__(self, key: K, value: V): + if not isinstance(key, int): + key = id(key) + return super().__setitem__(key, value) + + def __delitem__(self, key: K): + if not isinstance(key, int): + key = id(key) + return super().__delitem__(key) + + def __contains__(self, key: object): + if not isinstance(key, int): + key = id(key) + return super().__contains__(key) + + +@dataclass(frozen=True) +class BuiltApplication: + # Name of the application. + name: str + route_prefix: Optional[str] + logging_config: Optional[LoggingConfig] + # Name of the application's 'ingress' deployment + # (the one exposed over gRPC/HTTP/handle). + ingress_deployment_name: str + # List of unique deployments comprising the app. + deployments: List[Deployment] + # Dict[name, DeploymentHandle] mapping deployment names to the handles that replaced + # them in other deployments' init args/kwargs. + deployment_handles: Dict[str, DeploymentHandle] + + +def _make_deployment_handle_default( + deployment: Deployment, app_name: str +) -> DeploymentHandle: + return DeploymentHandle( + deployment.name, + app_name=app_name, + ) + + +def build_app( + app: Application, + *, + name: str, + route_prefix: Optional[str] = None, + logging_config: Optional[Union[Dict, LoggingConfig]] = None, + default_runtime_env: Optional[Dict[str, Any]] = None, + make_deployment_handle: Optional[ + Callable[[Deployment, str], DeploymentHandle] + ] = None, +) -> BuiltApplication: + """Builds the application into a list of finalized deployments. + + The following transformations are made: + - Application objects in constructor args/kwargs are converted to + DeploymentHandles for injection at runtime. + - Name conflicts from deployments that use the same class are handled + by appending a monotonically increasing suffix (e.g., SomeClass_1). + + Returns: BuiltApplication + """ + if make_deployment_handle is None: + make_deployment_handle = _make_deployment_handle_default + + handles = IDDict() + deployment_names = IDDict() + deployments = _build_app_recursive( + app, + app_name=name, + handles=handles, + deployment_names=deployment_names, + default_runtime_env=default_runtime_env, + make_deployment_handle=make_deployment_handle, + ) + return BuiltApplication( + name=name, + route_prefix=route_prefix, + logging_config=logging_config, + ingress_deployment_name=app._bound_deployment.name, + deployments=deployments, + deployment_handles={ + deployment_names[app]: handle for app, handle in handles.items() + }, + ) + + +def _build_app_recursive( + app: Application, + *, + app_name: str, + deployment_names: IDDict[Application, str], + handles: IDDict[Application, DeploymentHandle], + default_runtime_env: Optional[Dict[str, Any]] = None, + make_deployment_handle: Callable[[Deployment, str], DeploymentHandle], +) -> List[Deployment]: + """Recursively traverses the graph of Application objects. + + Each Application will have an associated DeploymentHandle created that will replace + it in any occurrences in other Applications' args or kwargs. + + Also collects a list of the unique Applications encountered and returns them as + deployable Deployment objects. + """ + # This application has already been encountered. + # There's no need to recurse into its child args and we don't want to create + # a duplicate entry for it in the list of deployments. + if app in handles: + return [] + + deployments = [] + scanner = _PyObjScanner(source_type=Application) + try: + # Recursively traverse any Application objects bound to init args/kwargs. + child_apps = scanner.find_nodes( + (app._bound_deployment.init_args, app._bound_deployment.init_kwargs) + ) + for child_app in child_apps: + deployments.extend( + _build_app_recursive( + child_app, + app_name=app_name, + handles=handles, + deployment_names=deployment_names, + make_deployment_handle=make_deployment_handle, + default_runtime_env=default_runtime_env, + ) + ) + + # Replace Application objects with their corresponding DeploymentHandles. + new_init_args, new_init_kwargs = scanner.replace_nodes(handles) + final_deployment = app._bound_deployment.options( + name=_get_unique_deployment_name_memoized(app, deployment_names), + _init_args=new_init_args, + _init_kwargs=new_init_kwargs, + ) + final_deployment = _set_default_runtime_env( + final_deployment, default_runtime_env + ) + + # Create the DeploymentHandle that will be used to replace this application + # in the arguments of its parent(s). + handles[app] = make_deployment_handle( + final_deployment, + app_name, + ) + + return deployments + [final_deployment] + finally: + scanner.clear() + + +def _set_default_runtime_env( + d: Deployment, default_runtime_env: Optional[Dict[str, Any]] +) -> Deployment: + """Configures the deployment with the provided default runtime_env. + + If the deployment does not have a runtime_env configured, the default will be set. + + If it does have a runtime_env configured but that runtime_env does not have a + working_dir, only the working_dir field will be set. + + Else the deployment's runtime_env will be left untouched. + """ + if not default_runtime_env: + return d + + ray_actor_options = deepcopy(d.ray_actor_options or {}) + default_working_dir = default_runtime_env.get("working_dir", None) + if "runtime_env" not in ray_actor_options: + ray_actor_options["runtime_env"] = default_runtime_env + elif default_working_dir is not None: + ray_actor_options["runtime_env"].setdefault("working_dir", default_working_dir) + + return d.options(ray_actor_options=ray_actor_options) + + +def _get_unique_deployment_name_memoized( + app: Application, deployment_names: IDDict[Application, str] +) -> str: + """Generates a name for the deployment. + + This is used to handle collisions when the user does not specify a name + explicitly, so typically we'd use the class name as the default. + + In that case, we append a monotonically increasing suffix to the name, e.g., + Deployment, then Deployment_1, then Deployment_2, ... + + Names are memoized in the `deployment_names` dict, which should be passed to + subsequent calls to this function. + """ + if app in deployment_names: + return deployment_names[app] + + idx = 1 + name = app._bound_deployment.name + while name in deployment_names.values(): + name = f"{app._bound_deployment.name}_{idx}" + idx += 1 + + if idx != 1: + logger.warning( + "There are multiple deployments with the same name " + f"'{app._bound_deployment.name}'. Renaming one to '{name}'." + ) + + deployment_names[app] = name + return name diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/client.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/client.py new file mode 100644 index 0000000000000000000000000000000000000000..ffec15fa89c2ad913bea3dfeee21fbb4a3fe2701 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/client.py @@ -0,0 +1,494 @@ +import logging +import random +import time +from collections.abc import Sequence +from functools import wraps +from typing import Callable, Dict, List, Optional, Tuple, Union + +import ray +from ray.actor import ActorHandle +from ray.serve._private.application_state import StatusOverview +from ray.serve._private.build_app import BuiltApplication +from ray.serve._private.common import ( + DeploymentID, + DeploymentStatus, + DeploymentStatusInfo, + RequestRoutingInfo, +) +from ray.serve._private.constants import ( + CLIENT_CHECK_CREATION_POLLING_INTERVAL_S, + CLIENT_POLLING_INTERVAL_S, + MAX_CACHED_HANDLES, + SERVE_DEFAULT_APP_NAME, + SERVE_LOGGER_NAME, +) +from ray.serve._private.controller import ServeController +from ray.serve._private.deploy_utils import get_deploy_args +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.utils import get_random_string +from ray.serve.config import HTTPOptions +from ray.serve.exceptions import RayServeException +from ray.serve.generated.serve_pb2 import ( + DeploymentArgs, + DeploymentRoute, + DeploymentStatusInfo as DeploymentStatusInfoProto, + StatusOverview as StatusOverviewProto, +) +from ray.serve.handle import DeploymentHandle +from ray.serve.schema import ( + ApplicationStatus, + LoggingConfig, + ServeApplicationSchema, + ServeDeploySchema, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def _ensure_connected(f: Callable) -> Callable: + @wraps(f) + def check(self, *args, **kwargs): + if self._shutdown: + raise RayServeException("Client has already been shut down.") + return f(self, *args, **kwargs) + + return check + + +class ServeControllerClient: + def __init__( + self, + controller: ActorHandle, + ): + self._controller: ServeController = controller + self._shutdown = False + self._http_config: HTTPOptions = ray.get(controller.get_http_config.remote()) + self._root_url = ray.get(controller.get_root_url.remote()) + + # Each handle has the overhead of long poll client, therefore cached. + self.handle_cache = dict() + self._evicted_handle_keys = set() + + @property + def root_url(self): + return self._root_url + + @property + def http_config(self): + return self._http_config + + def __reduce__(self): + raise RayServeException(("Ray Serve client cannot be serialized.")) + + def shutdown_cached_handles(self, _skip_asyncio_check: bool = False): + """Shuts down all cached handles. + + Remove the reference to the cached handles so that they can be + garbage collected. + """ + for cache_key in list(self.handle_cache): + self.handle_cache[cache_key].shutdown( + _skip_asyncio_check=_skip_asyncio_check + ) + del self.handle_cache[cache_key] + + def shutdown(self, timeout_s: float = 30.0) -> None: + """Completely shut down the connected Serve instance. + + Shuts down all processes and deletes all state associated with the + instance. + """ + self.shutdown_cached_handles() + + if ray.is_initialized() and not self._shutdown: + try: + ray.get(self._controller.graceful_shutdown.remote(), timeout=timeout_s) + except ray.exceptions.RayActorError: + # Controller has been shut down. + pass + except TimeoutError: + logger.warning( + f"Controller failed to shut down within {timeout_s}s. " + "Check controller logs for more details." + ) + self._shutdown = True + + def _wait_for_deployment_healthy(self, name: str, timeout_s: int = -1): + """Waits for the named deployment to enter "HEALTHY" status. + + Raises RuntimeError if the deployment enters the "UNHEALTHY" status + instead. + + Raises TimeoutError if this doesn't happen before timeout_s. + """ + start = time.time() + while time.time() - start < timeout_s or timeout_s < 0: + status_bytes = ray.get(self._controller.get_deployment_status.remote(name)) + + if status_bytes is None: + raise RuntimeError( + f"Waiting for deployment {name} to be HEALTHY, " + "but deployment doesn't exist." + ) + + status = DeploymentStatusInfo.from_proto( + DeploymentStatusInfoProto.FromString(status_bytes) + ) + + if status.status == DeploymentStatus.HEALTHY: + break + elif status.status == DeploymentStatus.UNHEALTHY: + raise RuntimeError( + f"Deployment {name} is UNHEALTHY: " f"{status.message}" + ) + else: + # Guard against new unhandled statuses being added. + assert status.status == DeploymentStatus.UPDATING + + logger.debug( + f"Waiting for {name} to be healthy, current status: " + f"{status.status}." + ) + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Deployment {name} did not become HEALTHY after {timeout_s}s." + ) + + def _wait_for_deployment_deleted( + self, name: str, app_name: str, timeout_s: int = 60 + ): + """Waits for the named deployment to be shut down and deleted. + + Raises TimeoutError if this doesn't happen before timeout_s. + """ + start = time.time() + while time.time() - start < timeout_s: + curr_status_bytes = ray.get( + self._controller.get_deployment_status.remote(name) + ) + if curr_status_bytes is None: + break + curr_status = DeploymentStatusInfo.from_proto( + DeploymentStatusInfoProto.FromString(curr_status_bytes) + ) + logger.debug( + f"Waiting for {name} to be deleted, current status: {curr_status}." + ) + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError(f"Deployment {name} wasn't deleted after {timeout_s}s.") + + def _wait_for_deployment_created( + self, deployment_name: str, app_name: str, timeout_s: int = -1 + ): + """Waits for the named deployment to be created. + + A deployment being created simply means that its been registered + with the deployment state manager. The deployment state manager + will then continue to reconcile the deployment towards its + target state. + + Raises TimeoutError if this doesn't happen before timeout_s. + """ + + start = time.time() + while time.time() - start < timeout_s or timeout_s < 0: + status_bytes = ray.get( + self._controller.get_deployment_status.remote(deployment_name, app_name) + ) + + if status_bytes is not None: + break + + logger.debug( + f"Waiting for deployment '{deployment_name}' in application " + f"'{app_name}' to be created." + ) + time.sleep(CLIENT_CHECK_CREATION_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Deployment '{deployment_name}' in application '{app_name}' " + f"did not become HEALTHY after {timeout_s}s." + ) + + def _wait_for_application_running(self, name: str, timeout_s: int = -1): + """Waits for the named application to enter "RUNNING" status. + + Raises: + RuntimeError: if the application enters the "DEPLOY_FAILED" status instead. + TimeoutError: if this doesn't happen before timeout_s. + """ + start = time.time() + while time.time() - start < timeout_s or timeout_s < 0: + status_bytes = ray.get(self._controller.get_serve_status.remote(name)) + if status_bytes is None: + raise RuntimeError( + f"Waiting for application {name} to be RUNNING, " + "but application doesn't exist." + ) + + status = StatusOverview.from_proto( + StatusOverviewProto.FromString(status_bytes) + ) + + if status.app_status.status == ApplicationStatus.RUNNING: + break + elif status.app_status.status == ApplicationStatus.DEPLOY_FAILED: + raise RuntimeError( + f"Deploying application {name} failed: {status.app_status.message}" + ) + + logger.debug( + f"Waiting for {name} to be RUNNING, current status: " + f"{status.app_status.status}." + ) + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Application {name} did not become RUNNING after {timeout_s}s." + ) + + @_ensure_connected + def deploy_applications( + self, + built_apps: Sequence[BuiltApplication], + *, + wait_for_ingress_deployment_creation: bool = True, + wait_for_applications_running: bool = True, + ) -> List[DeploymentHandle]: + name_to_deployment_args_list = {} + for app in built_apps: + deployment_args_list = [] + for deployment in app.deployments: + if deployment.logging_config is None and app.logging_config: + deployment = deployment.options(logging_config=app.logging_config) + + is_ingress = deployment.name == app.ingress_deployment_name + deployment_args = get_deploy_args( + deployment.name, + ingress=is_ingress, + replica_config=deployment._replica_config, + deployment_config=deployment._deployment_config, + version=deployment._version or get_random_string(), + route_prefix=app.route_prefix if is_ingress else None, + ) + + deployment_args_proto = DeploymentArgs() + deployment_args_proto.deployment_name = deployment_args[ + "deployment_name" + ] + deployment_args_proto.deployment_config = deployment_args[ + "deployment_config_proto_bytes" + ] + deployment_args_proto.replica_config = deployment_args[ + "replica_config_proto_bytes" + ] + deployment_args_proto.deployer_job_id = deployment_args[ + "deployer_job_id" + ] + if deployment_args["route_prefix"]: + deployment_args_proto.route_prefix = deployment_args["route_prefix"] + deployment_args_proto.ingress = deployment_args["ingress"] + + deployment_args_list.append(deployment_args_proto.SerializeToString()) + + name_to_deployment_args_list[app.name] = deployment_args_list + + ray.get( + self._controller.deploy_applications.remote(name_to_deployment_args_list) + ) + + handles = [] + for app in built_apps: + # The deployment state is not guaranteed to be created after + # deploy_application returns; the application state manager will + # need another reconcile iteration to create it. + if wait_for_ingress_deployment_creation: + self._wait_for_deployment_created(app.ingress_deployment_name, app.name) + + if wait_for_applications_running: + self._wait_for_application_running(app.name) + if app.route_prefix is not None: + url_part = " at " + self._root_url + app.route_prefix + else: + url_part = "" + logger.info(f"Application '{app.name}' is ready{url_part}.") + + handles.append( + self.get_handle( + app.ingress_deployment_name, app.name, check_exists=False + ) + ) + + return handles + + @_ensure_connected + def deploy_apps( + self, + config: Union[ServeApplicationSchema, ServeDeploySchema], + _blocking: bool = False, + ) -> None: + """Starts a task on the controller that deploys application(s) from a config. + + Args: + config: A single-application config (ServeApplicationSchema) or a + multi-application config (ServeDeploySchema) + _blocking: Whether to block until the application is running. + + Raises: + RayTaskError: If the deploy task on the controller fails. This can be + because a single-app config was deployed after deploying a multi-app + config, or vice versa. + """ + ray.get(self._controller.apply_config.remote(config)) + + if _blocking: + timeout_s = 60 + + start = time.time() + while time.time() - start < timeout_s: + curr_status = self.get_serve_status() + if curr_status.app_status.status == ApplicationStatus.RUNNING: + break + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Serve application isn't running after {timeout_s}s." + ) + + @_ensure_connected + def delete_apps(self, names: List[str], blocking: bool = True): + if not names: + return + + logger.info(f"Deleting app {names}") + self._controller.delete_apps.remote(names) + if blocking: + start = time.time() + while time.time() - start < 60: + curr_statuses_bytes = ray.get( + self._controller.get_serve_statuses.remote(names) + ) + all_deleted = True + for cur_status_bytes in curr_statuses_bytes: + cur_status = StatusOverview.from_proto( + StatusOverviewProto.FromString(cur_status_bytes) + ) + if cur_status.app_status.status != ApplicationStatus.NOT_STARTED: + all_deleted = False + if all_deleted: + return + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Some of these applications weren't deleted after 60s: {names}" + ) + + @_ensure_connected + def delete_all_apps(self, blocking: bool = True): + """Delete all applications""" + all_apps = [] + for status_bytes in ray.get(self._controller.list_serve_statuses.remote()): + proto = StatusOverviewProto.FromString(status_bytes) + status = StatusOverview.from_proto(proto) + all_apps.append(status.name) + self.delete_apps(all_apps, blocking) + + @_ensure_connected + def get_deployment_info( + self, name: str, app_name: str + ) -> Tuple[DeploymentInfo, str]: + deployment_route = DeploymentRoute.FromString( + ray.get(self._controller.get_deployment_info.remote(name, app_name)) + ) + return ( + DeploymentInfo.from_proto(deployment_route.deployment_info), + deployment_route.route if deployment_route.route != "" else None, + ) + + @_ensure_connected + def get_serve_status(self, name: str = SERVE_DEFAULT_APP_NAME) -> StatusOverview: + proto = StatusOverviewProto.FromString( + ray.get(self._controller.get_serve_status.remote(name)) + ) + return StatusOverview.from_proto(proto) + + @_ensure_connected + def get_all_deployment_statuses(self) -> List[DeploymentStatusInfo]: + statuses_bytes = ray.get(self._controller.get_all_deployment_statuses.remote()) + return [ + DeploymentStatusInfo.from_proto( + DeploymentStatusInfoProto.FromString(status_bytes) + ) + for status_bytes in statuses_bytes + ] + + @_ensure_connected + def get_serve_details(self) -> Dict: + return ray.get(self._controller.get_serve_instance_details.remote()) + + @_ensure_connected + def get_handle( + self, + deployment_name: str, + app_name: Optional[str] = SERVE_DEFAULT_APP_NAME, + check_exists: bool = True, + ) -> DeploymentHandle: + """Construct a handle for the specified deployment. + + Args: + deployment_name: Deployment name. + app_name: Application name. + check_exists: If False, then Serve won't check the deployment + is registered. True by default. + + Returns: + DeploymentHandle + """ + deployment_id = DeploymentID(name=deployment_name, app_name=app_name) + cache_key = (deployment_name, app_name, check_exists) + if cache_key in self.handle_cache: + return self.handle_cache[cache_key] + + if check_exists: + all_deployments = ray.get(self._controller.list_deployment_ids.remote()) + if deployment_id not in all_deployments: + raise KeyError(f"{deployment_id} does not exist.") + + handle = DeploymentHandle(deployment_name, app_name) + self.handle_cache[cache_key] = handle + if cache_key in self._evicted_handle_keys: + logger.warning( + "You just got a ServeHandle that was evicted from internal " + "cache. This means you are getting too many ServeHandles in " + "the same process, this will bring down Serve's performance. " + "Please post a github issue at " + "https://github.com/ray-project/ray/issues to let the Serve " + "team to find workaround for your use case." + ) + + if len(self.handle_cache) > MAX_CACHED_HANDLES: + # Perform random eviction to keep the handle cache from growing + # infinitely. We used use WeakValueDictionary but hit + # https://github.com/ray-project/ray/issues/18980. + evict_key = random.choice(list(self.handle_cache.keys())) + self._evicted_handle_keys.add(evict_key) + self.handle_cache.pop(evict_key) + + return handle + + @_ensure_connected + def record_request_routing_info(self, info: RequestRoutingInfo): + """Record replica routing information for a replica. + + Args: + info: RequestRoutingInfo including deployment name, replica tag, + multiplex model ids, and routing stats. + """ + self._controller.record_request_routing_info.remote(info) + + @_ensure_connected + def update_global_logging_config(self, logging_config: LoggingConfig): + """Reconfigure the logging config for the controller & proxies.""" + self._controller.reconfigure_global_logging_config.remote(logging_config) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/cluster_node_info_cache.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/cluster_node_info_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0121dd309d61d49409a6801650cd91a1f7f269 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/cluster_node_info_cache.py @@ -0,0 +1,102 @@ +from abc import ABC, abstractmethod +from typing import Dict, List, Optional, Set, Tuple, Union + +import ray +from ray._raylet import GcsClient +from ray.serve._private.constants import RAY_GCS_RPC_TIMEOUT_S + + +class ClusterNodeInfoCache(ABC): + """Provide access to cached node information in the cluster.""" + + def __init__(self, gcs_client: GcsClient): + self._gcs_client = gcs_client + self._cached_alive_nodes = None + self._cached_node_labels = dict() + self._cached_total_resources_per_node = dict() + self._cached_available_resources_per_node = dict() + + def update(self): + """Update the cache by fetching latest node information from GCS. + + This should be called once in each update cycle. + Within an update cycle, everyone will see the same + cached node info avoiding any potential issues + caused by inconsistent node info seen by different components. + """ + nodes = self._gcs_client.get_all_node_info(timeout=RAY_GCS_RPC_TIMEOUT_S) + alive_nodes = [ + (node_id.hex(), node.node_name, node.instance_id) + for (node_id, node) in nodes.items() + if node.state == ray.core.generated.gcs_pb2.GcsNodeInfo.ALIVE + ] + + # Sort on NodeID to ensure the ordering is deterministic across the cluster. + sorted(alive_nodes) + self._cached_alive_nodes = alive_nodes + self._cached_node_labels = { + node_id.hex(): dict(node.labels) for (node_id, node) in nodes.items() + } + + # Node resources + self._cached_total_resources_per_node = { + node_id.hex(): dict(node.resources_total) + for (node_id, node) in nodes.items() + } + + self._cached_available_resources_per_node = ( + ray._private.state.available_resources_per_node() + ) + + def get_alive_nodes(self) -> List[Tuple[str, str, str]]: + """Get IDs, IPs, and Instance IDs for all live nodes in the cluster. + + Returns a list of (node_id: str, node_ip: str, instance_id: str). + The node_id can be passed into the Ray SchedulingPolicy API. + """ + return self._cached_alive_nodes + + def get_total_resources_per_node(self) -> Dict[str, Dict]: + """Get total resources for alive nodes.""" + return self._cached_total_resources_per_node + + def get_alive_node_ids(self) -> Set[str]: + """Get IDs of all live nodes in the cluster.""" + return {node_id for node_id, _, _ in self.get_alive_nodes()} + + @abstractmethod + def get_draining_nodes(self) -> Dict[str, int]: + """Get draining nodes in the cluster and their deadlines.""" + raise NotImplementedError + + @abstractmethod + def get_node_az(self, node_id: str) -> Optional[str]: + """Get availability zone of a node.""" + raise NotImplementedError + + def get_active_node_ids(self) -> Set[str]: + """Get IDs of all active nodes in the cluster. + + A node is active if it's schedulable for new tasks and actors. + """ + return self.get_alive_node_ids() - set(self.get_draining_nodes()) + + def get_available_resources_per_node(self) -> Dict[str, Union[float, Dict]]: + """Get available resources per node. + + Returns a map from (node_id -> Dict of resources). + """ + + return self._cached_available_resources_per_node + + +class DefaultClusterNodeInfoCache(ClusterNodeInfoCache): + def __init__(self, gcs_client: GcsClient): + super().__init__(gcs_client) + + def get_draining_nodes(self) -> Dict[str, int]: + return dict() + + def get_node_az(self, node_id: str) -> Optional[str]: + """Get availability zone of a node.""" + return None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/common.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/common.py new file mode 100644 index 0000000000000000000000000000000000000000..682b186a6d7f2a41c366aff14f3987f88bf6b403 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/common.py @@ -0,0 +1,756 @@ +import json +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Any, Awaitable, Callable, Dict, List, Optional + +from starlette.types import Scope + +import ray +from ray.actor import ActorHandle +from ray.serve._private.constants import SERVE_DEFAULT_APP_NAME, SERVE_NAMESPACE +from ray.serve.generated.serve_pb2 import ( + DeploymentStatus as DeploymentStatusProto, + DeploymentStatusInfo as DeploymentStatusInfoProto, + DeploymentStatusTrigger as DeploymentStatusTriggerProto, +) +from ray.serve.grpc_util import RayServegRPCContext +from ray.util.annotations import PublicAPI + +REPLICA_ID_FULL_ID_STR_PREFIX = "SERVE_REPLICA::" + + +@dataclass(frozen=True) +class DeploymentID: + name: str + app_name: str = SERVE_DEFAULT_APP_NAME + + def to_replica_actor_class_name(self): + return f"ServeReplica:{self.app_name}:{self.name}" + + def __str__(self): + return f"Deployment(name='{self.name}', app='{self.app_name}')" + + def __repr__(self): + return str(self) + + +@PublicAPI(stability="alpha") +@dataclass(frozen=True) +class ReplicaID: + """A unique identifier for a replica.""" + + unique_id: str + """A unique identifier for the replica within the deployment.""" + + deployment_id: DeploymentID + """The deployment this replica belongs to.""" + + def to_full_id_str(self) -> str: + s = f"{self.deployment_id.name}#{self.unique_id}" + if self.deployment_id.app_name: + s = f"{self.deployment_id.app_name}#{s}" + + return f"{REPLICA_ID_FULL_ID_STR_PREFIX}{s}" + + @staticmethod + def is_full_id_str(s: str) -> bool: + return s.startswith(REPLICA_ID_FULL_ID_STR_PREFIX) + + @classmethod + def from_full_id_str(cls, s: str): + assert cls.is_full_id_str(s) + + parsed = s[len(REPLICA_ID_FULL_ID_STR_PREFIX) :].split("#") + if len(parsed) == 3: + app_name, deployment_name, unique_id = parsed + elif len(parsed) == 2: + app_name = "" + deployment_name, unique_id = parsed + else: + raise ValueError( + f"Given replica ID string {s} didn't match expected pattern, " + "ensure it has either two or three fields with delimiter '#'." + ) + + return cls( + unique_id, + deployment_id=DeploymentID(name=deployment_name, app_name=app_name), + ) + + def __repr__(self) -> str: + return str(self) + + def __str__(self) -> str: + """Returns a human-readable string. + + This is used in user-facing log messages, so take care when updating it. + """ + return ( + f"Replica(" + f"id='{self.unique_id}', " + f"deployment='{self.deployment_id.name}', " + f"app='{self.deployment_id.app_name}'" + ")" + ) + + +NodeId = str +Duration = float +ApplicationName = str + + +@dataclass +class EndpointInfo: + route: str + app_is_cross_language: bool = False + + +# Keep in sync with ServeReplicaState in dashboard/client/src/type/serve.ts +class ReplicaState(str, Enum): + STARTING = "STARTING" + UPDATING = "UPDATING" + RECOVERING = "RECOVERING" + RUNNING = "RUNNING" + STOPPING = "STOPPING" + PENDING_MIGRATION = "PENDING_MIGRATION" + + +class DeploymentStatus(str, Enum): + UPDATING = "UPDATING" + HEALTHY = "HEALTHY" + UNHEALTHY = "UNHEALTHY" + DEPLOY_FAILED = "DEPLOY_FAILED" + UPSCALING = "UPSCALING" + DOWNSCALING = "DOWNSCALING" + + +class DeploymentStatusTrigger(str, Enum): + """Explains how a deployment reached its current DeploymentStatus.""" + + UNSPECIFIED = "UNSPECIFIED" + CONFIG_UPDATE_STARTED = "CONFIG_UPDATE_STARTED" + CONFIG_UPDATE_COMPLETED = "CONFIG_UPDATE_COMPLETED" + UPSCALE_COMPLETED = "UPSCALE_COMPLETED" + DOWNSCALE_COMPLETED = "DOWNSCALE_COMPLETED" + AUTOSCALING = "AUTOSCALING" + REPLICA_STARTUP_FAILED = "REPLICA_STARTUP_FAILED" + HEALTH_CHECK_FAILED = "HEALTH_CHECK_FAILED" + INTERNAL_ERROR = "INTERNAL_ERROR" + DELETING = "DELETING" + + +# Internal Enum used to manage deployment state machine +class DeploymentStatusInternalTrigger(str, Enum): + HEALTHY = "HEALTHY" + CONFIG_UPDATE = "CONFIG_UPDATE" + AUTOSCALE_UP = "AUTOSCALE_UP" + AUTOSCALE_DOWN = "AUTOSCALE_DOWN" + # MANUALLY_INCREASE_NUM_REPLICAS and MANUALLY_DECREASE_NUM_REPLICAS are used + # instead of CONFIG_UPDATE when the config update only scales + # the number of replicas. + MANUALLY_INCREASE_NUM_REPLICAS = "MANUALLY_INCREASE_NUM_REPLICAS" + MANUALLY_DECREASE_NUM_REPLICAS = "MANUALLY_DECREASE_NUM_REPLICAS" + REPLICA_STARTUP_FAILED = "REPLICA_STARTUP_FAILED" + HEALTH_CHECK_FAILED = "HEALTH_CHECK_FAILED" + INTERNAL_ERROR = "INTERNAL_ERROR" + DELETE = "DELETE" + + +# List of states in ranked order. +# +# Each ranked state has the format of a tuple with either 1 or 2 items. +# If 1 item: contains a single DeploymentStatus, representing states with +# that DeploymentStatus and any DeploymentStatusTrigger. +# If 2 items: tuple contains a DeploymentStatus and a DeploymentStatusTrigger, +# representing a state with that status and status trigger. +DEPLOYMENT_STATUS_RANKING_ORDER = { + # Status ranking order is defined in a following fashion: + # 0. (Highest) State signaling a deploy failure. + (DeploymentStatus.DEPLOY_FAILED,): 0, + # 1. State signaling any non-deploy failures in the system. + (DeploymentStatus.UNHEALTHY,): 1, + # 2. States signaling the user updated the configuration. + (DeploymentStatus.UPDATING,): 2, + (DeploymentStatus.UPSCALING, DeploymentStatusTrigger.CONFIG_UPDATE_STARTED): 2, + ( + DeploymentStatus.DOWNSCALING, + DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + ): 2, + # 3. Steady state or autoscaling. + (DeploymentStatus.UPSCALING, DeploymentStatusTrigger.AUTOSCALING): 3, + (DeploymentStatus.DOWNSCALING, DeploymentStatusTrigger.AUTOSCALING): 3, + (DeploymentStatus.HEALTHY,): 3, +} + + +@dataclass(eq=True) +class DeploymentStatusInfo: + name: str + status: DeploymentStatus + status_trigger: DeploymentStatusTrigger + message: str = "" + + @property + def rank(self) -> int: + """Get priority of state based on ranking_order(). + + The ranked order indicates what the status should be of a + hierarchically "higher" resource when derived from a group of + `DeploymentStatusInfo` sub-resources. + """ + + if (self.status,) in DEPLOYMENT_STATUS_RANKING_ORDER: + return DEPLOYMENT_STATUS_RANKING_ORDER[(self.status,)] + elif (self.status, self.status_trigger) in DEPLOYMENT_STATUS_RANKING_ORDER: + return DEPLOYMENT_STATUS_RANKING_ORDER[(self.status, self.status_trigger)] + + def debug_string(self): + return json.dumps(asdict(self), indent=4) + + def _updated_copy( + self, + status: DeploymentStatus = None, + status_trigger: DeploymentStatusTrigger = None, + message: str = "", + ): + """Returns a copy of the current object with the passed in kwargs updated.""" + + return DeploymentStatusInfo( + name=self.name, + status=status if status else self.status, + status_trigger=status_trigger if status_trigger else self.status_trigger, + message=message, + ) + + def update_message(self, message: str): + return self._updated_copy(message=message) + + def handle_transition( + self, + trigger: DeploymentStatusInternalTrigger, + message: str = "", + ) -> "DeploymentStatusInfo": + """Handles a transition from the current state to the next state. + + Args: + trigger: An internal trigger that determines the state + transition. This is the new incoming trigger causing the + transition. + message: The message to set in status info. + + Returns: + New instance of DeploymentStatusInfo representing the + next state to transition to. + """ + + # If there was an unexpected internal error during reconciliation, set + # status to unhealthy immediately and return + if trigger == DeploymentStatusInternalTrigger.INTERNAL_ERROR: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.INTERNAL_ERROR, + message=message, + ) + + # If deployment is being deleted, set status immediately and return + elif trigger == DeploymentStatusInternalTrigger.DELETE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.DELETING, + message=message, + ) + + # Otherwise, go through normal state machine transitions + elif self.status == DeploymentStatus.UPDATING: + # Finished updating configuration and transition to healthy + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self._updated_copy( + status=DeploymentStatus.HEALTHY, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_COMPLETED, + message=message, + ) + + # A new configuration has been deployed before deployment + # has finished updating + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Autoscaling. + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_UP: + return self._updated_copy( + status=DeploymentStatus.UPSCALING, + status_trigger=DeploymentStatusTrigger.AUTOSCALING, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_DOWN: + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, + status_trigger=DeploymentStatusTrigger.AUTOSCALING, + message=message, + ) + + # Manually increasing or decreasing num replicas does not + # change the status while deployment is still updating. + elif trigger in { + DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS, + DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS, + }: + return self + + # Failures occurred while a deployment was being updated + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.DEPLOY_FAILED, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED: + return self._updated_copy( + status=DeploymentStatus.DEPLOY_FAILED, + status_trigger=DeploymentStatusTrigger.REPLICA_STARTUP_FAILED, + message=message, + ) + + elif self.status in {DeploymentStatus.UPSCALING, DeploymentStatus.DOWNSCALING}: + # Failures occurred while upscaling/downscaling + if trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.REPLICA_STARTUP_FAILED, + message=message, + ) + # Deployment transitions to healthy + elif trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self._updated_copy( + status=DeploymentStatus.HEALTHY, + status_trigger=DeploymentStatusTrigger.UPSCALE_COMPLETED + if self.status == DeploymentStatus.UPSCALING + else DeploymentStatusTrigger.DOWNSCALE_COMPLETED, + message=message, + ) + + # Configuration is updated before scaling is finished + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + elif self.status_trigger == DeploymentStatusTrigger.AUTOSCALING: + # Upscale replicas before previous autoscaling has finished + if trigger == DeploymentStatusInternalTrigger.AUTOSCALE_UP: + return self._updated_copy( + status=DeploymentStatus.UPSCALING, + message=message, + ) + # Downscale replicas before previous autoscaling has finished + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_DOWN: + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, + message=message, + ) + # Manually upscale replicas with config update before previous autoscaling has finished + elif ( + trigger + == DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.UPSCALING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + # Manually downscale replicas with config update before previous autoscaling has finished + elif ( + trigger + == DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + elif self.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED: + # Upscale replicas before previous config update has finished + if ( + trigger + == DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.UPSCALING, message=message + ) + + # Downscale replicas before previous config update has finished + elif ( + trigger + == DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, message=message + ) + + elif self.status == DeploymentStatus.HEALTHY: + # Deployment remains healthy + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self + + # New configuration is deployed + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Manually scaling / autoscaling num replicas + elif ( + trigger + == DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.UPSCALING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + elif ( + trigger + == DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_UP: + return self._updated_copy( + status=DeploymentStatus.UPSCALING, + status_trigger=DeploymentStatusTrigger.AUTOSCALING, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_DOWN: + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, + status_trigger=DeploymentStatusTrigger.AUTOSCALING, + message=message, + ) + + # Health check for one or more replicas has failed + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + + elif self.status == DeploymentStatus.UNHEALTHY: + # The deployment recovered + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self._updated_copy( + status=DeploymentStatus.HEALTHY, + status_trigger=DeploymentStatusTrigger.UNSPECIFIED, + message=message, + ) + + # A new configuration is being deployed. + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Old failures keep getting triggered, or new failures occurred. + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.REPLICA_STARTUP_FAILED, + message=message, + ) + + elif self.status == DeploymentStatus.DEPLOY_FAILED: + # The deployment recovered + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self._updated_copy( + status=DeploymentStatus.HEALTHY, + status_trigger=DeploymentStatusTrigger.UNSPECIFIED, + message=message, + ) + + # A new configuration is being deployed. + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Old failures keep getting triggered, or new failures occurred. + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.DEPLOY_FAILED, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED: + return self._updated_copy( + status=DeploymentStatus.DEPLOY_FAILED, + status_trigger=DeploymentStatusTrigger.REPLICA_STARTUP_FAILED, + message=message, + ) + + # If it's any other transition, ignore it. + return self + + def to_proto(self): + return DeploymentStatusInfoProto( + name=self.name, + status=f"DEPLOYMENT_STATUS_{self.status.name}", + status_trigger=f"DEPLOYMENT_STATUS_TRIGGER_{self.status_trigger.name}", + message=self.message, + ) + + @classmethod + def from_proto(cls, proto: DeploymentStatusInfoProto): + status = DeploymentStatusProto.Name(proto.status)[len("DEPLOYMENT_STATUS_") :] + status_trigger = DeploymentStatusTriggerProto.Name(proto.status_trigger)[ + len("DEPLOYMENT_STATUS_TRIGGER_") : + ] + return cls( + name=proto.name, + status=DeploymentStatus(status), + status_trigger=DeploymentStatusTrigger(status_trigger), + message=proto.message, + ) + + +@dataclass(frozen=True) +class RunningReplicaInfo: + replica_id: ReplicaID + node_id: Optional[str] + node_ip: Optional[str] + availability_zone: Optional[str] + actor_handle: ActorHandle + max_ongoing_requests: int + is_cross_language: bool = False + multiplexed_model_ids: List[str] = field(default_factory=list) + routing_stats: Dict[str, Any] = field(default_factory=dict) + port: Optional[int] = None + + def __post_init__(self): + # Set hash value when object is constructed. + # We use _actor_id to hash the ActorHandle object + # instead of actor_handle itself to make sure + # it is consistently same actor handle between different + # object ids. + + hash_val = hash( + " ".join( + [ + self.replica_id.to_full_id_str(), + self.node_id if self.node_id else "", + str(self.actor_handle._actor_id), + str(self.max_ongoing_requests), + str(self.is_cross_language), + str(self.multiplexed_model_ids), + str(self.routing_stats), + ] + ) + ) + + # RunningReplicaInfo class set frozen=True, this is the hacky way to set + # new attribute for the class. + object.__setattr__(self, "_hash", hash_val) + + def __hash__(self): + return self._hash + + def __eq__(self, other): + return all( + [ + isinstance(other, RunningReplicaInfo), + self._hash == other._hash, + ] + ) + + +@dataclass(frozen=True) +class DeploymentTargetInfo: + is_available: bool + running_replicas: List[RunningReplicaInfo] + + +class ServeDeployMode(str, Enum): + MULTI_APP = "MULTI_APP" + + +class ServeComponentType(str, Enum): + REPLICA = "replica" + + +@dataclass +class RequestRoutingInfo: + """Information about the request routing. + + It includes deployment name (from ReplicaID), replica tag (from ReplicaID), + multiplex model ids, and routing stats. + """ + + replica_id: ReplicaID + multiplexed_model_ids: Optional[List[str]] = None + routing_stats: Optional[Dict[str, Any]] = None + + +@dataclass +class gRPCRequest: + """Sent from the GRPC proxy to replicas on both unary and streaming codepaths.""" + + user_request_proto: Any + + +class RequestProtocol(str, Enum): + UNDEFINED = "UNDEFINED" + HTTP = "HTTP" + GRPC = "gRPC" + + +class DeploymentHandleSource(str, Enum): + UNKNOWN = "UNKNOWN" + PROXY = "PROXY" + REPLICA = "REPLICA" + + +@dataclass +class RequestMetadata: + # request_id can be passed by the client and is only generated by the proxy if the + # client did not pass it in the headers. It is used for logging across different + # system. We can not guarantee the uniqueness of its value. + request_id: str + # internal_request_id is always generated by the proxy and is used for tracking + # request objects. We can assume this is always unique between requests. + internal_request_id: str + + # Method of the user callable to execute. + call_method: str = "__call__" + + # HTTP route path of the request. + route: str = "" + + # Application name. + app_name: str = "" + + # Multiplexed model ID. + multiplexed_model_id: str = "" + + # If this request expects a streaming response. + is_streaming: bool = False + + _http_method: str = "" + + # The protocol to serve this request + _request_protocol: RequestProtocol = RequestProtocol.UNDEFINED + + # Serve's gRPC context associated with this request for getting and setting metadata + grpc_context: Optional[RayServegRPCContext] = None + + _by_reference: bool = True + + @property + def is_http_request(self) -> bool: + return self._request_protocol == RequestProtocol.HTTP + + @property + def is_grpc_request(self) -> bool: + return self._request_protocol == RequestProtocol.GRPC + + +class StreamingHTTPRequest: + """Sent from the HTTP proxy to replicas on the streaming codepath.""" + + def __init__( + self, + asgi_scope: Scope, + *, + proxy_actor_name: Optional[str] = None, + receive_asgi_messages: Optional[ + Callable[[RequestMetadata], Awaitable[bytes]] + ] = None, + ): + self._asgi_scope: Scope = asgi_scope + + if proxy_actor_name is None and receive_asgi_messages is None: + raise ValueError( + "Either proxy_actor_name or receive_asgi_messages must be provided." + ) + + # If receive_asgi_messages is passed, it'll be called directly. + # If proxy_actor_name is passed, the actor will be fetched and its + # `receive_asgi_messages` method will be called. + self._proxy_actor_name: Optional[str] = proxy_actor_name + # Need to keep the actor handle cached to avoid "lost reference to actor" error. + self._cached_proxy_actor: Optional[ActorHandle] = None + self._receive_asgi_messages: Optional[ + Callable[[RequestMetadata], Awaitable[bytes]] + ] = receive_asgi_messages + + @property + def asgi_scope(self) -> Scope: + return self._asgi_scope + + @property + def receive_asgi_messages(self) -> Callable[[RequestMetadata], Awaitable[bytes]]: + if self._receive_asgi_messages is None: + self._cached_proxy_actor = ray.get_actor( + self._proxy_actor_name, namespace=SERVE_NAMESPACE + ) + self._receive_asgi_messages = ( + self._cached_proxy_actor.receive_asgi_messages.remote + ) + + return self._receive_asgi_messages + + +class TargetCapacityDirection(str, Enum): + """Determines what direction the target capacity is scaling.""" + + UP = "UP" + DOWN = "DOWN" + + +@dataclass(frozen=True) +class ReplicaQueueLengthInfo: + accepted: bool + num_ongoing_requests: int + + +@dataclass(frozen=True) +class CreatePlacementGroupRequest: + bundles: List[Dict[str, float]] + strategy: str + target_node_id: str + name: str + runtime_env: Optional[str] = None + + +# This error is used to raise when a by-value DeploymentResponse is converted to an +# ObjectRef. +OBJ_REF_NOT_SUPPORTED_ERROR = RuntimeError( + "Converting by-value DeploymentResponses to ObjectRefs is not supported. " + "Use handle.options(_by_reference=True) to enable it." +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/config.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/config.py new file mode 100644 index 0000000000000000000000000000000000000000..eb633d6fa12d68998e3e8d3bd31af83c2557d0f5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/config.py @@ -0,0 +1,779 @@ +import inspect +import json +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union + +from google.protobuf.descriptor import FieldDescriptor +from google.protobuf.message import Message + +from ray import cloudpickle +from ray._common import ray_option_utils +from ray._common.pydantic_compat import ( + BaseModel, + Field, + NonNegativeFloat, + NonNegativeInt, + PositiveFloat, + PositiveInt, + validator, +) +from ray._common.utils import resources_from_ray_options +from ray._private.serialization import pickle_dumps +from ray.serve._private.constants import ( + DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_S, + DEFAULT_GRACEFUL_SHUTDOWN_WAIT_LOOP_S, + DEFAULT_HEALTH_CHECK_PERIOD_S, + DEFAULT_HEALTH_CHECK_TIMEOUT_S, + DEFAULT_MAX_ONGOING_REQUESTS, + MAX_REPLICAS_PER_NODE_MAX_VALUE, +) +from ray.serve._private.utils import DEFAULT, DeploymentOptionUpdateType +from ray.serve.config import AutoscalingConfig, RequestRouterConfig +from ray.serve.generated.serve_pb2 import ( + AutoscalingConfig as AutoscalingConfigProto, + DeploymentConfig as DeploymentConfigProto, + DeploymentLanguage, + EncodingType as EncodingTypeProto, + LoggingConfig as LoggingConfigProto, + ReplicaConfig as ReplicaConfigProto, + RequestRouterConfig as RequestRouterConfigProto, +) +from ray.util.placement_group import validate_placement_group + + +def _needs_pickle(deployment_language: DeploymentLanguage, is_cross_language: bool): + """From Serve client API's perspective, decide whether pickling is needed.""" + if deployment_language == DeploymentLanguage.PYTHON and not is_cross_language: + # Python client deploying Python replicas. + return True + elif deployment_language == DeploymentLanguage.JAVA and is_cross_language: + # Python client deploying Java replicas, + # using xlang serialization via cloudpickle. + return True + else: + return False + + +def _proto_to_dict(proto: Message) -> Dict: + """Recursively convert a protobuf into a Python dictionary. + + This is an alternative to protobuf's `MessageToDict`. Unlike + `MessageToDict`, this function doesn't add an extra base64 + encoding to bytes when constructing a json response. + """ + data = {} + # Fill data with non-empty fields. + for field, value in proto.ListFields(): + # Handle repeated fields + if field.label == FieldDescriptor.LABEL_REPEATED: + # if we dont do this block the repeated field will be a list of + # `google.protobuf.internal.containers.RepeatedScalarFieldContainer + # Explicitly convert to list + if field.type == FieldDescriptor.TYPE_MESSAGE: + data[field.name] = [ + _proto_to_dict(v) for v in value + ] # Convert each item + else: + data[field.name] = list(value) # Convert to list directly + # Recursively call if the field is another protobuf. + elif field.type == FieldDescriptor.TYPE_MESSAGE: + data[field.name] = _proto_to_dict(value) + else: + data[field.name] = value + + # Fill data default values. + for field in proto.DESCRIPTOR.fields: + if ( + field.name not in data # skip the fields that are already set + and field.type != FieldDescriptor.TYPE_MESSAGE # skip nested messages + and not field.containing_oneof # skip optional fields + ): + data[field.name] = field.default_value + return data + + +class DeploymentConfig(BaseModel): + """Internal datastructure wrapping config options for a deployment. + + Args: + num_replicas: The number of processes to start up that + handles requests to this deployment. Defaults to 1. + max_ongoing_requests: The maximum number of queries + that is sent to a replica of this deployment without receiving + a response. Defaults to 5. + max_queued_requests: Maximum number of requests to this deployment that will be + queued at each *caller* (proxy or DeploymentHandle). Once this limit is + reached, subsequent requests will raise a BackPressureError (for handles) or + return an HTTP 503 status code (for HTTP requests). Defaults to -1 (no + limit). + user_config: Arguments to pass to the reconfigure + method of the deployment. The reconfigure method is called if + user_config is not None. Must be JSON-serializable. + graceful_shutdown_wait_loop_s: Duration + that deployment replicas wait until there is no more work to + be done before shutting down. + graceful_shutdown_timeout_s: Controller waits for this duration + to forcefully kill the replica for shutdown. + health_check_period_s: Frequency at which the controller health + checks replicas. + health_check_timeout_s: Timeout that the controller waits for a + response from the replica's health check before marking it + unhealthy. + autoscaling_config: Autoscaling configuration. + logging_config: Configuration for deployment logs. + user_configured_option_names: The names of options manually + configured by the user. + request_router_config: Configuration for deployment request router. + """ + + num_replicas: Optional[NonNegativeInt] = Field( + default=1, update_type=DeploymentOptionUpdateType.LightWeight + ) + max_ongoing_requests: PositiveInt = Field( + default=DEFAULT_MAX_ONGOING_REQUESTS, + update_type=DeploymentOptionUpdateType.NeedsActorReconfigure, + ) + max_queued_requests: int = Field( + default=-1, + update_type=DeploymentOptionUpdateType.LightWeight, + ) + user_config: Any = Field( + default=None, update_type=DeploymentOptionUpdateType.NeedsActorReconfigure + ) + + graceful_shutdown_timeout_s: NonNegativeFloat = Field( + default=DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_S, + update_type=DeploymentOptionUpdateType.NeedsReconfigure, + ) + graceful_shutdown_wait_loop_s: NonNegativeFloat = Field( + default=DEFAULT_GRACEFUL_SHUTDOWN_WAIT_LOOP_S, + update_type=DeploymentOptionUpdateType.NeedsActorReconfigure, + ) + + health_check_period_s: PositiveFloat = Field( + default=DEFAULT_HEALTH_CHECK_PERIOD_S, + update_type=DeploymentOptionUpdateType.NeedsReconfigure, + ) + health_check_timeout_s: PositiveFloat = Field( + default=DEFAULT_HEALTH_CHECK_TIMEOUT_S, + update_type=DeploymentOptionUpdateType.NeedsReconfigure, + ) + + autoscaling_config: Optional[AutoscalingConfig] = Field( + default=None, update_type=DeploymentOptionUpdateType.NeedsActorReconfigure + ) + + request_router_config: RequestRouterConfig = Field( + default=RequestRouterConfig(), + update_type=DeploymentOptionUpdateType.NeedsActorReconfigure, + ) + + # This flag is used to let replica know they are deployed from + # a different language. + is_cross_language: bool = False + + # This flag is used to let controller know which language does + # the deployment use. + deployment_language: Any = DeploymentLanguage.PYTHON + + version: Optional[str] = Field( + default=None, + update_type=DeploymentOptionUpdateType.HeavyWeight, + ) + + logging_config: Optional[dict] = Field( + default=None, + update_type=DeploymentOptionUpdateType.NeedsActorReconfigure, + ) + + # Contains the names of deployment options manually set by the user + user_configured_option_names: Set[str] = set() + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + @validator("user_config", always=True) + def user_config_json_serializable(cls, v): + if isinstance(v, bytes): + return v + if v is not None: + try: + json.dumps(v) + except TypeError as e: + raise ValueError(f"user_config is not JSON-serializable: {str(e)}.") + + return v + + @validator("logging_config", always=True) + def logging_config_valid(cls, v): + if v is None: + return v + if not isinstance(v, dict): + raise TypeError( + f"Got invalid type '{type(v)}' for logging_config. " + "Expected a dictionary." + ) + # Handle default value + from ray.serve.schema import LoggingConfig + + v = LoggingConfig(**v).dict() + return v + + @validator("max_queued_requests", always=True) + def validate_max_queued_requests(cls, v): + if not isinstance(v, int): + raise TypeError("max_queued_requests must be an integer.") + + if v < 1 and v != -1: + raise ValueError( + "max_queued_requests must be -1 (no limit) or a positive integer." + ) + + return v + + def needs_pickle(self): + return _needs_pickle(self.deployment_language, self.is_cross_language) + + def to_proto(self): + data = self.dict() + if data.get("user_config") is not None: + if self.needs_pickle(): + data["user_config"] = cloudpickle.dumps(data["user_config"]) + if data.get("autoscaling_config"): + data["autoscaling_config"] = AutoscalingConfigProto( + **data["autoscaling_config"] + ) + if data.get("request_router_config"): + router_kwargs = data["request_router_config"].get("request_router_kwargs") + if router_kwargs is not None: + if not router_kwargs: + data["request_router_config"]["request_router_kwargs"] = b"" + elif self.needs_pickle(): + # Protobuf requires bytes, so we need to pickle + data["request_router_config"][ + "request_router_kwargs" + ] = cloudpickle.dumps(router_kwargs) + else: + raise ValueError( + "Non-empty request_router_kwargs not supported" + f"for cross-language deployments. Got: {router_kwargs}" + ) + data["request_router_config"] = RequestRouterConfigProto( + **data["request_router_config"] + ) + if data.get("logging_config"): + if "encoding" in data["logging_config"]: + data["logging_config"]["encoding"] = EncodingTypeProto.Value( + data["logging_config"]["encoding"] + ) + data["logging_config"] = LoggingConfigProto(**data["logging_config"]) + data["user_configured_option_names"] = list( + data["user_configured_option_names"] + ) + return DeploymentConfigProto(**data) + + def to_proto_bytes(self): + return self.to_proto().SerializeToString() + + @classmethod + def from_proto(cls, proto: DeploymentConfigProto): + data = _proto_to_dict(proto) + deployment_language = ( + data["deployment_language"] + if "deployment_language" in data + else DeploymentLanguage.PYTHON + ) + is_cross_language = ( + data["is_cross_language"] if "is_cross_language" in data else False + ) + needs_pickle = _needs_pickle(deployment_language, is_cross_language) + if "user_config" in data: + if data["user_config"] != b"": + if needs_pickle: + data["user_config"] = cloudpickle.loads(proto.user_config) + else: + data["user_config"] = proto.user_config + else: + data["user_config"] = None + if "request_router_config" in data: + if "request_router_kwargs" in data["request_router_config"]: + request_router_kwargs = data["request_router_config"][ + "request_router_kwargs" + ] + if request_router_kwargs != b"": + if needs_pickle: + data["request_router_config"][ + "request_router_kwargs" + ] = cloudpickle.loads( + proto.request_router_config.request_router_kwargs + ) + else: + data["request_router_config"][ + "request_router_kwargs" + ] = proto.request_router_config.request_router_kwargs + else: + data["request_router_config"]["request_router_kwargs"] = {} + + data["request_router_config"] = RequestRouterConfig( + **data["request_router_config"] + ) + if "autoscaling_config" in data: + if not data["autoscaling_config"].get("upscale_smoothing_factor"): + data["autoscaling_config"]["upscale_smoothing_factor"] = None + if not data["autoscaling_config"].get("downscale_smoothing_factor"): + data["autoscaling_config"]["downscale_smoothing_factor"] = None + if not data["autoscaling_config"].get("upscaling_factor"): + data["autoscaling_config"]["upscaling_factor"] = None + if not data["autoscaling_config"].get("downscaling_factor"): + data["autoscaling_config"]["downscaling_factor"] = None + if not data["autoscaling_config"].get("target_ongoing_requests"): + data["autoscaling_config"]["target_ongoing_requests"] = None + data["autoscaling_config"] = AutoscalingConfig(**data["autoscaling_config"]) + if "version" in data: + if data["version"] == "": + data["version"] = None + if "user_configured_option_names" in data: + data["user_configured_option_names"] = set( + data["user_configured_option_names"] + ) + if "logging_config" in data: + if "encoding" in data["logging_config"]: + data["logging_config"]["encoding"] = EncodingTypeProto.Name( + data["logging_config"]["encoding"] + ) + + return cls(**data) + + @classmethod + def from_proto_bytes(cls, proto_bytes: bytes): + proto = DeploymentConfigProto.FromString(proto_bytes) + return cls.from_proto(proto) + + @classmethod + def from_default(cls, **kwargs): + """Creates a default DeploymentConfig and overrides it with kwargs. + + Ignores any kwargs set to DEFAULT.VALUE. + + Raises: + TypeError: when a keyword that's not an argument to the class is + passed in. + """ + + config = cls() + valid_config_options = set(config.dict().keys()) + + # Friendly error if a non-DeploymentConfig kwarg was passed in + for key, val in kwargs.items(): + if key not in valid_config_options: + raise TypeError( + f'Got invalid Deployment config option "{key}" ' + f"(with value {val}) as keyword argument. All Deployment " + "config options must come from this list: " + f"{list(valid_config_options)}." + ) + + kwargs = {key: val for key, val in kwargs.items() if val != DEFAULT.VALUE} + + for key, val in kwargs.items(): + config.__setattr__(key, val) + + return config + + +def handle_num_replicas_auto( + max_ongoing_requests: Union[int, DEFAULT], + autoscaling_config: Optional[Union[Dict, AutoscalingConfig, DEFAULT]], +): + """Return modified `max_ongoing_requests` and `autoscaling_config` + for when num_replicas="auto". + + If `autoscaling_config` is unspecified, returns the modified value + AutoscalingConfig.default(). + If it is specified, the specified fields in `autoscaling_config` + override that of AutoscalingConfig.default(). + """ + + if autoscaling_config in [DEFAULT.VALUE, None]: + # If autoscaling config wasn't specified, use default + # configuration + autoscaling_config = AutoscalingConfig.default() + else: + # If autoscaling config was specified, values specified in + # autoscaling config overrides the default configuration + default_config = AutoscalingConfig.default().dict(exclude_unset=True) + autoscaling_config = ( + autoscaling_config + if isinstance(autoscaling_config, dict) + else autoscaling_config.dict(exclude_unset=True) + ) + default_config.update(autoscaling_config) + autoscaling_config = AutoscalingConfig(**default_config) + + return max_ongoing_requests, autoscaling_config + + +class ReplicaConfig: + """Internal datastructure wrapping config options for a deployment's replicas. + + Provides five main properties (see property docstrings for more info): + deployment_def: the code, or a reference to the code, that this + replica should run. + init_args: the deployment_def's init_args. + init_kwargs: the deployment_def's init_kwargs. + ray_actor_options: the Ray actor options to pass into the replica's + actor. + resource_dict: contains info on this replica's actor's resource needs. + + Offers a serialized equivalent (e.g. serialized_deployment_def) for + deployment_def, init_args, and init_kwargs. Deserializes these properties + when they're first accessed, if they were not passed in directly through + create(). + + Use the classmethod create() to make a ReplicaConfig with the deserialized + properties. + + Note: overwriting or setting any property after the ReplicaConfig has been + constructed is currently undefined behavior. The config's fields should not + be modified externally after it is created. + """ + + def __init__( + self, + deployment_def_name: str, + serialized_deployment_def: bytes, + serialized_init_args: bytes, + serialized_init_kwargs: bytes, + ray_actor_options: Dict, + placement_group_bundles: Optional[List[Dict[str, float]]] = None, + placement_group_strategy: Optional[str] = None, + max_replicas_per_node: Optional[int] = None, + needs_pickle: bool = True, + ): + """Construct a ReplicaConfig with serialized properties. + + All parameters are required. See classmethod create() for defaults. + """ + self.deployment_def_name = deployment_def_name + + # Store serialized versions of code properties. + self.serialized_deployment_def = serialized_deployment_def + self.serialized_init_args = serialized_init_args + self.serialized_init_kwargs = serialized_init_kwargs + + # Deserialize properties when first accessed. See @property methods. + self._deployment_def = None + self._init_args = None + self._init_kwargs = None + + # Configure ray_actor_options. These are the Ray options ultimately + # passed into the replica's actor when it's created. + self.ray_actor_options = ray_actor_options + + self.placement_group_bundles = placement_group_bundles + self.placement_group_strategy = placement_group_strategy + + self.max_replicas_per_node = max_replicas_per_node + + self._validate() + + # Create resource_dict. This contains info about the replica's resource + # needs. It does NOT set the replica's resource usage. That's done by + # the ray_actor_options. + self.resource_dict = resources_from_ray_options(self.ray_actor_options) + self.needs_pickle = needs_pickle + + def _validate(self): + self._validate_ray_actor_options() + self._validate_placement_group_options() + self._validate_max_replicas_per_node() + + if ( + self.max_replicas_per_node is not None + and self.placement_group_bundles is not None + ): + raise ValueError( + "Setting max_replicas_per_node is not allowed when " + "placement_group_bundles is provided." + ) + + def update( + self, + ray_actor_options: dict, + placement_group_bundles: Optional[List[Dict[str, float]]] = None, + placement_group_strategy: Optional[str] = None, + max_replicas_per_node: Optional[int] = None, + ): + self.ray_actor_options = ray_actor_options + + self.placement_group_bundles = placement_group_bundles + self.placement_group_strategy = placement_group_strategy + + self.max_replicas_per_node = max_replicas_per_node + + self._validate() + + self.resource_dict = resources_from_ray_options(self.ray_actor_options) + + @classmethod + def create( + cls, + deployment_def: Union[Callable, str], + init_args: Optional[Tuple[Any]] = None, + init_kwargs: Optional[Dict[Any, Any]] = None, + ray_actor_options: Optional[Dict] = None, + placement_group_bundles: Optional[List[Dict[str, float]]] = None, + placement_group_strategy: Optional[str] = None, + max_replicas_per_node: Optional[int] = None, + deployment_def_name: Optional[str] = None, + ): + """Create a ReplicaConfig from deserialized parameters.""" + + if not callable(deployment_def) and not isinstance(deployment_def, str): + raise TypeError("@serve.deployment must be called on a class or function.") + + if not (init_args is None or isinstance(init_args, (tuple, list))): + raise TypeError("init_args must be a tuple.") + + if not (init_kwargs is None or isinstance(init_kwargs, dict)): + raise TypeError("init_kwargs must be a dict.") + + if inspect.isfunction(deployment_def): + if init_args: + raise ValueError("init_args not supported for function deployments.") + elif init_kwargs: + raise ValueError("init_kwargs not supported for function deployments.") + + if not isinstance(deployment_def, (Callable, str)): + raise TypeError( + f'Got invalid type "{type(deployment_def)}" for ' + "deployment_def. Expected deployment_def to be a " + "class, function, or string." + ) + # Set defaults + if init_args is None: + init_args = () + if init_kwargs is None: + init_kwargs = {} + if ray_actor_options is None: + ray_actor_options = {} + if deployment_def_name is None: + if isinstance(deployment_def, str): + deployment_def_name = deployment_def + else: + deployment_def_name = deployment_def.__name__ + + config = cls( + deployment_def_name, + pickle_dumps( + deployment_def, + f"Could not serialize the deployment {repr(deployment_def)}", + ), + pickle_dumps(init_args, "Could not serialize the deployment init args"), + pickle_dumps(init_kwargs, "Could not serialize the deployment init kwargs"), + ray_actor_options, + placement_group_bundles, + placement_group_strategy, + max_replicas_per_node, + ) + + config._deployment_def = deployment_def + config._init_args = init_args + config._init_kwargs = init_kwargs + + return config + + def _validate_ray_actor_options(self): + if not isinstance(self.ray_actor_options, dict): + raise TypeError( + f'Got invalid type "{type(self.ray_actor_options)}" for ' + "ray_actor_options. Expected a dictionary." + ) + # Please keep this in sync with the docstring for the ray_actor_options + # kwarg in api.py. + allowed_ray_actor_options = { + # Resource options + "accelerator_type", + "memory", + "num_cpus", + "num_gpus", + "resources", + # Other options + "runtime_env", + } + + for option in self.ray_actor_options: + if option not in allowed_ray_actor_options: + raise ValueError( + f"Specifying '{option}' in ray_actor_options is not allowed. " + f"Allowed options: {allowed_ray_actor_options}" + ) + ray_option_utils.validate_actor_options(self.ray_actor_options, in_options=True) + + # Set Serve replica defaults + if self.ray_actor_options.get("num_cpus") is None: + self.ray_actor_options["num_cpus"] = 1 + + def _validate_max_replicas_per_node(self) -> None: + if self.max_replicas_per_node is None: + return + if not isinstance(self.max_replicas_per_node, int): + raise TypeError( + f"Get invalid type '{type(self.max_replicas_per_node)}' for " + "max_replicas_per_node. Expected None or an integer " + f"in the range of [1, {MAX_REPLICAS_PER_NODE_MAX_VALUE}]." + ) + if ( + self.max_replicas_per_node < 1 + or self.max_replicas_per_node > MAX_REPLICAS_PER_NODE_MAX_VALUE + ): + raise ValueError( + f"Invalid max_replicas_per_node {self.max_replicas_per_node}. " + "Valid values are None or an integer " + f"in the range of [1, {MAX_REPLICAS_PER_NODE_MAX_VALUE}]." + ) + + def _validate_placement_group_options(self) -> None: + if self.placement_group_strategy is not None: + if self.placement_group_bundles is None: + raise ValueError( + "If `placement_group_strategy` is provided, " + "`placement_group_bundles` must also be provided." + ) + + if self.placement_group_bundles is not None: + validate_placement_group( + bundles=self.placement_group_bundles, + strategy=self.placement_group_strategy or "PACK", + lifetime="detached", + ) + + resource_error_prefix = ( + "When using `placement_group_bundles`, the replica actor " + "will be placed in the first bundle, so the resource " + "requirements for the actor must be a subset of the first " + "bundle." + ) + + first_bundle = self.placement_group_bundles[0] + + # Validate that the replica actor fits in the first bundle. + bundle_cpu = first_bundle.get("CPU", 0) + replica_actor_num_cpus = self.ray_actor_options.get("num_cpus", 0) + if bundle_cpu < replica_actor_num_cpus: + raise ValueError( + f"{resource_error_prefix} `num_cpus` for the actor is " + f"{replica_actor_num_cpus}, but the bundle only has " + f"{bundle_cpu} `CPU` specified." + ) + + bundle_gpu = first_bundle.get("GPU", 0) + replica_actor_num_gpus = self.ray_actor_options.get("num_gpus", 0) + if bundle_gpu < replica_actor_num_gpus: + raise ValueError( + f"{resource_error_prefix} `num_gpus` for the actor is " + f"{replica_actor_num_gpus}, but the bundle only has " + f"{bundle_gpu} `GPU` specified." + ) + + replica_actor_resources = self.ray_actor_options.get("resources", {}) + for actor_resource, actor_value in replica_actor_resources.items(): + bundle_value = first_bundle.get(actor_resource, 0) + if bundle_value < actor_value: + raise ValueError( + f"{resource_error_prefix} `{actor_resource}` requirement " + f"for the actor is {actor_value}, but the bundle only " + f"has {bundle_value} `{actor_resource}` specified." + ) + + @property + def deployment_def(self) -> Union[Callable, str]: + """The code, or a reference to the code, that this replica runs. + + For Python replicas, this can be one of the following: + - Function (Callable) + - Class (Callable) + - Import path (str) + + For Java replicas, this can be one of the following: + - Class path (str) + """ + if self._deployment_def is None: + if self.needs_pickle: + self._deployment_def = cloudpickle.loads(self.serialized_deployment_def) + else: + self._deployment_def = self.serialized_deployment_def.decode( + encoding="utf-8" + ) + + return self._deployment_def + + @property + def init_args(self) -> Optional[Union[Tuple[Any], bytes]]: + """The init_args for a Python class. + + This property is only meaningful if deployment_def is a Python class. + Otherwise, it is None. + """ + if self._init_args is None: + if self.needs_pickle: + self._init_args = cloudpickle.loads(self.serialized_init_args) + else: + self._init_args = self.serialized_init_args + + return self._init_args + + @property + def init_kwargs(self) -> Optional[Tuple[Any]]: + """The init_kwargs for a Python class. + + This property is only meaningful if deployment_def is a Python class. + Otherwise, it is None. + """ + + if self._init_kwargs is None: + self._init_kwargs = cloudpickle.loads(self.serialized_init_kwargs) + + return self._init_kwargs + + @classmethod + def from_proto(cls, proto: ReplicaConfigProto, needs_pickle: bool = True): + return ReplicaConfig( + proto.deployment_def_name, + proto.deployment_def, + proto.init_args if proto.init_args != b"" else None, + proto.init_kwargs if proto.init_kwargs != b"" else None, + json.loads(proto.ray_actor_options), + json.loads(proto.placement_group_bundles) + if proto.placement_group_bundles + else None, + proto.placement_group_strategy + if proto.placement_group_strategy != "" + else None, + proto.max_replicas_per_node if proto.max_replicas_per_node else None, + needs_pickle, + ) + + @classmethod + def from_proto_bytes(cls, proto_bytes: bytes, needs_pickle: bool = True): + proto = ReplicaConfigProto.FromString(proto_bytes) + return cls.from_proto(proto, needs_pickle) + + def to_proto(self): + return ReplicaConfigProto( + deployment_def_name=self.deployment_def_name, + deployment_def=self.serialized_deployment_def, + init_args=self.serialized_init_args, + init_kwargs=self.serialized_init_kwargs, + ray_actor_options=json.dumps(self.ray_actor_options), + placement_group_bundles=json.dumps(self.placement_group_bundles) + if self.placement_group_bundles is not None + else "", + placement_group_strategy=self.placement_group_strategy, + max_replicas_per_node=self.max_replicas_per_node + if self.max_replicas_per_node is not None + else 0, + ) + + def to_proto_bytes(self): + return self.to_proto().SerializeToString() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/constants.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..dd46f0c6c20c38f2106205503b0f751c006b1281 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/constants.py @@ -0,0 +1,466 @@ +from typing import List + +from ray.serve._private.constants_utils import ( + get_env_bool, + get_env_float, + get_env_float_non_negative, + get_env_float_non_zero_with_warning, + get_env_int, + get_env_int_positive, + get_env_str, + parse_latency_buckets, + str_to_list, +) + +#: Logger used by serve components +SERVE_LOGGER_NAME = "ray.serve" + +#: Actor name used to register controller +SERVE_CONTROLLER_NAME = "SERVE_CONTROLLER_ACTOR" + +#: Actor name used to register HTTP proxy actor +SERVE_PROXY_NAME = "SERVE_PROXY_ACTOR" + +#: Ray namespace used for all Serve actors +SERVE_NAMESPACE = "serve" + +#: HTTP Host +DEFAULT_HTTP_HOST = get_env_str("RAY_SERVE_DEFAULT_HTTP_HOST", "127.0.0.1") + +#: HTTP Port +DEFAULT_HTTP_PORT = get_env_int("RAY_SERVE_DEFAULT_HTTP_PORT", 8000) + +#: Uvicorn timeout_keep_alive Config +DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S = 90 + +#: gRPC Port +DEFAULT_GRPC_PORT = get_env_int("RAY_SERVE_DEFAULT_GRPC_PORT", 9000) + +#: Default Serve application name +SERVE_DEFAULT_APP_NAME = "default" + +#: Max concurrency +ASYNC_CONCURRENCY = int(1e6) + +# How long to sleep between control loop cycles on the controller. +CONTROL_LOOP_INTERVAL_S = get_env_float_non_negative( + "RAY_SERVE_CONTROL_LOOP_INTERVAL_S", 0.1 +) + +#: Max time to wait for HTTP proxy in `serve.start()`. +HTTP_PROXY_TIMEOUT = 60 + +#: Max retry count for allowing failures in replica constructor. +#: If no replicas at target version is running by the time we're at +#: max construtor retry count, deploy() is considered failed. +#: By default we set threshold as min(num_replicas * 3, this value) +MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT = get_env_int( + "MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT", 20 +) + +# Max retry on deployment constructor is +# min(num_replicas * MAX_PER_REPLICA_RETRY_COUNT, MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT) +MAX_PER_REPLICA_RETRY_COUNT = get_env_int("MAX_PER_REPLICA_RETRY_COUNT", 3) + +# If you are wondering why we are using histogram buckets, please refer to +# https://prometheus.io/docs/practices/histograms/ +# short answer is that its cheaper to calculate percentiles on the histogram +# than to calculate them on raw data, both in terms of time and space. + +#: Default histogram buckets for latency tracker. +DEFAULT_LATENCY_BUCKET_MS = [ + 1, + 2, + 5, + 10, + 20, + 50, + 100, + 200, + 300, + 400, + 500, + 1000, + 2000, + # 5 seconds + 5000, + # 10 seconds + 10000, + # 60 seconds + 60000, + # 2min + 120000, + # 5 min + 300000, + # 10 min + 600000, +] + +# Example usage: +# RAY_SERVE_REQUEST_LATENCY_BUCKET_MS="1,2,3,4" +# RAY_SERVE_MODEL_LOAD_LATENCY_BUCKET_MS="1,2,3,4" +#: Histogram buckets for request latency. +REQUEST_LATENCY_BUCKETS_MS = parse_latency_buckets( + get_env_str("REQUEST_LATENCY_BUCKETS_MS", ""), DEFAULT_LATENCY_BUCKET_MS +) +#: Histogram buckets for model load/unload latency. +MODEL_LOAD_LATENCY_BUCKETS_MS = parse_latency_buckets( + get_env_str("MODEL_LOAD_LATENCY_BUCKETS_MS", ""), DEFAULT_LATENCY_BUCKET_MS +) + +#: Name of deployment health check method implemented by user. +HEALTH_CHECK_METHOD = "check_health" + +#: Name of deployment reconfiguration method implemented by user. +RECONFIGURE_METHOD = "reconfigure" + +SERVE_ROOT_URL_ENV_KEY = "RAY_SERVE_ROOT_URL" + +#: Limit the number of cached handles because each handle has long poll +#: overhead. See https://github.com/ray-project/ray/issues/18980 +MAX_CACHED_HANDLES = get_env_int_positive("MAX_CACHED_HANDLES", 100) + +#: Because ServeController will accept one long poll request per handle, its +#: concurrency needs to scale as O(num_handles) +CONTROLLER_MAX_CONCURRENCY = get_env_int_positive("CONTROLLER_MAX_CONCURRENCY", 15_000) + +DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_S = 20 +DEFAULT_GRACEFUL_SHUTDOWN_WAIT_LOOP_S = 2 +DEFAULT_HEALTH_CHECK_PERIOD_S = 10 +DEFAULT_HEALTH_CHECK_TIMEOUT_S = 30 +DEFAULT_MAX_ONGOING_REQUESTS = 5 +DEFAULT_TARGET_ONGOING_REQUESTS = 2 + +# HTTP Proxy health check configs +PROXY_HEALTH_CHECK_TIMEOUT_S = get_env_float_non_zero_with_warning( + "RAY_SERVE_PROXY_HEALTH_CHECK_TIMEOUT_S", 10.0 +) + +PROXY_HEALTH_CHECK_PERIOD_S = get_env_float_non_zero_with_warning( + "RAY_SERVE_PROXY_HEALTH_CHECK_PERIOD_S", 10.0 +) +PROXY_READY_CHECK_TIMEOUT_S = get_env_float_non_zero_with_warning( + "RAY_SERVE_PROXY_READY_CHECK_TIMEOUT_S", 5.0 +) + +# Number of times in a row that a HTTP proxy must fail the health check before +# being marked unhealthy. +PROXY_HEALTH_CHECK_UNHEALTHY_THRESHOLD = 3 + +# The minimum drain period for a HTTP proxy. +PROXY_MIN_DRAINING_PERIOD_S = get_env_float_non_zero_with_warning( + "RAY_SERVE_PROXY_MIN_DRAINING_PERIOD_S", 30.0 +) +# The time in seconds that the http proxy state waits before +# rechecking whether the proxy actor is drained or not. +PROXY_DRAIN_CHECK_PERIOD_S = 5 + +#: Number of times in a row that a replica must fail the health check before +#: being marked unhealthy. +REPLICA_HEALTH_CHECK_UNHEALTHY_THRESHOLD = 3 + +# The time in seconds that the Serve client waits before rechecking deployment state +CLIENT_POLLING_INTERVAL_S = 1.0 + +# The time in seconds that the Serve client waits before checking if +# deployment has been created +CLIENT_CHECK_CREATION_POLLING_INTERVAL_S = 0.1 + +# Timeout for GCS internal KV service +RAY_SERVE_KV_TIMEOUT_S = get_env_float_non_zero_with_warning( + "RAY_SERVE_KV_TIMEOUT_S", None +) + +# Timeout for GCS RPC request +RAY_GCS_RPC_TIMEOUT_S = 3.0 + +# Maximum duration to wait until broadcasting a long poll update if there are +# still replicas in the RECOVERING state. +RECOVERING_LONG_POLL_BROADCAST_TIMEOUT_S = 10.0 + +# Minimum duration to wait until broadcasting model IDs. +PUSH_MULTIPLEXED_MODEL_IDS_INTERVAL_S = 0.1 + +# Deprecation message for V1 migrations. +MIGRATION_MESSAGE = ( + "See https://docs.ray.io/en/latest/serve/index.html for more information." +) + +# Environment variable name for to specify the encoding of the log messages +RAY_SERVE_LOG_ENCODING = get_env_str("RAY_SERVE_LOG_ENCODING", "TEXT") + +# Jsonify the log messages. This constant is deprecated and will be removed in the +# future. Use RAY_SERVE_LOG_ENCODING or 'LoggingConfig' to enable json format. +RAY_SERVE_ENABLE_JSON_LOGGING = get_env_bool("RAY_SERVE_ENABLE_JSON_LOGGING", "0") + +# Setting RAY_SERVE_LOG_TO_STDERR=0 will disable logging to the stdout and stderr. +# Also, redirect them to serve's log files. +RAY_SERVE_LOG_TO_STDERR = get_env_bool("RAY_SERVE_LOG_TO_STDERR", "1") + +# Logging format attributes +SERVE_LOG_REQUEST_ID = "request_id" +SERVE_LOG_ROUTE = "route" +SERVE_LOG_APPLICATION = "application" +SERVE_LOG_DEPLOYMENT = "deployment" +SERVE_LOG_REPLICA = "replica" +SERVE_LOG_COMPONENT = "component_name" +SERVE_LOG_COMPONENT_ID = "component_id" +SERVE_LOG_MESSAGE = "message" +# This is a reserved for python logging module attribute, it should not be changed. +SERVE_LOG_LEVEL_NAME = "levelname" +SERVE_LOG_TIME = "asctime" + +# Logging format with record key to format string dict +SERVE_LOG_RECORD_FORMAT = { + SERVE_LOG_REQUEST_ID: "%(request_id)s", + SERVE_LOG_APPLICATION: "%(application)s", + SERVE_LOG_MESSAGE: "-- %(message)s", + SERVE_LOG_LEVEL_NAME: "%(levelname)s", + SERVE_LOG_TIME: "%(asctime)s", +} + +# There are some attributes that we only use internally or don't provide values to the +# users. Adding to this set will remove them from structured logs. +SERVE_LOG_UNWANTED_ATTRS = { + "serve_access_log", + "task_id", + "job_id", + "skip_context_filter", +} + +RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S = get_env_int( + "RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S", 0 +) + +RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S = ( + get_env_float("RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S", 0.0) + or get_env_float("SERVE_REQUEST_PROCESSING_TIMEOUT_S", 0.0) + or None +) + +SERVE_LOG_EXTRA_FIELDS = "ray_serve_extra_fields" + +# Serve HTTP request header key for routing requests. +SERVE_MULTIPLEXED_MODEL_ID = "serve_multiplexed_model_id" + +# HTTP request ID +SERVE_HTTP_REQUEST_ID_HEADER = "x-request-id" + +# Feature flag to turn on node locality routing for proxies. On by default. +RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING = get_env_bool( + "RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING", "1" +) + +# Feature flag to turn on AZ locality routing for proxies. On by default. +RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING = get_env_bool( + "RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING", "1" +) + +# Serve HTTP proxy callback import path. +RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH = get_env_str( + "RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH", None +) +# Serve controller callback import path. +RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH = get_env_str( + "RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH", None +) + +# How often autoscaling metrics are recorded on Serve replicas. +RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_INTERVAL_S = get_env_float( + "RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_INTERVAL_S", 0.5 +) + +# Replica autoscaling metrics push interval. +RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PUSH_INTERVAL_S = get_env_float( + "RAY_SERVE_REPLICA_AUTOSCALING_METRIC_PUSH_INTERVAL_S", 10.0 +) + +# How often autoscaling metrics are recorded on Serve handles. +RAY_SERVE_HANDLE_AUTOSCALING_METRIC_RECORD_INTERVAL_S = get_env_float( + "RAY_SERVE_HANDLE_AUTOSCALING_METRIC_RECORD_INTERVAL_S", 0.5 +) + +# Handle autoscaling metrics push interval. (This interval will affect the cold start time period) +RAY_SERVE_HANDLE_AUTOSCALING_METRIC_PUSH_INTERVAL_S = get_env_float( + "RAY_SERVE_HANDLE_AUTOSCALING_METRIC_PUSH_INTERVAL_S", + # Legacy env var for RAY_SERVE_HANDLE_AUTOSCALING_METRIC_PUSH_INTERVAL_S + get_env_float("RAY_SERVE_HANDLE_METRIC_PUSH_INTERVAL_S", 10.0), +) + +# Serve multiplexed matching timeout. +# This is the timeout for the matching process of multiplexed requests. To avoid +# thundering herd problem, the timeout value will be randomed between this value +# and this value * 2. The unit is second. +# If the matching process takes longer than the timeout, the request will be +# fallen to the default routing strategy. +RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S = get_env_float( + "RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S", 1.0 +) + +# Enable memray in all Serve actors. +RAY_SERVE_ENABLE_MEMORY_PROFILING = get_env_bool( + "RAY_SERVE_ENABLE_MEMORY_PROFILING", "0" +) + +# Max value allowed for max_replicas_per_node option. +# TODO(jjyao) the <= 100 limitation is an artificial one +# and is due to the fact that Ray core only supports resource +# precision up to 0.0001. +# This limitation should be lifted in the long term. +MAX_REPLICAS_PER_NODE_MAX_VALUE = 100 + +# Argument name for passing in the gRPC context into a replica. +GRPC_CONTEXT_ARG_NAME = "grpc_context" + +# Whether or not to forcefully kill replicas that fail health checks. +RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS = get_env_bool( + "RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS", "0" +) + +# Initial deadline for queue length responses in the router. +RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S = get_env_float( + "RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S", 0.1 +) + +# Maximum deadline for queue length responses in the router (in backoff). +RAY_SERVE_MAX_QUEUE_LENGTH_RESPONSE_DEADLINE_S = get_env_float( + "RAY_SERVE_MAX_QUEUE_LENGTH_RESPONSE_DEADLINE_S", 1.0 +) + +# Length of time to respect entries in the queue length cache when routing requests. +RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S = get_env_float( + "RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S", 10.0 +) + +# Backoff seconds when choosing router failed, backoff time is calculated as +# initial_backoff_s * backoff_multiplier ** attempt. +# The default backoff time is [0, 0.025, 0.05, 0.1, 0.2, 0.4, 0.5, 0.5 ... ]. +RAY_SERVE_ROUTER_RETRY_INITIAL_BACKOFF_S = get_env_float( + "RAY_SERVE_ROUTER_RETRY_INITIAL_BACKOFF_S", 0.025 +) +RAY_SERVE_ROUTER_RETRY_BACKOFF_MULTIPLIER = get_env_int( + "RAY_SERVE_ROUTER_RETRY_BACKOFF_MULTIPLIER", 2 +) +RAY_SERVE_ROUTER_RETRY_MAX_BACKOFF_S = get_env_float( + "RAY_SERVE_ROUTER_RETRY_MAX_BACKOFF_S", 0.5 +) + +# The default autoscaling policy to use if none is specified. +DEFAULT_AUTOSCALING_POLICY_NAME = ( + "ray.serve.autoscaling_policy:default_autoscaling_policy" +) + +# Feature flag to enable collecting all queued and ongoing request +# metrics at handles instead of replicas. ON by default. +RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE = get_env_bool( + "RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE", "1" +) + +RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S = get_env_float( + "RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S", 10.0 +) + +# Feature flag to always run a proxy on the head node even if it has no replicas. +RAY_SERVE_ALWAYS_RUN_PROXY_ON_HEAD_NODE = get_env_bool( + "RAY_SERVE_ALWAYS_RUN_PROXY_ON_HEAD_NODE", "1" +) + +# Default is 2GiB, the max for a signed int. +RAY_SERVE_GRPC_MAX_MESSAGE_SIZE = get_env_int( + "RAY_SERVE_GRPC_MAX_MESSAGE_SIZE", (2 * 1024 * 1024 * 1024) - 1 +) + +# Default options passed when constructing gRPC servers. +DEFAULT_GRPC_SERVER_OPTIONS = [ + ("grpc.max_send_message_length", RAY_SERVE_GRPC_MAX_MESSAGE_SIZE), + ("grpc.max_receive_message_length", RAY_SERVE_GRPC_MAX_MESSAGE_SIZE), +] + +# Timeout for gracefully shutting down metrics pusher, e.g. in routers or replicas +METRICS_PUSHER_GRACEFUL_SHUTDOWN_TIMEOUT_S = 10 + +# Feature flag to set `enable_task_events=True` on Serve-managed actors. +RAY_SERVE_ENABLE_TASK_EVENTS = get_env_bool("RAY_SERVE_ENABLE_TASK_EVENTS", "0") + +# Use compact instead of spread scheduling strategy +RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY = get_env_bool( + "RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY", "0" +) + +# Comma-separated list of custom resources prioritized in scheduling. Sorted from highest to lowest priority. +# Example: "customx,customy" +RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES: List[str] = str_to_list( + get_env_str("RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES", "") +) + +# Feature flag to always override local_testing_mode to True in serve.run. +# This is used for internal testing to avoid passing the flag to every invocation. +RAY_SERVE_FORCE_LOCAL_TESTING_MODE = get_env_bool( + "RAY_SERVE_FORCE_LOCAL_TESTING_MODE", "0" +) + +# Run sync methods defined in the replica in a thread pool by default. +RAY_SERVE_RUN_SYNC_IN_THREADPOOL = get_env_bool("RAY_SERVE_RUN_SYNC_IN_THREADPOOL", "0") + +RAY_SERVE_RUN_SYNC_IN_THREADPOOL_WARNING = ( + "Calling sync method '{method_name}' directly on the " + "asyncio loop. In a future version, sync methods will be run in a " + "threadpool by default. Ensure your sync methods are thread safe " + "or keep the existing behavior by making them `async def`. Opt " + "into the new behavior by setting " + "RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1." +) + +# Feature flag to turn off GC optimizations in the proxy (in case there is a +# memory leak or negative performance impact). +RAY_SERVE_ENABLE_PROXY_GC_OPTIMIZATIONS = get_env_bool( + "RAY_SERVE_ENABLE_PROXY_GC_OPTIMIZATIONS", "1" +) + +# Used for gc.set_threshold() when proxy GC optimizations are enabled. +RAY_SERVE_PROXY_GC_THRESHOLD = get_env_int("RAY_SERVE_PROXY_GC_THRESHOLD", 10_000) + +# Interval at which cached metrics will be exported using the Ray metric API. +# Set to `0` to disable caching entirely. +RAY_SERVE_METRICS_EXPORT_INTERVAL_MS = get_env_int( + "RAY_SERVE_METRICS_EXPORT_INTERVAL_MS", 100 +) + +# The default request router class to use if none is specified. +DEFAULT_REQUEST_ROUTER_PATH = ( + "ray.serve._private.request_router:PowerOfTwoChoicesRequestRouter" +) + +# The default request routing period to use if none is specified. +DEFAULT_REQUEST_ROUTING_STATS_PERIOD_S = 10 + +# The default request routing timeout to use if none is specified. +DEFAULT_REQUEST_ROUTING_STATS_TIMEOUT_S = 30 + +# Name of deployment request routing stats method implemented by user. +REQUEST_ROUTING_STATS_METHOD = "record_routing_stats" + +# By default, we run user code in a separate event loop. +# This flag can be set to 0 to run user code in the same event loop as the +# replica's main event loop. +RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD = get_env_bool( + "RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD", "1" +) + +# By default, we run the router in a separate event loop. +# This flag can be set to 0 to run the router in the same event loop as the +# replica's main event loop. +RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP = get_env_bool( + "RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP", "1" +) + +# The default buffer size for request path logs. Setting to 1 will ensure +# logs are flushed to file handler immediately, otherwise it will be buffered +# and flushed to file handler when the buffer is full or when there is a log +# line with level ERROR. +RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE = get_env_int( + "RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE", 1 +) + +# The message to return when the replica is healthy. +HEALTHY_MESSAGE = "success" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/constants_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/constants_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac97ab3eabd9495ba2822a80f1d896997f89063 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/constants_utils.py @@ -0,0 +1,252 @@ +import os +import warnings +from typing import Callable, List, Optional, Type, TypeVar + + +def str_to_list(s: str) -> List[str]: + """Return a list from a comma-separated string. + + Trims whitespace and skips empty entries. + """ + return [part for part in (part.strip() for part in s.split(",")) if part] + + +def parse_latency_buckets(bucket_str: str, default_buckets: List[float]) -> List[float]: + """Parse a comma-separated string of latency bucket values. + + Args: + bucket_str: A comma-separated string of positive numbers in ascending order. + default_buckets: Default bucket values to use if bucket_str is empty. + + Returns: + A list of parsed float values. + + Raises: + ValueError: If the format is invalid or values don't meet requirements. + """ + if bucket_str.strip() == "": + return default_buckets + try: + # Convert string to list of floats + buckets = [float(x.strip()) for x in bucket_str.split(",")] + + if not buckets: + raise ValueError("Empty bucket list") + if any(x <= 0 for x in buckets): + raise ValueError("Bucket values must be positive") + if sorted(set(buckets)) != buckets: + raise ValueError("Bucket values must be in strictly ascending order") + + return buckets + except Exception as e: + raise ValueError( + f"Invalid format for `{bucket_str}`. " + f"Expected comma-separated positive numbers in ascending order. Error: {str(e)}" + ) from e + + +T = TypeVar("T") + + +def _get_env_value( + name: str, + default: Optional[T], + value_type: Type[T], + validation_func: Optional[Callable[[T], bool]] = None, + expected_value_description: str = None, +) -> Optional[T]: + """Get environment variable with type conversion and validation. + + This function retrieves an environment variable, converts it to the specified type, + and optionally validates the converted value. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + If None, the function will return None without validation. + value_type: Type to convert the environment variable value to (e.g., int, float, str). + validation_func: Optional function that takes the converted value and returns + a boolean indicating whether the value is valid. + expected_value_description: Description of the expected value characteristics + (e.g., "positive", "non negative") used in error messages. + + Returns: + The environment variable value converted to the specified type and validated, + or the default value if the environment variable is not set. + + Raises: + ValueError: If the environment variable value cannot be converted to the specified + type, or if it fails the optional validation check. + """ + raw = os.environ.get(name, default) + if raw is None: + return None + + try: + value = value_type(raw) + except ValueError as e: + raise ValueError( + f"Environment variable `{name}` value `{raw}` cannot be converted to `{value_type.__name__}`!" + ) from e + + if validation_func and not validation_func(value): + raise ValueError( + f"Got unexpected value `{value}` for `{name}` environment variable! " + f"Expected {expected_value_description} `{value_type.__name__}`." + ) + + return value + + +def get_env_int(name: str, default: Optional[int]) -> Optional[int]: + """Get environment variable as an integer. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + + Returns: + The environment variable value as an integer. + + Raises: + ValueError: If the value cannot be converted to an integer. + """ + return _get_env_value(name, default, int) + + +def get_env_int_positive(name: str, default: Optional[int]) -> Optional[int]: + """Get environment variable as a positive integer. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + + Returns: + The environment variable value as a positive integer. + + Raises: + ValueError: If the value cannot be converted to an integer or is not positive. + """ + return _get_env_value(name, default, int, lambda x: x > 0, "positive") + + +def get_env_int_non_negative(name: str, default: Optional[int]) -> Optional[int]: + """Get environment variable as a non-negative integer. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + + Returns: + The environment variable value as a non-negative integer. + + Raises: + ValueError: If the value cannot be converted to an integer or is negative. + """ + return _get_env_value(name, default, int, lambda x: x >= 0, "non negative") + + +def get_env_float(name: str, default: Optional[float]) -> Optional[float]: + """Get environment variable as a float. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + + Returns: + The environment variable value as a float. + + Raises: + ValueError: If the value cannot be converted to a float. + """ + return _get_env_value(name, default, float) + + +def get_env_float_positive(name: str, default: Optional[float]) -> Optional[float]: + """Get environment variable as a positive float. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + + Returns: + The environment variable value as a positive float. + + Raises: + ValueError: If the value cannot be converted to a float or is not positive. + """ + return _get_env_value(name, default, float, lambda x: x > 0, "positive") + + +def get_env_float_non_negative(name: str, default: Optional[float]) -> Optional[float]: + """Get environment variable as a non-negative float. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + + Returns: + The environment variable value as a non-negative float. + + Raises: + ValueError: If the value cannot be converted to a float or is negative. + """ + return _get_env_value(name, default, float, lambda x: x >= 0, "non negative") + + +def get_env_str(name: str, default: Optional[str]) -> str: + """Get environment variable as a string. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + + Returns: + The environment variable value as a string. + """ + return os.environ.get(name, default) + + +def get_env_bool(name: str, default: Optional[str]) -> bool: + """Get environment variable as a boolean. + + Environment variable values of "1" are interpreted as True, all others as False. + + Args: + name: The name of the environment variable. + default: Default value to use if the environment variable is not set. + + Returns: + True if the environment variable value is "1", False otherwise. + """ + return os.environ.get(name, default) == "1" + + +def get_env_float_non_zero_with_warning( + name: str, default: Optional[float] +) -> Optional[float]: + """Introduced for backward compatibility for constants: + + PROXY_HEALTH_CHECK_TIMEOUT_S + PROXY_HEALTH_CHECK_PERIOD_S + PROXY_READY_CHECK_TIMEOUT_S + PROXY_MIN_DRAINING_PERIOD_S + RAY_SERVE_KV_TIMEOUT_S + + todo: replace this function with 'get_env_float_positive' for the '2.50.0' release. + """ + removal_version = "2.50.0" + + env_value = get_env_float(name, default) + backward_compatible_result = env_value or default + + if env_value is not None and env_value <= 0: + # warning message if unexpected value + warnings.warn( + f"Got unexpected value `{env_value}` for `{name}` environment variable! " + f"Starting from version `{removal_version}`, the environment variable will require a positive value. " + f"Setting `{name}` to `{backward_compatible_result}`. ", + FutureWarning, + stacklevel=2, + ) + return backward_compatible_result diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/controller.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..cc0724f2056583b3ca974328f2bc865cf321b531 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/controller.py @@ -0,0 +1,1206 @@ +import asyncio +import logging +import os +import pickle +import time +from typing import Any, Dict, Iterable, List, Optional, Tuple, Union + +import ray +from ray._common.network_utils import build_address +from ray._common.utils import run_background_task +from ray._raylet import GcsClient +from ray.actor import ActorHandle +from ray.serve._private.application_state import ApplicationStateManager, StatusOverview +from ray.serve._private.autoscaling_state import AutoscalingStateManager +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + NodeId, + RequestProtocol, + RequestRoutingInfo, + RunningReplicaInfo, + TargetCapacityDirection, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + CONTROL_LOOP_INTERVAL_S, + RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH, + RECOVERING_LONG_POLL_BROADCAST_TIMEOUT_S, + SERVE_CONTROLLER_NAME, + SERVE_DEFAULT_APP_NAME, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, + SERVE_ROOT_URL_ENV_KEY, +) +from ray.serve._private.default_impl import create_cluster_node_info_cache +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.deployment_state import DeploymentStateManager +from ray.serve._private.endpoint_state import EndpointState +from ray.serve._private.grpc_util import set_proxy_default_grpc_options +from ray.serve._private.http_util import ( + configure_http_options_with_defaults, +) +from ray.serve._private.logging_utils import ( + configure_component_logger, + configure_component_memory_profiler, + get_component_logger_file_path, +) +from ray.serve._private.long_poll import LongPollHost, LongPollNamespace +from ray.serve._private.proxy_state import ProxyStateManager +from ray.serve._private.storage.kv_store import RayInternalKVStore +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + call_function_from_import_path, + get_all_live_placement_group_names, + get_head_node_id, + is_grpc_enabled, +) +from ray.serve.config import HTTPOptions, ProxyLocation, gRPCOptions +from ray.serve.generated.serve_pb2 import ( + ActorNameList, + DeploymentArgs, + DeploymentRoute, + EndpointInfo as EndpointInfoProto, + EndpointSet, +) +from ray.serve.schema import ( + ApplicationDetails, + DeploymentDetails, + HTTPOptionsSchema, + LoggingConfig, + ProxyDetails, + ServeActorDetails, + ServeApplicationSchema, + ServeDeploySchema, + ServeInstanceDetails, + TargetGroup, + gRPCOptionsSchema, +) +from ray.util import metrics + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +# Used for testing purposes only. If this is set, the controller will crash +# after writing each checkpoint with the specified probability. +_CRASH_AFTER_CHECKPOINT_PROBABILITY = 0 + +CONFIG_CHECKPOINT_KEY = "serve-app-config-checkpoint" +LOGGING_CONFIG_CHECKPOINT_KEY = "serve-logging-config-checkpoint" + + +class ServeController: + """Responsible for managing the state of the serving system. + + The controller implements fault tolerance by persisting its state in + a new checkpoint each time a state change is made. If the actor crashes, + the latest checkpoint is loaded and the state is recovered. Checkpoints + are written/read using a provided KV-store interface. + + All hard state in the system is maintained by this actor and persisted via + these checkpoints. Soft state required by other components is fetched by + those actors from this actor on startup and updates are pushed out from + this actor. + + All other actors started by the controller are named, detached actors + so they will not fate share with the controller if it crashes. + + The following guarantees are provided for state-changing calls to the + controller: + - If the call succeeds, the change was made and will be reflected in + the system even if the controller or other actors die unexpectedly. + - If the call fails, the change may have been made but isn't guaranteed + to have been. The client should retry in this case. Note that this + requires all implementations here to be idempotent. + """ + + async def __init__( + self, + *, + http_options: HTTPOptions, + global_logging_config: LoggingConfig, + grpc_options: Optional[gRPCOptions] = None, + ): + self._controller_node_id = ray.get_runtime_context().get_node_id() + assert ( + self._controller_node_id == get_head_node_id() + ), "Controller must be on the head node." + + self.ray_worker_namespace = ray.get_runtime_context().namespace + self.gcs_client = GcsClient(address=ray.get_runtime_context().gcs_address) + kv_store_namespace = f"ray-serve-{self.ray_worker_namespace}" + self.kv_store = RayInternalKVStore(kv_store_namespace, self.gcs_client) + + self.long_poll_host = LongPollHost() + self.done_recovering_event = asyncio.Event() + + # Try to read config from checkpoint + # logging config from checkpoint take precedence over the one passed in + # the constructor. + self.global_logging_config = None + log_config_checkpoint = self.kv_store.get(LOGGING_CONFIG_CHECKPOINT_KEY) + if log_config_checkpoint is not None: + global_logging_config = pickle.loads(log_config_checkpoint) + self.reconfigure_global_logging_config(global_logging_config) + + configure_component_memory_profiler( + component_name="controller", component_id=str(os.getpid()) + ) + + if RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH: + logger.info( + "Calling user-provided callback from import path " + f"{RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH}." + ) + call_function_from_import_path(RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH) + + # Used to read/write checkpoints. + self.cluster_node_info_cache = create_cluster_node_info_cache(self.gcs_client) + self.cluster_node_info_cache.update() + + # Configure proxy default HTTP and gRPC options. + self.proxy_state_manager = ProxyStateManager( + http_options=configure_http_options_with_defaults(http_options), + head_node_id=self._controller_node_id, + cluster_node_info_cache=self.cluster_node_info_cache, + logging_config=self.global_logging_config, + grpc_options=set_proxy_default_grpc_options(grpc_options), + ) + # We modify the HTTP and gRPC options above, so delete them to avoid + del http_options, grpc_options + + self.endpoint_state = EndpointState(self.kv_store, self.long_poll_host) + + # Fetch all running actors in current cluster as source of current + # replica state for controller failure recovery + all_current_actors = ray.util.list_named_actors(all_namespaces=True) + all_serve_actor_names = [ + actor["name"] + for actor in all_current_actors + if actor["namespace"] == SERVE_NAMESPACE + ] + + self.autoscaling_state_manager = AutoscalingStateManager() + self.deployment_state_manager = DeploymentStateManager( + self.kv_store, + self.long_poll_host, + all_serve_actor_names, + get_all_live_placement_group_names(), + self.cluster_node_info_cache, + self.autoscaling_state_manager, + ) + + # Manage all applications' state + self.application_state_manager = ApplicationStateManager( + self.deployment_state_manager, + self.endpoint_state, + self.kv_store, + self.global_logging_config, + ) + + # Controller actor details + self._actor_details = ServeActorDetails( + node_id=ray.get_runtime_context().get_node_id(), + node_ip=ray.util.get_node_ip_address(), + node_instance_id=ray.util.get_node_instance_id(), + actor_id=ray.get_runtime_context().get_actor_id(), + actor_name=SERVE_CONTROLLER_NAME, + worker_id=ray.get_runtime_context().get_worker_id(), + log_file_path=get_component_logger_file_path(), + ) + self._shutting_down = False + self._shutdown_event = asyncio.Event() + self._shutdown_start_time = None + + self._create_control_loop_metrics() + run_background_task(self.run_control_loop()) + + # The target capacity percentage for all deployments across the cluster. + self._target_capacity: Optional[float] = None + self._target_capacity_direction: Optional[TargetCapacityDirection] = None + self._recover_state_from_checkpoint() + + # Nodes where proxy actors should run. + self._proxy_nodes = set() + self._update_proxy_nodes() + + def reconfigure_global_logging_config(self, global_logging_config: LoggingConfig): + if ( + self.global_logging_config + and self.global_logging_config == global_logging_config + ): + return + self.kv_store.put( + LOGGING_CONFIG_CHECKPOINT_KEY, pickle.dumps(global_logging_config) + ) + self.global_logging_config = global_logging_config + + self.long_poll_host.notify_changed( + {LongPollNamespace.GLOBAL_LOGGING_CONFIG: global_logging_config} + ) + configure_component_logger( + component_name="controller", + component_id=str(os.getpid()), + logging_config=global_logging_config, + ) + + logger.info( + f"Controller starting (version='{ray.__version__}').", + extra={"log_to_stderr": False}, + ) + logger.debug( + "Configure the serve controller logger " + f"with logging config: {self.global_logging_config}" + ) + + def check_alive(self) -> None: + """No-op to check if this controller is alive.""" + return + + def get_pid(self) -> int: + return os.getpid() + + def record_autoscaling_metrics( + self, replica_id: str, window_avg: Optional[float], send_timestamp: float + ): + logger.debug( + f"Received metrics from replica {replica_id}: {window_avg} running requests" + ) + self.autoscaling_state_manager.record_request_metrics_for_replica( + replica_id, window_avg, send_timestamp + ) + + def record_handle_metrics( + self, + deployment_id: str, + handle_id: str, + actor_id: Optional[str], + handle_source: DeploymentHandleSource, + queued_requests: float, + running_requests: Dict[str, float], + send_timestamp: float, + ): + logger.debug( + f"Received metrics from handle {handle_id} for deployment {deployment_id}: " + f"{queued_requests} queued requests and {running_requests} running requests" + ) + self.autoscaling_state_manager.record_request_metrics_for_handle( + deployment_id=deployment_id, + handle_id=handle_id, + actor_id=actor_id, + handle_source=handle_source, + queued_requests=queued_requests, + running_requests=running_requests, + send_timestamp=send_timestamp, + ) + + def _dump_autoscaling_metrics_for_testing(self): + return self.autoscaling_state_manager.get_metrics() + + def _dump_replica_states_for_testing(self, deployment_id: DeploymentID): + return self.deployment_state_manager._deployment_states[deployment_id]._replicas + + def _stop_one_running_replica_for_testing(self, deployment_id): + self.deployment_state_manager._deployment_states[ + deployment_id + ]._stop_one_running_replica_for_testing() + + async def listen_for_change(self, keys_to_snapshot_ids: Dict[str, int]): + """Proxy long pull client's listen request. + + Args: + keys_to_snapshot_ids (Dict[str, int]): Snapshot IDs are used to + determine whether or not the host should immediately return the + data or wait for the value to be changed. + """ + if not self.done_recovering_event.is_set(): + await self.done_recovering_event.wait() + + return await self.long_poll_host.listen_for_change(keys_to_snapshot_ids) + + async def listen_for_change_java(self, keys_to_snapshot_ids_bytes: bytes): + """Proxy long pull client's listen request. + + Args: + keys_to_snapshot_ids_bytes (Dict[str, int]): the protobuf bytes of + keys_to_snapshot_ids (Dict[str, int]). + """ + if not self.done_recovering_event.is_set(): + await self.done_recovering_event.wait() + + return await self.long_poll_host.listen_for_change_java( + keys_to_snapshot_ids_bytes + ) + + def get_all_endpoints(self) -> Dict[DeploymentID, Dict[str, Any]]: + """Returns a dictionary of deployment name to config.""" + return self.endpoint_state.get_endpoints() + + def get_all_endpoints_java(self) -> bytes: + """Returns a dictionary of deployment name to config.""" + endpoints = self.get_all_endpoints() + # NOTE(zcin): Java only supports 1.x deployments, so only return + # a dictionary of deployment name -> endpoint info + data = { + endpoint_tag.name: EndpointInfoProto(route=endpoint_dict["route"]) + for endpoint_tag, endpoint_dict in endpoints.items() + } + return EndpointSet(endpoints=data).SerializeToString() + + def get_proxies(self) -> Dict[NodeId, ActorHandle]: + """Returns a dictionary of node ID to proxy actor handles.""" + if self.proxy_state_manager is None: + return {} + return self.proxy_state_manager.get_proxy_handles() + + def get_proxy_names(self) -> bytes: + """Returns the proxy actor name list serialized by protobuf.""" + if self.proxy_state_manager is None: + return None + + actor_name_list = ActorNameList( + names=self.proxy_state_manager.get_proxy_names().values() + ) + return actor_name_list.SerializeToString() + + def _update_proxy_nodes(self): + """Update the nodes set where proxy actors should run. + + Controller decides where proxy actors should run + (head node and nodes with deployment replicas). + """ + new_proxy_nodes = self.deployment_state_manager.get_active_node_ids() + new_proxy_nodes = new_proxy_nodes - set( + self.cluster_node_info_cache.get_draining_nodes() + ) + new_proxy_nodes.add(self._controller_node_id) + self._proxy_nodes = new_proxy_nodes + + async def run_control_loop(self) -> None: + # NOTE(edoakes): we catch all exceptions here and simply log them, + # because an unhandled exception would cause the main control loop to + # halt, which should *never* happen. + recovering_timeout = RECOVERING_LONG_POLL_BROADCAST_TIMEOUT_S + num_loops = 0 + start_time = time.time() + while True: + loop_start_time = time.time() + try: + await self.run_control_loop_step( + start_time, recovering_timeout, num_loops + ) + except Exception as e: + # we never expect this to happen, but adding this to be safe + logger.exception(f"There was an exception in the control loop: {e}") + await asyncio.sleep(1) + + loop_duration = time.time() - loop_start_time + if loop_duration > 10: + logger.warning( + f"The last control loop was slow (took {loop_duration}s). " + "This is likely caused by running a large number of " + "replicas in a single Ray cluster. Consider using " + "multiple Ray clusters.", + extra={"log_to_stderr": False}, + ) + self.control_loop_duration_gauge_s.set(loop_duration) + + num_loops += 1 + self.num_control_loops_gauge.set(num_loops) + + sleep_start_time = time.time() + await asyncio.sleep(CONTROL_LOOP_INTERVAL_S) + self.sleep_duration_gauge_s.set(time.time() - sleep_start_time) + + async def run_control_loop_step( + self, start_time: float, recovering_timeout: float, num_loops: int + ): + try: + self.cluster_node_info_cache.update() + except Exception: + logger.exception("Exception updating cluster node info cache.") + + if self._shutting_down: + try: + self.shutdown() + except Exception: + logger.exception("Exception during shutdown.") + + if ( + not self.done_recovering_event.is_set() + and time.time() - start_time > recovering_timeout + ): + logger.warning( + f"Replicas still recovering after {recovering_timeout}s, " + "setting done recovering event to broadcast long poll updates." + ) + self.done_recovering_event.set() + + # initialize any_recovering to None to indicate that we don't know if + # we've recovered anything yet + any_recovering: Optional[bool] = None + try: + dsm_update_start_time = time.time() + any_recovering = self.deployment_state_manager.update() + + self.deployment_state_manager.save_checkpoint() + + self.dsm_update_duration_gauge_s.set(time.time() - dsm_update_start_time) + if not self.done_recovering_event.is_set() and not any_recovering: + self.done_recovering_event.set() + if num_loops > 0: + # Only log if we actually needed to recover anything. + logger.info( + "Finished recovering deployments after " + f"{(time.time() - start_time):.2f}s.", + extra={"log_to_stderr": False}, + ) + except Exception: + logger.exception("Exception updating deployment state.") + + try: + asm_update_start_time = time.time() + self.application_state_manager.update() + + self.application_state_manager.save_checkpoint() + # ApplicationStateManager.update() can also mutate the + # DeploymentStateManager so we need to checkpoint that as well + self.deployment_state_manager.save_checkpoint() + + self.asm_update_duration_gauge_s.set(time.time() - asm_update_start_time) + except Exception: + logger.exception("Exception updating application state.") + + # Update the proxy nodes set before updating the proxy states, + # so they are more consistent. + node_update_start_time = time.time() + self._update_proxy_nodes() + self.node_update_duration_gauge_s.set(time.time() - node_update_start_time) + + # Don't update proxy_state until after the done recovering event is set, + # otherwise we may start a new proxy but not broadcast it any + # info about available deployments & their replicas. + if self.proxy_state_manager and self.done_recovering_event.is_set(): + try: + proxy_update_start_time = time.time() + self.proxy_state_manager.update(proxy_nodes=self._proxy_nodes) + self.proxy_update_duration_gauge_s.set( + time.time() - proxy_update_start_time + ) + except Exception: + logger.exception("Exception updating proxy state.") + + # When the controller is done recovering, drop invalid handle metrics + # that may be stale for autoscaling + if any_recovering is False: + self.autoscaling_state_manager.drop_stale_handle_metrics( + self.deployment_state_manager.get_alive_replica_actor_ids() + | self.proxy_state_manager.get_alive_proxy_actor_ids() + ) + + def _create_control_loop_metrics(self): + self.node_update_duration_gauge_s = metrics.Gauge( + "serve_controller_node_update_duration_s", + description="The control loop time spent on collecting proxy node info.", + ) + self.proxy_update_duration_gauge_s = metrics.Gauge( + "serve_controller_proxy_state_update_duration_s", + description="The control loop time spent on updating proxy state.", + ) + self.dsm_update_duration_gauge_s = metrics.Gauge( + "serve_controller_deployment_state_update_duration_s", + description="The control loop time spent on updating deployment state.", + ) + self.asm_update_duration_gauge_s = metrics.Gauge( + "serve_controller_application_state_update_duration_s", + description="The control loop time spent on updating application state.", + ) + self.sleep_duration_gauge_s = metrics.Gauge( + "serve_controller_sleep_duration_s", + description="The duration of the last control loop's sleep.", + ) + self.control_loop_duration_gauge_s = metrics.Gauge( + "serve_controller_control_loop_duration_s", + description="The duration of the last control loop.", + ) + self.num_control_loops_gauge = metrics.Gauge( + "serve_controller_num_control_loops", + description=( + "The number of control loops performed by the controller. " + "Increases monotonically over the controller's lifetime." + ), + tag_keys=("actor_id",), + ) + self.num_control_loops_gauge.set_default_tags( + {"actor_id": ray.get_runtime_context().get_actor_id()} + ) + + def _recover_state_from_checkpoint(self): + ( + deployment_time, + serve_config, + target_capacity_direction, + ) = self._read_config_checkpoint() + self._target_capacity_direction = target_capacity_direction + if serve_config is not None: + logger.info( + "Recovered config from checkpoint.", extra={"log_to_stderr": False} + ) + self.apply_config(serve_config, deployment_time=deployment_time) + + def _read_config_checkpoint( + self, + ) -> Tuple[float, Optional[ServeDeploySchema], Optional[TargetCapacityDirection]]: + """Reads the current Serve config checkpoint. + + The Serve config checkpoint stores active application configs and + other metadata. + + Returns: + + If the GCS contains a checkpoint, tuple of: + 1. A deployment timestamp. + 2. A Serve config. This Serve config is reconstructed from the + active application states. It may not exactly match the + submitted config (e.g. the top-level http options may be + different). + 3. The target_capacity direction calculated after the Serve + was submitted. + + If the GCS doesn't contain a checkpoint, returns (0, None, None). + """ + + checkpoint = self.kv_store.get(CONFIG_CHECKPOINT_KEY) + if checkpoint is not None: + ( + deployment_time, + target_capacity, + target_capacity_direction, + config_checkpoints_dict, + ) = pickle.loads(checkpoint) + + return ( + deployment_time, + ServeDeploySchema( + applications=list(config_checkpoints_dict.values()), + target_capacity=target_capacity, + ), + target_capacity_direction, + ) + else: + return (0.0, None, None) + + def _all_running_replicas(self) -> Dict[DeploymentID, List[RunningReplicaInfo]]: + """Used for testing. + + Returned dictionary maps deployment names to replica infos. + """ + + return self.deployment_state_manager.get_running_replica_infos() + + def get_actor_details(self) -> ServeActorDetails: + """Returns the actor details for this controller. + + Currently used for test only. + """ + return self._actor_details + + def get_proxy_details(self, node_id: str) -> Optional[ProxyDetails]: + """Returns the proxy details for the proxy on the given node. + + Currently used for test only. Will return None if the proxy doesn't exist on + the given node. + """ + if self.proxy_state_manager is None: + return None + + return self.proxy_state_manager.get_proxy_details().get(node_id) + + def get_deployment_timestamps(self, app_name: str) -> float: + """Returns the deployment timestamp for the given app. + + Currently used for test only. + """ + for ( + _app_name, + app_status_info, + ) in self.application_state_manager.list_app_statuses().items(): + if app_name == _app_name: + return app_status_info.deployment_timestamp + + def get_deployment_details( + self, app_name: str, deployment_name: str + ) -> DeploymentDetails: + """Returns the deployment details for the app and deployment. + + Currently used for test only. + """ + return self.application_state_manager.list_deployment_details(app_name)[ + deployment_name + ] + + def get_http_config(self) -> HTTPOptions: + """Return the HTTP proxy configuration.""" + if self.proxy_state_manager is None: + return HTTPOptions() + return self.proxy_state_manager.get_config() + + def get_grpc_config(self) -> gRPCOptions: + """Return the gRPC proxy configuration.""" + if self.proxy_state_manager is None: + return gRPCOptions() + return self.proxy_state_manager.get_grpc_config() + + def get_root_url(self): + """Return the root url for the serve instance.""" + if self.proxy_state_manager is None: + return None + http_config = self.get_http_config() + if http_config.root_url == "": + if SERVE_ROOT_URL_ENV_KEY in os.environ: + return os.environ[SERVE_ROOT_URL_ENV_KEY] + else: + return ( + f"http://{build_address(http_config.host, http_config.port)}" + f"{http_config.root_path}" + ) + return http_config.root_url + + def config_checkpoint_deleted(self) -> bool: + """Returns whether the config checkpoint has been deleted. + + Get the config checkpoint from the kv store. If it is None, then it has been + deleted. + """ + return self.kv_store.get(CONFIG_CHECKPOINT_KEY) is None + + def shutdown(self): + """Shuts down the serve instance completely. + + This method will only be triggered when `self._shutting_down` is true. It + deletes the kv store for config checkpoints, sets application state to deleting, + delete all deployments, and shuts down all proxies. Once all these + resources are released, it then kills the controller actor. + """ + if not self._shutting_down: + return + + if self._shutdown_start_time is None: + self._shutdown_start_time = time.time() + logger.info("Controller shutdown started.", extra={"log_to_stderr": False}) + + self.kv_store.delete(CONFIG_CHECKPOINT_KEY) + self.kv_store.delete(LOGGING_CONFIG_CHECKPOINT_KEY) + self.application_state_manager.shutdown() + self.deployment_state_manager.shutdown() + self.endpoint_state.shutdown() + if self.proxy_state_manager: + self.proxy_state_manager.shutdown() + + config_checkpoint_deleted = self.config_checkpoint_deleted() + application_is_shutdown = self.application_state_manager.is_ready_for_shutdown() + deployment_is_shutdown = self.deployment_state_manager.is_ready_for_shutdown() + endpoint_is_shutdown = self.endpoint_state.is_ready_for_shutdown() + proxy_state_is_shutdown = ( + self.proxy_state_manager is None + or self.proxy_state_manager.is_ready_for_shutdown() + ) + if ( + config_checkpoint_deleted + and application_is_shutdown + and deployment_is_shutdown + and endpoint_is_shutdown + and proxy_state_is_shutdown + ): + logger.warning( + "All resources have shut down, controller exiting.", + extra={"log_to_stderr": False}, + ) + _controller_actor = ray.get_runtime_context().current_actor + ray.kill(_controller_actor, no_restart=True) + elif time.time() - self._shutdown_start_time > 10: + if not config_checkpoint_deleted: + logger.warning( + f"{CONFIG_CHECKPOINT_KEY} not yet deleted", + extra={"log_to_stderr": False}, + ) + if not application_is_shutdown: + logger.warning( + "application not yet shutdown", + extra={"log_to_stderr": False}, + ) + if not deployment_is_shutdown: + logger.warning( + "deployment not yet shutdown", + extra={"log_to_stderr": False}, + ) + if not endpoint_is_shutdown: + logger.warning( + "endpoint not yet shutdown", + extra={"log_to_stderr": False}, + ) + if not proxy_state_is_shutdown: + logger.warning( + "proxy_state not yet shutdown", + extra={"log_to_stderr": False}, + ) + + def deploy_applications( + self, name_to_deployment_args_list: Dict[str, List[bytes]] + ) -> None: + """ + Takes in a list of dictionaries that contain deployment arguments. + If same app name deployed, old application will be overwritten. + + Args: + name: Application name. + deployment_args_list: List of serialized deployment information, + where each item in the list is bytes representing the serialized + protobuf `DeploymentArgs` object. `DeploymentArgs` contains all the + information for the single deployment. + """ + name_to_deployment_args = {} + for name, deployment_args_list in name_to_deployment_args_list.items(): + deployment_args_deserialized = [] + for deployment_args_bytes in deployment_args_list: + args = DeploymentArgs.FromString(deployment_args_bytes) + deployment_args_deserialized.append( + { + "deployment_name": args.deployment_name, + "deployment_config_proto_bytes": args.deployment_config, + "replica_config_proto_bytes": args.replica_config, + "deployer_job_id": args.deployer_job_id, + "ingress": args.ingress, + "route_prefix": ( + args.route_prefix if args.HasField("route_prefix") else None + ), + } + ) + name_to_deployment_args[name] = deployment_args_deserialized + + self.application_state_manager.deploy_apps(name_to_deployment_args) + + self.application_state_manager.save_checkpoint() + + def deploy_application(self, name: str, deployment_args_list: List[bytes]) -> None: + """ + Deploy a single application + (as deploy_applications(), but it only takes a single name and deployment args). + This primarily exists as a shim to avoid + changing Java code in https://github.com/ray-project/ray/pull/49168, + and could be removed if the Java code was refactored + to use the new bulk deploy_applications API. + """ + self.deploy_applications({name: deployment_args_list}) + + def apply_config( + self, + config: ServeDeploySchema, + deployment_time: float = 0.0, + ) -> None: + """Apply the config described in `ServeDeploySchema`. + + This will upgrade the applications to the goal state specified in the + config. + + If `deployment_time` is not provided, `time.time()` is used. + """ + ServeUsageTag.API_VERSION.record("v2") + if not deployment_time: + deployment_time = time.time() + + new_config_checkpoint = {} + + _, curr_config, _ = self._read_config_checkpoint() + + self._target_capacity_direction = calculate_target_capacity_direction( + curr_config=curr_config, + new_config=config, + curr_target_capacity_direction=self._target_capacity_direction, + ) + log_target_capacity_change( + self._target_capacity, + config.target_capacity, + self._target_capacity_direction, + ) + self._target_capacity = config.target_capacity + + for app_config in config.applications: + # If the application logging config is not set, use the global logging + # config. + if app_config.logging_config is None and config.logging_config: + app_config.logging_config = config.logging_config + + app_config_dict = app_config.dict(exclude_unset=True) + new_config_checkpoint[app_config.name] = app_config_dict + + self.kv_store.put( + CONFIG_CHECKPOINT_KEY, + pickle.dumps( + ( + deployment_time, + self._target_capacity, + self._target_capacity_direction, + new_config_checkpoint, + ) + ), + ) + + # Declaratively apply the new set of applications. + # This will delete any applications no longer in the config that were + # previously deployed via the REST API. + self.application_state_manager.apply_app_configs( + config.applications, + deployment_time=deployment_time, + target_capacity=self._target_capacity, + target_capacity_direction=self._target_capacity_direction, + ) + + self.application_state_manager.save_checkpoint() + + def get_deployment_info(self, name: str, app_name: str = "") -> bytes: + """Get the current information about a deployment. + + Args: + name: the name of the deployment. + + Returns: + DeploymentRoute's protobuf serialized bytes + + Raises: + KeyError: If the deployment doesn't exist. + """ + id = DeploymentID(name=name, app_name=app_name) + deployment_info = self.deployment_state_manager.get_deployment(id) + if deployment_info is None: + app_msg = f" in application '{app_name}'" if app_name else "" + raise KeyError(f"Deployment '{name}' does not exist{app_msg}.") + + route = self.endpoint_state.get_endpoint_route(id) + + deployment_route = DeploymentRoute( + deployment_info=deployment_info.to_proto(), route=route + ) + return deployment_route.SerializeToString() + + def list_deployments_internal( + self, + ) -> Dict[DeploymentID, Tuple[DeploymentInfo, str]]: + """Gets the current information about all deployments. + + Returns: + Dict(deployment_id, (DeploymentInfo, route)) + """ + return { + id: (info, self.endpoint_state.get_endpoint_route(id)) + for id, info in self.deployment_state_manager.get_deployment_infos().items() + } + + def get_deployment_config( + self, deployment_id: DeploymentID + ) -> Optional[DeploymentConfig]: + """Get the deployment config for the given deployment id. + + Args: + deployment_id: The deployment id to get the config for. + + Returns: + A deployment config object if the deployment id exist, + None otherwise. + """ + deployment_info = self.deployment_state_manager.get_deployment_infos().get( + deployment_id + ) + return deployment_info.deployment_config if deployment_info else None + + def list_deployment_ids(self) -> List[DeploymentID]: + """Gets the current list of all deployments' identifiers.""" + return self.deployment_state_manager._deployment_states.keys() + + def get_serve_instance_details(self) -> Dict: + """Gets details on all applications on the cluster and system-level info. + + The information includes application and deployment statuses, config options, + error messages, etc. + + Returns: + Dict that follows the format of the schema ServeInstanceDetails. + """ + + http_config = self.get_http_config() + grpc_config = self.get_grpc_config() + applications = {} + + app_statuses = self.application_state_manager.list_app_statuses() + + # If there are no app statuses, there's no point getting the app configs. + # Moreover, there might be no app statuses because the GCS is down, + # in which case getting the app configs would fail anyway, + # since they're stored in the checkpoint in the GCS. + app_configs = self.get_app_configs() if app_statuses else {} + + for ( + app_name, + app_status_info, + ) in app_statuses.items(): + applications[app_name] = ApplicationDetails( + name=app_name, + route_prefix=self.application_state_manager.get_route_prefix(app_name), + docs_path=self.get_docs_path(app_name), + status=app_status_info.status, + message=app_status_info.message, + last_deployed_time_s=app_status_info.deployment_timestamp, + # This can be none if the app was deployed through + # serve.run, the app is in deleting state, + # or a checkpoint hasn't been set yet + deployed_app_config=app_configs.get(app_name), + source=self.application_state_manager.get_app_source(app_name), + deployments=self.application_state_manager.list_deployment_details( + app_name + ), + ) + + # NOTE(zcin): We use exclude_unset here because we explicitly and intentionally + # fill in all info that should be shown to users. + http_options = HTTPOptionsSchema.parse_obj(http_config.dict(exclude_unset=True)) + grpc_options = gRPCOptionsSchema.parse_obj(grpc_config.dict(exclude_unset=True)) + + return ServeInstanceDetails( + target_capacity=self._target_capacity, + controller_info=self._actor_details, + proxy_location=ProxyLocation._from_deployment_mode(http_config.location), + http_options=http_options, + grpc_options=grpc_options, + proxies=( + self.proxy_state_manager.get_proxy_details() + if self.proxy_state_manager + else None + ), + applications=applications, + target_groups=self.get_target_groups(), + )._get_user_facing_json_serializable_dict(exclude_unset=True) + + def get_target_groups(self, app_name: Optional[str] = None) -> List[TargetGroup]: + """Target groups contains information about IP + addresses and ports of all proxies in the cluster. + + This information is used to setup the load balancer. + """ + target_groups: List[TargetGroup] = [] + + if self.proxy_state_manager.get_proxy_details(): + # setting prefix route to "/" because in ray serve, proxy + # accepts requests from the client and routes them to the + # correct application. This is true for both HTTP and gRPC proxies. + target_groups.append( + TargetGroup( + protocol=RequestProtocol.HTTP, + route_prefix="/", + targets=self.proxy_state_manager.get_targets(RequestProtocol.HTTP), + ) + ) + if is_grpc_enabled(self.get_grpc_config()): + target_groups.append( + TargetGroup( + protocol=RequestProtocol.GRPC, + route_prefix="/", + targets=self.proxy_state_manager.get_targets( + RequestProtocol.GRPC + ), + ) + ) + return target_groups + + def get_serve_status(self, name: str = SERVE_DEFAULT_APP_NAME) -> bytes: + """Return application status + Args: + name: application name. If application name doesn't exist, app_status + is NOT_STARTED. + """ + + app_status = self.application_state_manager.get_app_status_info(name) + deployment_statuses = self.application_state_manager.get_deployments_statuses( + name + ) + status_info = StatusOverview( + name=name, + app_status=app_status, + deployment_statuses=deployment_statuses, + ) + return status_info.to_proto().SerializeToString() + + def get_serve_statuses(self, names: List[str]) -> List[bytes]: + statuses = [] + for name in names: + statuses.append(self.get_serve_status(name)) + return statuses + + def list_serve_statuses(self) -> List[bytes]: + statuses = [] + for name in self.application_state_manager.list_app_statuses(): + statuses.append(self.get_serve_status(name)) + return statuses + + def get_app_configs(self) -> Dict[str, ServeApplicationSchema]: + checkpoint = self.kv_store.get(CONFIG_CHECKPOINT_KEY) + if checkpoint is None: + return {} + + _, _, _, config_checkpoints_dict = pickle.loads(checkpoint) + return { + app: ServeApplicationSchema.parse_obj(config) + for app, config in config_checkpoints_dict.items() + } + + def get_all_deployment_statuses(self) -> List[bytes]: + """Gets deployment status bytes for all live deployments.""" + statuses = self.deployment_state_manager.get_deployment_statuses() + return [status.to_proto().SerializeToString() for status in statuses] + + def get_deployment_status( + self, name: str, app_name: str = "" + ) -> Union[None, bytes]: + """Get deployment status by deployment name. + + Args: + name: Deployment name. + app_name: Application name. Default is "" because 1.x + deployments go through this API. + """ + + id = DeploymentID(name=name, app_name=app_name) + status = self.deployment_state_manager.get_deployment_statuses([id]) + if not status: + return None + return status[0].to_proto().SerializeToString() + + def get_docs_path(self, name: str): + """Docs path for application. + + Currently, this is the OpenAPI docs path for FastAPI-integrated applications.""" + return self.application_state_manager.get_docs_path(name) + + def get_ingress_deployment_name(self, app_name: str) -> Optional[str]: + """Name of the ingress deployment in an application. + + Returns: + Ingress deployment name (str): if the application exists. + None: if the application does not exist. + """ + return self.application_state_manager.get_ingress_deployment_name(app_name) + + def delete_apps(self, names: Iterable[str]): + """Delete applications based on names + + During deletion, the application status is DELETING + """ + for name in names: + self.application_state_manager.delete_app(name) + + self.application_state_manager.save_checkpoint() + + def record_request_routing_info(self, info: RequestRoutingInfo): + """Record replica routing information for a replica. + + Args: + info: RequestRoutingInfo including deployment name, replica tag, + multiplex model ids, and routing stats. + """ + self.deployment_state_manager.record_request_routing_info(info) + + async def graceful_shutdown(self, wait: bool = True): + """Set the shutting down flag on controller to signal shutdown in + run_control_loop(). + + This is used to signal to the controller that it should proceed with shutdown + process, so it can shut down gracefully. It also waits until the shutdown + event is triggered if wait is true. + + Raises: + RayActorError: if wait is True, the caller waits until the controller + is killed, which raises a RayActorError. + """ + self._shutting_down = True + if not wait: + return + + # This event never gets set. The caller waits indefinitely on this event + # until the controller is killed, which raises a RayActorError. + await self._shutdown_event.wait() + + def _get_logging_config(self) -> Tuple: + """Get the logging configuration (for testing purposes).""" + log_file_path = None + for handler in logger.handlers: + if isinstance(handler, logging.handlers.MemoryHandler): + log_file_path = handler.target.baseFilename + return self.global_logging_config, log_file_path + + def _get_target_capacity_direction(self) -> Optional[TargetCapacityDirection]: + """Gets the controller's scale direction (for testing purposes).""" + + return self._target_capacity_direction + + +def calculate_target_capacity_direction( + curr_config: Optional[ServeDeploySchema], + new_config: ServeDeploySchema, + curr_target_capacity_direction: Optional[float], +) -> Optional[TargetCapacityDirection]: + """Compares two Serve configs to calculate the next scaling direction.""" + + curr_target_capacity = None + next_target_capacity_direction = None + + if curr_config is not None and applications_match(curr_config, new_config): + curr_target_capacity = curr_config.target_capacity + next_target_capacity = new_config.target_capacity + + if curr_target_capacity == next_target_capacity: + next_target_capacity_direction = curr_target_capacity_direction + elif curr_target_capacity is None and next_target_capacity is not None: + # target_capacity is scaling down from None to a number. + next_target_capacity_direction = TargetCapacityDirection.DOWN + elif next_target_capacity is None: + next_target_capacity_direction = None + elif curr_target_capacity < next_target_capacity: + next_target_capacity_direction = TargetCapacityDirection.UP + else: + next_target_capacity_direction = TargetCapacityDirection.DOWN + elif new_config.target_capacity is not None: + # A config with different apps has been applied, and it contains a + # target_capacity. Serve must start scaling this config up. + next_target_capacity_direction = TargetCapacityDirection.UP + else: + next_target_capacity_direction = None + + return next_target_capacity_direction + + +def applications_match(config1: ServeDeploySchema, config2: ServeDeploySchema) -> bool: + """Checks whether the applications in config1 and config2 match. + + Two applications match if they have the same name. + """ + + config1_app_names = {app.name for app in config1.applications} + config2_app_names = {app.name for app in config2.applications} + + return config1_app_names == config2_app_names + + +def log_target_capacity_change( + curr_target_capacity: Optional[float], + next_target_capacity: Optional[float], + next_target_capacity_direction: Optional[TargetCapacityDirection], +): + """Logs changes in the target_capacity.""" + + if curr_target_capacity != next_target_capacity: + if isinstance(next_target_capacity_direction, TargetCapacityDirection): + logger.info( + "Target capacity scaling " + f"{next_target_capacity_direction.value.lower()} " + f"from {curr_target_capacity} to {next_target_capacity}." + ) + else: + logger.info("Target capacity entering 100% at steady state.") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/controller_avatar.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/controller_avatar.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c5764809478a050bcbf900484f985ae942536a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/controller_avatar.py @@ -0,0 +1,40 @@ +import ray +from ray.serve._private.constants import SERVE_CONTROLLER_NAME, SERVE_NAMESPACE +from ray.serve._private.default_impl import get_controller_impl +from ray.serve.config import HTTPOptions +from ray.serve.schema import LoggingConfig + + +@ray.remote(num_cpus=0) +class ServeControllerAvatar: + """A hack that proxy the creation of async actors from Java. + + To be removed after https://github.com/ray-project/ray/pull/26037 + + Java api can not support python async actor. If we use java api create + python async actor. The async init method won't be executed. The async + method will fail with pickle error. And the run_control_loop of controller + actor can't be executed too. We use this proxy actor create python async + actor to avoid the above problem. + """ + + def __init__( + self, + http_proxy_port: int = 8000, + ): + try: + self._controller = ray.get_actor( + SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE + ) + except ValueError: + self._controller = None + if self._controller is None: + controller_impl = get_controller_impl() + self._controller = controller_impl.remote( + http_options=HTTPOptions(port=http_proxy_port), + global_logging_config=LoggingConfig(), + ) + + def check_alive(self) -> None: + """No-op to check if this actor is alive.""" + return diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/default_impl.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/default_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..047960abcdf6939f64d596bc66dd0fd52169da69 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/default_impl.py @@ -0,0 +1,237 @@ +import asyncio +from typing import Callable, Optional, Tuple + +import ray +from ray._common.constants import HEAD_NODE_RESOURCE_NAME +from ray._raylet import GcsClient +from ray.serve._private.cluster_node_info_cache import ( + ClusterNodeInfoCache, + DefaultClusterNodeInfoCache, +) +from ray.serve._private.common import ( + CreatePlacementGroupRequest, + DeploymentHandleSource, + DeploymentID, + EndpointInfo, + RequestMetadata, + RequestProtocol, +) +from ray.serve._private.constants import ( + CONTROLLER_MAX_CONCURRENCY, + RAY_SERVE_ENABLE_TASK_EVENTS, + RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING, + RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP, + SERVE_CONTROLLER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.deployment_scheduler import ( + DefaultDeploymentScheduler, + DeploymentScheduler, +) +from ray.serve._private.grpc_util import gRPCGenericServer +from ray.serve._private.handle_options import DynamicHandleOptions, InitHandleOptions +from ray.serve._private.router import CurrentLoopRouter, Router, SingletonThreadRouter +from ray.serve._private.utils import ( + generate_request_id, + get_current_actor_id, + get_head_node_id, + inside_ray_client_context, + resolve_deployment_response, +) +from ray.util.placement_group import PlacementGroup + +# NOTE: Please read carefully before changing! +# +# These methods are common extension points, therefore these should be +# changed as a Developer API, ie methods should not be renamed, have their +# API modified w/o substantial enough justification + + +def create_cluster_node_info_cache(gcs_client: GcsClient) -> ClusterNodeInfoCache: + return DefaultClusterNodeInfoCache(gcs_client) + + +CreatePlacementGroupFn = Callable[[CreatePlacementGroupRequest], PlacementGroup] + + +def _default_create_placement_group( + request: CreatePlacementGroupRequest, +) -> PlacementGroup: + return ray.util.placement_group( + request.bundles, + request.strategy, + _soft_target_node_id=request.target_node_id, + name=request.name, + lifetime="detached", + ) + + +def create_deployment_scheduler( + cluster_node_info_cache: ClusterNodeInfoCache, + head_node_id_override: Optional[str] = None, + create_placement_group_fn_override: Optional[CreatePlacementGroupFn] = None, +) -> DeploymentScheduler: + head_node_id = head_node_id_override or get_head_node_id() + return DefaultDeploymentScheduler( + cluster_node_info_cache, + head_node_id, + create_placement_group_fn=create_placement_group_fn_override + or _default_create_placement_group, + ) + + +def create_replica_impl(**kwargs): + from ray.serve._private.replica import Replica + + return Replica(**kwargs) + + +def create_replica_metrics_manager(**kwargs): + from ray.serve._private.replica import ReplicaMetricsManager + + return ReplicaMetricsManager(**kwargs) + + +def create_dynamic_handle_options(**kwargs): + return DynamicHandleOptions(**kwargs) + + +def create_init_handle_options(**kwargs): + return InitHandleOptions.create(**kwargs) + + +def get_request_metadata(init_options, handle_options): + _request_context = ray.serve.context._get_serve_request_context() + + request_protocol = RequestProtocol.UNDEFINED + if init_options and init_options._source == DeploymentHandleSource.PROXY: + if _request_context.is_http_request: + request_protocol = RequestProtocol.HTTP + elif _request_context.grpc_context: + request_protocol = RequestProtocol.GRPC + + return RequestMetadata( + request_id=_request_context.request_id + if _request_context.request_id + else generate_request_id(), + internal_request_id=_request_context._internal_request_id + if _request_context._internal_request_id + else generate_request_id(), + call_method=handle_options.method_name, + route=_request_context.route, + app_name=_request_context.app_name, + multiplexed_model_id=handle_options.multiplexed_model_id, + is_streaming=handle_options.stream, + _request_protocol=request_protocol, + grpc_context=_request_context.grpc_context, + _by_reference=True, + ) + + +def _get_node_id_and_az() -> Tuple[str, Optional[str]]: + node_id = ray.get_runtime_context().get_node_id() + try: + cluster_node_info_cache = create_cluster_node_info_cache( + GcsClient(address=ray.get_runtime_context().gcs_address) + ) + cluster_node_info_cache.update() + az = cluster_node_info_cache.get_node_az(node_id) + except Exception: + az = None + + return node_id, az + + +# Interface definition for create_router. +CreateRouterCallable = Callable[[str, DeploymentID, InitHandleOptions], Router] + + +def create_router( + handle_id: str, + deployment_id: DeploymentID, + handle_options: InitHandleOptions, + request_router_class: Optional[Callable] = None, +) -> Router: + # NOTE(edoakes): this is lazy due to a nasty circular import that should be fixed. + from ray.serve.context import _get_global_client + + actor_id = get_current_actor_id() + node_id, availability_zone = _get_node_id_and_az() + controller_handle = _get_global_client()._controller + is_inside_ray_client_context = inside_ray_client_context() + + if handle_options._run_router_in_separate_loop: + router_wrapper_cls = SingletonThreadRouter + else: + try: + asyncio.get_running_loop() + except RuntimeError: + raise RuntimeError( + "No event loop running. You cannot use a handle initialized with " + "`_run_router_in_separate_loop=False` when not inside an asyncio event " + "loop." + ) + + router_wrapper_cls = CurrentLoopRouter + + return router_wrapper_cls( + controller_handle=controller_handle, + deployment_id=deployment_id, + handle_id=handle_id, + self_actor_id=actor_id, + handle_source=handle_options._source, + request_router_class=request_router_class, + # Streaming ObjectRefGenerators are not supported in Ray Client + enable_strict_max_ongoing_requests=not is_inside_ray_client_context, + resolve_request_arg_func=resolve_deployment_response, + node_id=node_id, + availability_zone=availability_zone, + prefer_local_node_routing=handle_options._prefer_local_routing, + ) + + +def add_grpc_address(grpc_server: gRPCGenericServer, server_address: str): + """Helper function to add an address to a gRPC server.""" + grpc_server.add_insecure_port(server_address) + + +def get_proxy_handle(endpoint: DeploymentID, info: EndpointInfo): + # NOTE(zcin): needs to be lazy import due to a circular dependency. + # We should not be importing from application_state in context. + from ray.serve.context import _get_global_client + + client = _get_global_client() + handle = client.get_handle(endpoint.name, endpoint.app_name, check_exists=True) + + # NOTE(zcin): It's possible that a handle is already initialized + # if a deployment with the same name and application name was + # deleted, then redeployed later. However this is not an issue since + # we initialize all handles with the same init options. + if not handle.is_initialized: + # NOTE(zcin): since the router is eagerly initialized here, the + # proxy will receive the replica set from the controller early. + handle._init( + _prefer_local_routing=RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING, + _source=DeploymentHandleSource.PROXY, + _run_router_in_separate_loop=RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP, + ) + + return handle.options(stream=not info.app_is_cross_language) + + +def get_controller_impl(): + from ray.serve._private.controller import ServeController + + controller_impl = ray.remote( + name=SERVE_CONTROLLER_NAME, + namespace=SERVE_NAMESPACE, + num_cpus=0, + lifetime="detached", + max_restarts=-1, + max_task_retries=-1, + resources={HEAD_NODE_RESOURCE_NAME: 0.001}, + max_concurrency=CONTROLLER_MAX_CONCURRENCY, + enable_task_events=RAY_SERVE_ENABLE_TASK_EVENTS, + )(ServeController) + + return controller_impl diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deploy_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deploy_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a0dc0909b066f5bae4facb2eebbf653ba249bda0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deploy_utils.py @@ -0,0 +1,109 @@ +import hashlib +import json +import logging +import time +from typing import Any, Dict, Optional, Union + +import ray +import ray.util.serialization_addons +from ray.serve._private.common import DeploymentID +from ray.serve._private.config import DeploymentConfig, ReplicaConfig +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve.schema import ServeApplicationSchema + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def get_deploy_args( + name: str, + replica_config: ReplicaConfig, + ingress: bool = False, + deployment_config: Optional[Union[DeploymentConfig, Dict[str, Any]]] = None, + version: Optional[str] = None, + route_prefix: Optional[str] = None, +) -> Dict: + """ + Takes a deployment's configuration, and returns the arguments needed + for the controller to deploy it. + """ + if deployment_config is None: + deployment_config = {} + + if isinstance(deployment_config, dict): + deployment_config = DeploymentConfig.parse_obj(deployment_config) + elif not isinstance(deployment_config, DeploymentConfig): + raise TypeError("config must be a DeploymentConfig or a dictionary.") + + deployment_config.version = version + + controller_deploy_args = { + "deployment_name": name, + "deployment_config_proto_bytes": deployment_config.to_proto_bytes(), + "replica_config_proto_bytes": replica_config.to_proto_bytes(), + "route_prefix": route_prefix, + "deployer_job_id": ray.get_runtime_context().get_job_id(), + "ingress": ingress, + } + + return controller_deploy_args + + +def deploy_args_to_deployment_info( + deployment_name: str, + deployment_config_proto_bytes: bytes, + replica_config_proto_bytes: bytes, + deployer_job_id: Union[str, bytes], + app_name: Optional[str] = None, + ingress: bool = False, + route_prefix: Optional[str] = None, + **kwargs, +) -> DeploymentInfo: + """Takes deployment args passed to the controller after building an application and + constructs a DeploymentInfo object. + """ + + deployment_config = DeploymentConfig.from_proto_bytes(deployment_config_proto_bytes) + version = deployment_config.version + replica_config = ReplicaConfig.from_proto_bytes( + replica_config_proto_bytes, deployment_config.needs_pickle() + ) + + # Java API passes in JobID as bytes + if isinstance(deployer_job_id, bytes): + deployer_job_id = ray.JobID.from_int( + int.from_bytes(deployer_job_id, "little") + ).hex() + + return DeploymentInfo( + actor_name=DeploymentID( + name=deployment_name, app_name=app_name + ).to_replica_actor_class_name(), + version=version, + deployment_config=deployment_config, + replica_config=replica_config, + deployer_job_id=deployer_job_id, + start_time_ms=int(time.time() * 1000), + route_prefix=route_prefix, + ingress=ingress, + ) + + +def get_app_code_version(app_config: ServeApplicationSchema) -> str: + """Returns the code version of an application. + + Args: + app_config: The application config. + + Returns: a hash of the import path and (application level) runtime env representing + the code version of the application. + """ + encoded = json.dumps( + { + "import_path": app_config.import_path, + "runtime_env": app_config.runtime_env, + "args": app_config.args, + }, + sort_keys=True, + ).encode("utf-8") + return hashlib.sha1(encoded).hexdigest() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_info.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_info.py new file mode 100644 index 0000000000000000000000000000000000000000..5413c7878aa013e68f93cc0b15acab9880a5cc05 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_info.py @@ -0,0 +1,169 @@ +from typing import Any, Dict, Optional + +import ray +from ray.serve._private.common import TargetCapacityDirection +from ray.serve._private.config import DeploymentConfig, ReplicaConfig +from ray.serve.generated.serve_pb2 import ( + DeploymentInfo as DeploymentInfoProto, + TargetCapacityDirection as TargetCapacityDirectionProto, +) + + +class DeploymentInfo: + def __init__( + self, + deployment_config: DeploymentConfig, + replica_config: ReplicaConfig, + start_time_ms: int, + deployer_job_id: str, + actor_name: Optional[str] = None, + version: Optional[str] = None, + end_time_ms: Optional[int] = None, + route_prefix: str = None, + ingress: bool = False, + target_capacity: Optional[float] = None, + target_capacity_direction: Optional[TargetCapacityDirection] = None, + ): + self.deployment_config = deployment_config + self.replica_config = replica_config + # The time when .deploy() was first called for this deployment. + self.start_time_ms = start_time_ms + self.actor_name = actor_name + self.version = version + self.deployer_job_id = deployer_job_id + # The time when this deployment was deleted. + self.end_time_ms = end_time_ms + + # ephermal state + self._cached_actor_def = None + + self.route_prefix = route_prefix + self.ingress = ingress + + self.target_capacity = target_capacity + self.target_capacity_direction = target_capacity_direction + + def __getstate__(self) -> Dict[Any, Any]: + clean_dict = self.__dict__.copy() + del clean_dict["_cached_actor_def"] + return clean_dict + + def __setstate__(self, d: Dict[Any, Any]) -> None: + self.__dict__ = d + self._cached_actor_def = None + + def update( + self, + deployment_config: DeploymentConfig = None, + replica_config: ReplicaConfig = None, + version: str = None, + route_prefix: str = None, + ) -> "DeploymentInfo": + return DeploymentInfo( + deployment_config=deployment_config or self.deployment_config, + replica_config=replica_config or self.replica_config, + start_time_ms=self.start_time_ms, + deployer_job_id=self.deployer_job_id, + actor_name=self.actor_name, + version=version or self.version, + end_time_ms=self.end_time_ms, + route_prefix=route_prefix or self.route_prefix, + ingress=self.ingress, + target_capacity=self.target_capacity, + target_capacity_direction=self.target_capacity_direction, + ) + + def set_target_capacity( + self, + new_target_capacity: Optional[float], + new_target_capacity_direction: Optional[TargetCapacityDirection], + ): + self.target_capacity = new_target_capacity + self.target_capacity_direction = new_target_capacity_direction + + def config_changed(self, other) -> bool: + return ( + self.deployment_config != other.deployment_config + or self.replica_config.ray_actor_options + != other.replica_config.ray_actor_options + or other.version is None + or self.version != other.version + ) + + @property + def actor_def(self): + if self._cached_actor_def is None: + assert self.actor_name is not None + + # Break circular import :(. + from ray.serve._private.replica import ReplicaActor + + # Dynamically create a new class with custom name here so Ray picks it up + # correctly in actor metadata table and observability stack. + self._cached_actor_def = ray.remote( + type( + self.actor_name, + (ReplicaActor,), + dict(ReplicaActor.__dict__), + ) + ) + + return self._cached_actor_def + + @classmethod + def from_proto(cls, proto: DeploymentInfoProto): + deployment_config = ( + DeploymentConfig.from_proto(proto.deployment_config) + if proto.deployment_config + else None + ) + + target_capacity = proto.target_capacity if proto.target_capacity != -1 else None + + target_capacity_direction = TargetCapacityDirectionProto.Name( + proto.target_capacity_direction + ) + if target_capacity_direction == "UNSET": + target_capacity_direction = None + else: + target_capacity_direction = TargetCapacityDirection( + target_capacity_direction + ) + + data = { + "deployment_config": deployment_config, + "replica_config": ReplicaConfig.from_proto( + proto.replica_config, + deployment_config.needs_pickle() if deployment_config else True, + ), + "start_time_ms": proto.start_time_ms, + "actor_name": proto.actor_name if proto.actor_name != "" else None, + "version": proto.version if proto.version != "" else None, + "end_time_ms": proto.end_time_ms if proto.end_time_ms != 0 else None, + "deployer_job_id": ray.get_runtime_context().get_job_id(), + "target_capacity": target_capacity, + "target_capacity_direction": target_capacity_direction, + } + + return cls(**data) + + def to_proto(self): + data = { + "start_time_ms": self.start_time_ms, + "actor_name": self.actor_name, + "version": self.version, + "end_time_ms": self.end_time_ms, + } + if self.deployment_config: + data["deployment_config"] = self.deployment_config.to_proto() + if self.replica_config: + data["replica_config"] = self.replica_config.to_proto() + if self.target_capacity is None: + data["target_capacity"] = -1 + else: + data["target_capacity"] = self.target_capacity + if self.target_capacity_direction is None: + data["target_capacity_direction"] = TargetCapacityDirectionProto.UNSET + else: + data["target_capacity_direction"] = self.target_capacity_direction.name + return DeploymentInfoProto(**data) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_node.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_node.py new file mode 100644 index 0000000000000000000000000000000000000000..375c49e830c4788d973c555e0ede3d5f1c883730 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_node.py @@ -0,0 +1,56 @@ +from typing import Any, Dict, List, Optional, Tuple + +from ray.dag import DAGNode +from ray.dag.format_utils import get_dag_node_str +from ray.serve.deployment import Deployment +from ray.serve.handle import DeploymentHandle + + +class DeploymentNode(DAGNode): + """Represents a deployment node in a DAG authored Ray DAG API.""" + + def __init__( + self, + # For serve structured deployment, deployment body can be import path + # to the class or function instead. + deployment: Deployment, + app_name: str, + deployment_init_args: Tuple[Any], + deployment_init_kwargs: Dict[str, Any], + ray_actor_options: Dict[str, Any], + other_args_to_resolve: Optional[Dict[str, Any]] = None, + ): + # Assign instance variables in base class constructor. + super().__init__( + deployment_init_args, + deployment_init_kwargs, + ray_actor_options, + other_args_to_resolve=other_args_to_resolve, + ) + self._app_name = app_name + self._deployment = deployment + self._deployment_handle = DeploymentHandle( + self._deployment.name, self._app_name + ) + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ): + return DeploymentNode( + self._deployment, + self._app_name, + new_args, + new_kwargs, + new_options, + other_args_to_resolve=new_other_args_to_resolve, + ) + + def __str__(self) -> str: + return get_dag_node_str(self, str(self._deployment)) + + def get_deployment_name(self): + return self._deployment.name diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_scheduler.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..473044a657d74886fb3a2dc184e3d7ae2e234517 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_scheduler.py @@ -0,0 +1,813 @@ +import copy +import logging +import sys +from abc import ABC, abstractmethod +from collections import defaultdict +from dataclasses import dataclass +from enum import Enum +from functools import total_ordering +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +import ray +from ray.serve._private.cluster_node_info_cache import ClusterNodeInfoCache +from ray.serve._private.common import ( + CreatePlacementGroupRequest, + DeploymentID, + ReplicaID, +) +from ray.serve._private.config import ReplicaConfig +from ray.serve._private.constants import ( + RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES, + RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY, + SERVE_LOGGER_NAME, +) +from ray.util.scheduling_strategies import ( + LabelMatchExpressionsT, + NodeAffinitySchedulingStrategy, + NodeLabelSchedulingStrategy, + PlacementGroupSchedulingStrategy, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class SpreadDeploymentSchedulingPolicy: + """A scheduling policy that spreads replicas with best effort.""" + + pass + + +@total_ordering +class Resources(dict): + # Custom resource priority from environment variable + CUSTOM_PRIORITY: List[str] = RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES + EPSILON = 1e-9 + + def get(self, key: str): + val = super().get(key) + if val is not None: + return val + + # Implicit resources by default have 1 total + if key.startswith(ray._raylet.IMPLICIT_RESOURCE_PREFIX): + return 1 + + # Otherwise by default there is 0 of this resource + return 0 + + def can_fit(self, other): + keys = set(self.keys()) | set(other.keys()) + # We add a small epsilon to avoid floating point precision issues. + return all(self.get(k) + self.EPSILON >= other.get(k) for k in keys) + + def __eq__(self, other): + keys = set(self.keys()) | set(other.keys()) + return all([self.get(k) == other.get(k) for k in keys]) + + def __add__(self, other): + keys = set(self.keys()) | set(other.keys()) + + kwargs = dict() + for key in keys: + if key.startswith(ray._raylet.IMPLICIT_RESOURCE_PREFIX): + kwargs[key] = min(1.0, self.get(key) + other.get(key)) + else: + kwargs[key] = self.get(key) + other.get(key) + + return Resources(kwargs) + + def __sub__(self, other): + keys = set(self.keys()) | set(other.keys()) + kwargs = {key: self.get(key) - other.get(key) for key in keys} + return Resources(kwargs) + + def __lt__(self, other): + """Determines priority when sorting a list of SoftResources. + 1. Custom resources defined in RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES (sorted by priority) + 2. GPU + 3. CPU + 4. memory + 5. Other custom resources + This means a resource with a larger number of high-priority resources is always + sorted higher than one with fewer, regardless of other types. + """ + + keys = set(self.keys()) | set(other.keys()) + custom_keys = keys - {"GPU", "CPU", "memory"} + + for key in self.CUSTOM_PRIORITY: + if self.get(key) < other.get(key): + return True + elif self.get(key) > other.get(key): + return False + + if self.get("GPU") < other.get("GPU"): + return True + elif self.get("GPU") > other.get("GPU"): + return False + + if self.get("CPU") < other.get("CPU"): + return True + elif self.get("CPU") > other.get("CPU"): + return False + + if self.get("memory") < other.get("memory"): + return True + elif self.get("memory") > other.get("memory"): + return False + + for key in custom_keys - set(self.CUSTOM_PRIORITY): + if self.get(key) < other.get(key): + return True + elif self.get(key) > other.get(key): + return False + + return False + + +class ReplicaSchedulingRequestStatus(str, Enum): + """The status of a replica scheduling request.""" + + IN_PROGRESS = "IN_PROGRESS" + SUCCEEDED = "SUCCEEDED" + ACTOR_CREATION_FAILED = "ACTOR_CREATION_FAILED" + PLACEMENT_GROUP_CREATION_FAILED = "PLACEMENT_GROUP_CREATION_FAILED" + + +@dataclass +class ReplicaSchedulingRequest: + """Request to schedule a single replica. + + The scheduler is responsible for scheduling + based on the deployment scheduling policy. + """ + + replica_id: ReplicaID + actor_def: ray.actor.ActorClass + actor_resources: Dict + actor_options: Dict + actor_init_args: Tuple + on_scheduled: Callable + status: ReplicaSchedulingRequestStatus = ReplicaSchedulingRequestStatus.IN_PROGRESS + # Placement group bundles and strategy *for this replica*. + # These are optional: by default replicas do not have a placement group. + placement_group_bundles: Optional[List[Dict[str, float]]] = None + placement_group_strategy: Optional[str] = None + max_replicas_per_node: Optional[int] = None + + @property + def required_resources(self) -> Resources: + """The resources required to schedule this replica on a node. + + If this replica uses a strict pack placement group, the + required resources is the sum of the placement group bundles. + Otherwise, required resources is simply the actor resources. + """ + + if ( + self.placement_group_bundles is not None + and self.placement_group_strategy == "STRICT_PACK" + ): + return sum( + [Resources(bundle) for bundle in self.placement_group_bundles], + Resources(), + ) + else: + required = Resources(self.actor_resources) + + # Using implicit resource (resources that every node + # implicitly has and total is 1) + # to limit the number of replicas on a single node. + if self.max_replicas_per_node is not None: + deployment_id = self.replica_id.deployment_id + implicit_resource = ( + f"{ray._raylet.IMPLICIT_RESOURCE_PREFIX}" + f"{deployment_id.app_name}:{deployment_id.name}" + ) + required[implicit_resource] = 1.0 / self.max_replicas_per_node + + return required + + +@dataclass +class DeploymentDownscaleRequest: + """Request to stop a certain number of replicas. + + The scheduler is responsible for + choosing the replicas to stop. + """ + + deployment_id: DeploymentID + num_to_stop: int + + +@dataclass +class DeploymentSchedulingInfo: + deployment_id: DeploymentID + scheduling_policy: Any + actor_resources: Optional[Resources] = None + placement_group_bundles: Optional[List[Resources]] = None + placement_group_strategy: Optional[str] = None + max_replicas_per_node: Optional[int] = None + + @property + def required_resources(self) -> Resources: + """The resources required to schedule a replica of this deployment on a node. + + If this replicas uses a strict pack placement group, the + required resources is the sum of the placement group bundles. + Otherwise, required resources is simply the actor resources. + """ + + if ( + self.placement_group_bundles is not None + and self.placement_group_strategy == "STRICT_PACK" + ): + return sum(self.placement_group_bundles, Resources()) + else: + required = self.actor_resources + + # Using implicit resource (resources that every node + # implicitly has and total is 1) + # to limit the number of replicas on a single node. + if self.max_replicas_per_node: + implicit_resource = ( + f"{ray._raylet.IMPLICIT_RESOURCE_PREFIX}" + f"{self.deployment_id.app_name}:{self.deployment_id.name}" + ) + required[implicit_resource] = 1.0 / self.max_replicas_per_node + + return required + + def is_non_strict_pack_pg(self) -> bool: + return ( + self.placement_group_bundles is not None + and self.placement_group_strategy != "STRICT_PACK" + ) + + +@dataclass +class LaunchingReplicaInfo: + """Describes a replica for which a schedule request has been sent to + core but has not been scheduled (placed on a node) yet. + + Args: + target_node_id: The exact node that's been requested for this + replica. This is best effort and may not be fulfilled. + target_labels: The node labels that have been requested for this + replica. This is best effort and may not be fulfilled. + """ + + target_node_id: Optional[str] = None + target_labels: Optional[Dict[str, Any]] = None + + +def _flatten( + deployment_to_replicas: Dict[DeploymentID, Dict[ReplicaID, Any]] +) -> Dict[ReplicaID, Any]: + """Flattens a dict of {deployment_id: {replica_id: val}} to {replica_id: val}.""" + + return { + replica_id: val + for replicas in deployment_to_replicas.values() + for replica_id, val in replicas.items() + } + + +class DeploymentScheduler(ABC): + """A centralized scheduler for all Serve deployments. + + It makes a batch of scheduling decisions in each update cycle. + """ + + def __init__( + self, + cluster_node_info_cache: ClusterNodeInfoCache, + head_node_id: str, + create_placement_group_fn: Callable, + ): + # {deployment_id: scheduling_policy} + self._deployments: Dict[DeploymentID, DeploymentSchedulingInfo] = {} + # Replicas that are waiting to be scheduled. + # {deployment_id: {replica_id: deployment_upscale_request}} + self._pending_replicas: Dict[ + DeploymentID, Dict[str, ReplicaSchedulingRequest] + ] = defaultdict(dict) + # Replicas that are being scheduled. + # The underlying actors have been submitted. + # {deployment_id: {replica_id: target_node_id}} + self._launching_replicas: Dict[ + DeploymentID, Dict[str, LaunchingReplicaInfo] + ] = defaultdict(dict) + # Replicas that are recovering. + # We don't know where those replicas are running. + # {deployment_id: {replica_id}} + self._recovering_replicas = defaultdict(set) + # Replicas that are running. + # We know where those replicas are running. + # {deployment_id: {replica_id: running_node_id}} + self._running_replicas = defaultdict(dict) + + self._cluster_node_info_cache = cluster_node_info_cache + self._head_node_id = head_node_id + self._create_placement_group_fn = create_placement_group_fn + + def on_deployment_created( + self, + deployment_id: DeploymentID, + scheduling_policy: SpreadDeploymentSchedulingPolicy, + ) -> None: + """Called whenever a new deployment is created.""" + assert deployment_id not in self._pending_replicas + assert deployment_id not in self._launching_replicas + assert deployment_id not in self._recovering_replicas + assert deployment_id not in self._running_replicas + self._deployments[deployment_id] = DeploymentSchedulingInfo( + deployment_id=deployment_id, scheduling_policy=scheduling_policy + ) + + def on_deployment_deployed( + self, + deployment_id: DeploymentID, + replica_config: ReplicaConfig, + ) -> None: + assert deployment_id in self._deployments + + info = self._deployments[deployment_id] + info.actor_resources = Resources(replica_config.resource_dict) + info.max_replicas_per_node = replica_config.max_replicas_per_node + if replica_config.placement_group_bundles: + info.placement_group_bundles = [ + Resources(bundle) for bundle in replica_config.placement_group_bundles + ] + if replica_config.placement_group_strategy: + info.placement_group_strategy = replica_config.placement_group_strategy + + def on_deployment_deleted(self, deployment_id: DeploymentID) -> None: + """Called whenever a deployment is deleted.""" + assert not self._pending_replicas[deployment_id] + self._pending_replicas.pop(deployment_id, None) + + assert not self._launching_replicas[deployment_id] + self._launching_replicas.pop(deployment_id, None) + + assert not self._recovering_replicas[deployment_id] + self._recovering_replicas.pop(deployment_id, None) + + assert not self._running_replicas[deployment_id] + self._running_replicas.pop(deployment_id, None) + + del self._deployments[deployment_id] + + def on_replica_stopping(self, replica_id: ReplicaID) -> None: + """Called whenever a deployment replica is being stopped.""" + deployment_id = replica_id.deployment_id + self._pending_replicas[deployment_id].pop(replica_id, None) + self._launching_replicas[deployment_id].pop(replica_id, None) + self._recovering_replicas[deployment_id].discard(replica_id) + self._running_replicas[deployment_id].pop(replica_id, None) + + def on_replica_running(self, replica_id: ReplicaID, node_id: str) -> None: + """Called whenever a deployment replica is running with a known node id.""" + deployment_id = replica_id.deployment_id + assert replica_id not in self._pending_replicas[deployment_id] + + self._launching_replicas[deployment_id].pop(replica_id, None) + self._recovering_replicas[deployment_id].discard(replica_id) + + self._running_replicas[deployment_id][replica_id] = node_id + + def on_replica_recovering(self, replica_id: ReplicaID) -> None: + """Called whenever a deployment replica is recovering.""" + deployment_id = replica_id.deployment_id + assert replica_id not in self._pending_replicas[deployment_id] + assert replica_id not in self._launching_replicas[deployment_id] + assert replica_id not in self._running_replicas[deployment_id] + assert replica_id not in self._recovering_replicas[deployment_id] + + self._recovering_replicas[deployment_id].add(replica_id) + + def _on_replica_launching( + self, + replica_id: ReplicaID, + target_node_id: Optional[str] = None, + target_labels: Optional[Dict[str, Any]] = None, + ): + deployment_id = replica_id.deployment_id + self._launching_replicas[deployment_id][replica_id] = LaunchingReplicaInfo( + target_node_id=target_node_id, target_labels=target_labels + ) + + def _get_node_to_running_replicas( + self, deployment_id: Optional[DeploymentID] = None + ) -> Dict[str, Set[ReplicaID]]: + res = defaultdict(set) + if deployment_id: + for replica_id, node_id in self._running_replicas[deployment_id].items(): + res[node_id].add(replica_id) + else: + for _, replicas in self._running_replicas.items(): + for replica_id, node_id in replicas.items(): + res[node_id].add(replica_id) + + return res + + def _get_available_resources_per_node(self) -> Dict[str, Resources]: + """Gets current available resources per node. + + This returns a conservative view of the available resources + currently in the cluster. It returns the minimum of: + + 1. The available resources per node fetched and cached from the + GCS every control loop. + 2. The remaining resources left over on each node after + subtracting the resources taken up by running (already + scheduled by core) and launching (to-be-scheduled and soft + targeting that node) replicas. + + Note that (1) may not be accurate because it uses cached info + and there is a delay from fetching data from GCS, and (2) may + not be accurate because there can be other actors (not replicas) + running in the cluster, and launching replicas may not end up on + the node we're targeting. So the information returned from this + method is only best effort. + """ + + available_resources = ( + self._cluster_node_info_cache.get_available_resources_per_node() + ) + total_resources = self._cluster_node_info_cache.get_total_resources_per_node() + + gcs_info = {node_id: Resources(r) for node_id, r in available_resources.items()} + + # Manually calculate available resources per node by subtracting + # launching and running replicas from total resources + total_minus_replicas = { + node_id: Resources(resources) + for node_id, resources in total_resources.items() + } + for deployment_id, replicas in self._launching_replicas.items(): + deployment = self._deployments[deployment_id] + for info in replicas.values(): + target_node_id = info.target_node_id + if not target_node_id or target_node_id not in total_minus_replicas: + continue + + total_minus_replicas[target_node_id] -= deployment.required_resources + + for deployment_id, replicas in self._running_replicas.items(): + deployment = self._deployments[deployment_id] + for node_id in replicas.values(): + if node_id not in total_minus_replicas: + continue + + total_minus_replicas[node_id] -= deployment.required_resources + + def custom_min(a: Resources, b: Resources): + keys = set(a.keys()) | set(b.keys()) + res = Resources() + for key in keys: + res[key] = min(a.get(key), b.get(key)) + return res + + # Filter by active node ids (alive but not draining) + return { + node_id: custom_min( + gcs_info.get(node_id, Resources()), + total_minus_replicas.get(node_id, Resources()), + ) + for node_id in self._cluster_node_info_cache.get_active_node_ids() + } + + def _best_fit_node( + self, required_resources: Resources, available_resources: Dict[str, Resources] + ) -> Optional[str]: + """Chooses a node using best fit strategy. + + This strategy picks the node where, if the required resources + were to be scheduled on that node, it will leave the smallest + remaining space. This minimizes fragmentation of resources. + """ + + min_remaining_space = None + chosen_node = None + + for node_id in available_resources: + if not available_resources[node_id].can_fit(required_resources): + continue + + # TODO(zcin): We can make this better by only considering + # custom resources that required_resources has. + remaining_space = available_resources[node_id] - required_resources + if min_remaining_space is None or remaining_space < min_remaining_space: + min_remaining_space = remaining_space + chosen_node = node_id + + return chosen_node + + @abstractmethod + def schedule( + self, + upscales: Dict[DeploymentID, List[ReplicaSchedulingRequest]], + downscales: Dict[DeploymentID, DeploymentDownscaleRequest], + ) -> Dict[DeploymentID, Set[ReplicaID]]: + """Called for each update cycle to do batch scheduling. + + Args: + upscales: a dict of deployment name to a list of replicas to schedule. + downscales: a dict of deployment name to a downscale request. + + Returns: + The name of replicas to stop for each deployment. + """ + raise NotImplementedError + + def _schedule_replica( + self, + scheduling_request: ReplicaSchedulingRequest, + default_scheduling_strategy: str, + target_node_id: Optional[str] = None, + target_labels: Optional[LabelMatchExpressionsT] = None, + ): + """Schedule a replica from a scheduling request. + + The following special scheduling strategies will be used, in + order of highest to lowest priority. + 1. If a replica requires placement groups, we will choose to use + a `PlacementGroupSchedulingStrategy`. This can also take a + target node into consideration (soft target), if provided. + However it cannot take into account target labels. + 2. If a `target_node_id` is provided, we will choose to use a + `NodeAffinitySchedulingStrategy`. + 3. If `target_labels` is provided, we will choose to use a + `NodeLabelSchedulingStrategy`. + + Args: + scheduling_request: A request to schedule a replica. + default_scheduling_strategy: The scheduling strategy to fall + back to if no special scheduling strategy is necessary. + target_node_id: Attempt to schedule this replica onto this + target node. + target_labels: Attempt to schedule this replica onto nodes + with these target labels. + """ + + replica_id = scheduling_request.replica_id + deployment_id = replica_id.deployment_id + placement_group = None + + scheduling_strategy = default_scheduling_strategy + if scheduling_request.placement_group_bundles is not None: + placement_group_strategy = ( + scheduling_request.placement_group_strategy + if scheduling_request.placement_group_strategy + else "PACK" + ) + try: + pg = self._create_placement_group_fn( + CreatePlacementGroupRequest( + bundles=scheduling_request.placement_group_bundles, + strategy=placement_group_strategy, + target_node_id=target_node_id, + name=scheduling_request.actor_options["name"], + ) + ) + except Exception: + # We add a defensive exception here, so the controller can + # make progress even if the placement group isn't created. + # See https://github.com/ray-project/ray/issues/43888. + logger.exception( + f"Failed to create a placement group for {replica_id}." + ) + scheduling_request.status = ( + ReplicaSchedulingRequestStatus.PLACEMENT_GROUP_CREATION_FAILED + ) + return + scheduling_strategy = PlacementGroupSchedulingStrategy( + placement_group=pg, + placement_group_capture_child_tasks=True, + ) + target_labels = None + elif target_node_id is not None: + scheduling_strategy = NodeAffinitySchedulingStrategy( + node_id=target_node_id, soft=True, _spill_on_unavailable=True + ) + target_labels = None + elif target_labels is not None: + scheduling_strategy = NodeLabelSchedulingStrategy( + hard={}, soft=target_labels + ) + target_node_id = None + + actor_options = copy.copy(scheduling_request.actor_options) + if scheduling_request.max_replicas_per_node is not None: + if "resources" not in actor_options: + actor_options["resources"] = {} + # Using implicit resource (resources that every node + # implicitly has and total is 1) + # to limit the number of replicas on a single node. + actor_options["resources"][ + f"{ray._raylet.IMPLICIT_RESOURCE_PREFIX}" + f"{deployment_id.app_name}:{deployment_id.name}" + ] = (1.0 / scheduling_request.max_replicas_per_node) + + try: + actor_handle = scheduling_request.actor_def.options( + scheduling_strategy=scheduling_strategy, + **actor_options, + ).remote(*scheduling_request.actor_init_args) + except Exception: + # We add a defensive exception here, so the controller can + # make progress even if the actor options are misconfigured. + logger.exception(f"Failed to create an actor for {replica_id}.") + scheduling_request.status = ( + ReplicaSchedulingRequestStatus.ACTOR_CREATION_FAILED + ) + return + + del self._pending_replicas[deployment_id][replica_id] + self._on_replica_launching( + replica_id, target_node_id=target_node_id, target_labels=target_labels + ) + + if isinstance(scheduling_strategy, PlacementGroupSchedulingStrategy): + placement_group = scheduling_strategy.placement_group + + scheduling_request.status = ReplicaSchedulingRequestStatus.SUCCEEDED + scheduling_request.on_scheduled(actor_handle, placement_group=placement_group) + + @abstractmethod + def get_node_to_compact( + self, allow_new_compaction: bool + ) -> Optional[Tuple[str, float]]: + """Returns a node ID to be compacted and a compaction deadlne.""" + raise NotImplementedError + + +class DefaultDeploymentScheduler(DeploymentScheduler): + def schedule( + self, + upscales: Dict[DeploymentID, List[ReplicaSchedulingRequest]], + downscales: Dict[DeploymentID, DeploymentDownscaleRequest], + ) -> Dict[DeploymentID, Set[ReplicaID]]: + """Called for each update cycle to do batch scheduling. + + Args: + upscales: a dict of deployment name to a list of replicas to schedule. + downscales: a dict of deployment name to a downscale request. + + Returns: + The IDs of replicas to stop for each deployment. + """ + for upscale in upscales.values(): + for scheduling_request in upscale: + replica_id = scheduling_request.replica_id + deployment_id = replica_id.deployment_id + self._pending_replicas[deployment_id][replica_id] = scheduling_request + + non_strict_pack_pgs_exist = any( + d.is_non_strict_pack_pg() for d in self._deployments.values() + ) + # Schedule replicas using compact strategy. + if RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY and not non_strict_pack_pgs_exist: + # Flatten dict of deployment replicas into all replicas, + # then sort by decreasing resource size + all_scheduling_requests = sorted( + _flatten(self._pending_replicas).values(), + key=lambda r: r.required_resources, + reverse=True, + ) + + # Schedule each replica + for scheduling_request in all_scheduling_requests: + target_node = self._find_best_available_node( + scheduling_request.required_resources, + self._get_available_resources_per_node(), + ) + + self._schedule_replica( + scheduling_request, + default_scheduling_strategy="DEFAULT", + target_node_id=target_node, + ) + + else: + for pending_replicas in self._pending_replicas.values(): + if not pending_replicas: + continue + + for scheduling_request in list(pending_replicas.values()): + self._schedule_replica( + scheduling_request=scheduling_request, + default_scheduling_strategy="SPREAD", + ) + + deployment_to_replicas_to_stop = {} + for downscale in downscales.values(): + deployment_to_replicas_to_stop[ + downscale.deployment_id + ] = self._get_replicas_to_stop( + downscale.deployment_id, downscale.num_to_stop + ) + + return deployment_to_replicas_to_stop + + def _get_replicas_to_stop( + self, deployment_id: DeploymentID, max_num_to_stop: int + ) -> Set[ReplicaID]: + """Prioritize replicas running on a node with fewest replicas of + all deployments. + + This algorithm helps to scale down more intelligently because it can + relinquish nodes faster. Note that this algorithm doesn't consider + other non-serve actors on the same node. See more at + https://github.com/ray-project/ray/issues/20599. + """ + replicas_to_stop = set() + + # Replicas not in running state don't have node id. + # We will prioritize those first. + pending_launching_recovering_replicas = set().union( + self._pending_replicas[deployment_id].keys(), + self._launching_replicas[deployment_id].keys(), + self._recovering_replicas[deployment_id], + ) + for ( + pending_launching_recovering_replica + ) in pending_launching_recovering_replicas: + if len(replicas_to_stop) == max_num_to_stop: + return replicas_to_stop + else: + replicas_to_stop.add(pending_launching_recovering_replica) + + node_to_running_replicas_of_target_deployment = ( + self._get_node_to_running_replicas(deployment_id) + ) + node_to_running_replicas_of_all_deployments = ( + self._get_node_to_running_replicas() + ) + + # Replicas on the head node has the lowest priority for downscaling + # since we cannot relinquish the head node. + def key(node_and_num_running_replicas_of_all_deployments): + return ( + len(node_and_num_running_replicas_of_all_deployments[1]) + if node_and_num_running_replicas_of_all_deployments[0] + != self._head_node_id + else sys.maxsize + ) + + for node_id, _ in sorted( + node_to_running_replicas_of_all_deployments.items(), key=key + ): + if node_id not in node_to_running_replicas_of_target_deployment: + continue + for running_replica in node_to_running_replicas_of_target_deployment[ + node_id + ]: + if len(replicas_to_stop) == max_num_to_stop: + return replicas_to_stop + else: + replicas_to_stop.add(running_replica) + + return replicas_to_stop + + def _find_best_available_node( + self, + required_resources: Resources, + available_resources_per_node: Dict[str, Resources], + ) -> Optional[str]: + """Chooses best available node to schedule the required resources. + + If there are available nodes, returns the node ID of the best + available node, minimizing fragmentation. Prefers non-idle nodes + over idle nodes. + """ + + node_to_running_replicas = self._get_node_to_running_replicas() + + non_idle_nodes = { + node_id: res + for node_id, res in available_resources_per_node.items() + if len(node_to_running_replicas.get(node_id, set())) > 0 + } + idle_nodes = { + node_id: res + for node_id, res in available_resources_per_node.items() + if len(node_to_running_replicas.get(node_id, set())) == 0 + } + + # 1. Prefer non-idle nodes + chosen_node = self._best_fit_node(required_resources, non_idle_nodes) + if chosen_node: + return chosen_node + + # 2. Consider idle nodes last + chosen_node = self._best_fit_node(required_resources, idle_nodes) + if chosen_node: + return chosen_node + + def get_node_to_compact( + self, allow_new_compaction: bool + ) -> Optional[Tuple[str, float]]: + return None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_state.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_state.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf969f9538fcf0643bbb6a7fc1b18812331b531 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/deployment_state.py @@ -0,0 +1,3018 @@ +import json +import logging +import math +import os +import random +import time +import traceback +from collections import defaultdict +from copy import copy +from dataclasses import dataclass +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +import ray +from ray import ObjectRef, cloudpickle +from ray._common import ray_constants +from ray.actor import ActorHandle +from ray.exceptions import RayActorError, RayError, RayTaskError, RuntimeEnvSetupError +from ray.serve import metrics +from ray.serve._private import default_impl +from ray.serve._private.autoscaling_state import AutoscalingStateManager +from ray.serve._private.cluster_node_info_cache import ClusterNodeInfoCache +from ray.serve._private.common import ( + DeploymentID, + DeploymentStatus, + DeploymentStatusInfo, + DeploymentStatusInternalTrigger, + DeploymentStatusTrigger, + DeploymentTargetInfo, + Duration, + ReplicaID, + ReplicaState, + RequestRoutingInfo, + RunningReplicaInfo, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT, + MAX_PER_REPLICA_RETRY_COUNT, + RAY_SERVE_ENABLE_TASK_EVENTS, + RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS, + RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY, + REPLICA_HEALTH_CHECK_UNHEALTHY_THRESHOLD, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.deployment_scheduler import ( + DeploymentDownscaleRequest, + DeploymentScheduler, + ReplicaSchedulingRequest, + ReplicaSchedulingRequestStatus, + SpreadDeploymentSchedulingPolicy, +) +from ray.serve._private.long_poll import LongPollHost, LongPollNamespace +from ray.serve._private.storage.kv_store import KVStoreBase +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + JavaActorHandleProxy, + check_obj_ref_ready_nowait, + get_capacity_adjusted_num_replicas, + get_random_string, + msgpack_deserialize, + msgpack_serialize, +) +from ray.serve._private.version import DeploymentVersion +from ray.serve.generated.serve_pb2 import DeploymentLanguage +from ray.serve.schema import ( + DeploymentDetails, + ReplicaDetails, + _deployment_info_to_schema, +) +from ray.util.placement_group import PlacementGroup + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class ReplicaStartupStatus(Enum): + PENDING_ALLOCATION = 1 + PENDING_INITIALIZATION = 2 + SUCCEEDED = 3 + FAILED = 4 + + +class ReplicaHealthCheckResponse(Enum): + NONE = 1 + SUCCEEDED = 2 + APP_FAILURE = 3 + ACTOR_CRASHED = 4 + + +@dataclass +class DeploymentTargetState: + """The current goal state for a deployment. + + info: contains the information needed to initialize a replica. + target_num_replicas: the number of replicas to run. This should already + be adjusted by the target_capacity. + version: the goal version of the deployment. + deleting: whether the deployment is being deleted. + """ + + info: Optional[DeploymentInfo] + target_num_replicas: int + version: Optional[DeploymentVersion] + deleting: bool + + @classmethod + def default(cls) -> "DeploymentTargetState": + return cls(None, -1, None, False) + + @classmethod + def create( + cls, + info: DeploymentInfo, + target_num_replicas: int, + *, + deleting: bool = False, + ) -> "DeploymentTargetState": + if deleting: + if target_num_replicas != 0: + raise ValueError( + "target_num_replicas must be 0 when setting target state " + f"to deleting. Got {target_num_replicas} instead." + ) + + version = DeploymentVersion( + info.version, + deployment_config=info.deployment_config, + ray_actor_options=info.replica_config.ray_actor_options, + placement_group_bundles=info.replica_config.placement_group_bundles, + placement_group_strategy=info.replica_config.placement_group_strategy, + max_replicas_per_node=info.replica_config.max_replicas_per_node, + route_prefix=info.route_prefix, + ) + + return cls(info, target_num_replicas, version, deleting) + + def is_scaled_copy_of(self, other_target_state: "DeploymentTargetState") -> bool: + """Checks if this target state is a scaled copy of another target state. + + A target state is a scaled copy of another target state if all + configurable info is identical, other than target_num_replicas. + + Returns: True if this target state contains a non-None DeploymentInfo + and is a scaled copy of the other target state. + """ + + if other_target_state.info is None: + return False + + return all( + [ + self.info.replica_config.ray_actor_options + == other_target_state.info.replica_config.ray_actor_options, + self.info.replica_config.placement_group_bundles + == other_target_state.info.replica_config.placement_group_bundles, + self.info.replica_config.placement_group_strategy + == other_target_state.info.replica_config.placement_group_strategy, + self.info.replica_config.max_replicas_per_node + == other_target_state.info.replica_config.max_replicas_per_node, + self.info.deployment_config.dict(exclude={"num_replicas"}) + == other_target_state.info.deployment_config.dict( + exclude={"num_replicas"} + ), + # TODO(zcin): version can be None, this is from an outdated codepath. + # We should remove outdated code, so version can never be None. + self.version, + self.version == other_target_state.version, + ] + ) + + +@dataclass +class DeploymentStateUpdateResult: + deleted: bool + any_replicas_recovering: bool + upscale: List[ReplicaSchedulingRequest] + downscale: Optional[DeploymentDownscaleRequest] + + +CHECKPOINT_KEY = "serve-deployment-state-checkpoint" +SLOW_STARTUP_WARNING_S = int(os.environ.get("SERVE_SLOW_STARTUP_WARNING_S", 30)) +SLOW_STARTUP_WARNING_PERIOD_S = int( + os.environ.get("SERVE_SLOW_STARTUP_WARNING_PERIOD_S", 30) +) + +ALL_REPLICA_STATES = list(ReplicaState) +_SCALING_LOG_ENABLED = os.environ.get("SERVE_ENABLE_SCALING_LOG", "0") != "0" +# Feature flag to disable forcibly shutting down replicas. +RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY = ( + os.environ.get("RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY", "0") + == "1" +) + + +def print_verbose_scaling_log(): + assert _SCALING_LOG_ENABLED + + log_path = "/tmp/ray/session_latest/logs/monitor.log" + last_n_lines = 50 + autoscaler_log_last_n_lines = [] + if os.path.exists(log_path): + with open(log_path) as f: + autoscaler_log_last_n_lines = f.readlines()[-last_n_lines:] + + debug_info = { + "nodes": ray.nodes(), + "available_resources": ray.available_resources(), + "total_resources": ray.cluster_resources(), + "autoscaler_logs": autoscaler_log_last_n_lines, + } + logger.error(f"Scaling information\n{json.dumps(debug_info, indent=2)}") + + +class ActorReplicaWrapper: + """Wraps a Ray actor for a deployment replica. + + This is primarily defined so that we can mock out actual Ray operations + for unit testing. + + *All Ray API calls should be made here, not in DeploymentState.* + """ + + def __init__( + self, + replica_id: ReplicaID, + version: DeploymentVersion, + ): + self._replica_id = replica_id + self._deployment_id = replica_id.deployment_id + self._actor_name = replica_id.to_full_id_str() + + # Populated in either self.start() or self.recover() + self._allocated_obj_ref: ObjectRef = None + self._ready_obj_ref: ObjectRef = None + + self._actor_resources: Dict[str, float] = None + # If the replica is being started, this will be the true version + # If the replica is being recovered, this will be the target + # version, which may be inconsistent with the actual replica + # version. If so, the actual version will be updated later after + # recover() and check_ready() + self._version: DeploymentVersion = version + self._healthy: bool = True + self._health_check_ref: Optional[ObjectRef] = None + self._last_health_check_time: float = 0.0 + self._consecutive_health_check_failures = 0 + self._initialization_latency_s: Optional[float] = None + self._port: Optional[int] = None + self._docs_path: Optional[str] = None + # Populated in `on_scheduled` or `recover`. + self._actor_handle: ActorHandle = None + self._placement_group: PlacementGroup = None + + # Populated after replica is allocated. + self._pid: int = None + self._actor_id: str = None + self._worker_id: str = None + self._node_id: str = None + self._node_ip: str = None + self._node_instance_id: str = None + self._log_file_path: str = None + + # Populated in self.stop(). + self._graceful_shutdown_ref: ObjectRef = None + + # todo: will be confused with deployment_config.is_cross_language + self._is_cross_language = False + self._deployment_is_cross_language = False + self._routing_stats: Dict[str, Any] = {} + self._record_routing_stats_ref: Optional[ObjectRef] = None + self._last_record_routing_stats_time: float = 0.0 + self._ingress: bool = False + + @property + def replica_id(self) -> str: + return self._replica_id + + @property + def deployment_name(self) -> str: + return self._deployment_id.name + + @property + def app_name(self) -> str: + return self._deployment_id.app_name + + @property + def is_cross_language(self) -> bool: + return self._is_cross_language + + @property + def actor_handle(self) -> Optional[ActorHandle]: + if not self._actor_handle: + try: + self._actor_handle = ray.get_actor( + self._actor_name, namespace=SERVE_NAMESPACE + ) + except ValueError: + self._actor_handle = None + + if self._is_cross_language: + assert isinstance(self._actor_handle, JavaActorHandleProxy) + return self._actor_handle.handle + + return self._actor_handle + + @property + def placement_group_bundles(self) -> Optional[List[Dict[str, float]]]: + if not self._placement_group: + return None + + return self._placement_group.bundle_specs + + @property + def version(self) -> DeploymentVersion: + """Replica version. This can be incorrect during state recovery. + + If the controller crashes and the deployment state is being + recovered, this will temporarily be the deployment-wide target + version, which may be inconsistent with the actual version + running on the replica actor. If so, the actual version will be + updated when the replica transitions from RECOVERING -> RUNNING + """ + return self._version + + @property + def deployment_config(self) -> DeploymentConfig: + """Deployment config. This can return an incorrect config during state recovery. + + If the controller hasn't yet recovered the up-to-date version + from the running replica actor, this property will return the + current target config for the deployment. + """ + return self._version.deployment_config + + @property + def docs_path(self) -> Optional[str]: + return self._docs_path + + @property + def max_ongoing_requests(self) -> int: + return self.deployment_config.max_ongoing_requests + + @property + def max_queued_requests(self) -> int: + return self.deployment_config.max_queued_requests + + @property + def graceful_shutdown_timeout_s(self) -> float: + return self.deployment_config.graceful_shutdown_timeout_s + + @property + def health_check_period_s(self) -> float: + return self.deployment_config.health_check_period_s + + @property + def health_check_timeout_s(self) -> float: + return self.deployment_config.health_check_timeout_s + + @property + def request_routing_stats_period_s(self) -> float: + return ( + self.deployment_config.request_router_config.request_routing_stats_period_s + ) + + @property + def request_routing_stats_timeout_s(self) -> float: + return ( + self.deployment_config.request_router_config.request_routing_stats_timeout_s + ) + + @property + def pid(self) -> Optional[int]: + """Returns the pid of the actor, None if not started.""" + return self._pid + + @property + def actor_id(self) -> Optional[str]: + """Returns the actor id, None if not started.""" + return self._actor_id + + @property + def worker_id(self) -> Optional[str]: + """Returns the worker id, None if not started.""" + return self._worker_id + + @property + def node_id(self) -> Optional[str]: + """Returns the node id of the actor, None if not placed.""" + return self._node_id + + @property + def node_ip(self) -> Optional[str]: + """Returns the node ip of the actor, None if not placed.""" + return self._node_ip + + @property + def node_instance_id(self) -> Optional[str]: + """Returns the node instance id of the actor, None if not placed.""" + return self._node_instance_id + + @property + def log_file_path(self) -> Optional[str]: + """Returns the relative log file path of the actor, None if not placed.""" + return self._log_file_path + + @property + def initialization_latency_s(self) -> Optional[float]: + """Returns the initialization latency for the replica actor. + + Returns None if the replica hasn't started yet. + + Note: this value isn't checkpointed, so if the controller restarts, + this value goes back to None. + """ + + return self._initialization_latency_s + + def start(self, deployment_info: DeploymentInfo) -> ReplicaSchedulingRequest: + """Start the current DeploymentReplica instance. + + The replica will be in the STARTING and PENDING_ALLOCATION states + until the deployment scheduler schedules the underlying actor. + """ + self._actor_resources = deployment_info.replica_config.resource_dict + self._ingress = deployment_info.ingress + # it is currently not possible to create a placement group + # with no resources (https://github.com/ray-project/ray/issues/20401) + self._deployment_is_cross_language = ( + deployment_info.deployment_config.is_cross_language + ) + + logger.info( + f"Starting {self.replica_id}.", + extra={"log_to_stderr": False}, + ) + + actor_def = deployment_info.actor_def + if ( + deployment_info.deployment_config.deployment_language + == DeploymentLanguage.PYTHON + ): + if deployment_info.replica_config.serialized_init_args is None: + serialized_init_args = cloudpickle.dumps(()) + else: + serialized_init_args = ( + cloudpickle.dumps( + msgpack_deserialize( + deployment_info.replica_config.serialized_init_args + ) + ) + if self._deployment_is_cross_language + else deployment_info.replica_config.serialized_init_args + ) + init_args = ( + self.replica_id, + cloudpickle.dumps(deployment_info.replica_config.deployment_def) + if self._deployment_is_cross_language + else deployment_info.replica_config.serialized_deployment_def, + serialized_init_args, + deployment_info.replica_config.serialized_init_kwargs + if deployment_info.replica_config.serialized_init_kwargs + else cloudpickle.dumps({}), + deployment_info.deployment_config.to_proto_bytes(), + self._version, + deployment_info.ingress, + deployment_info.route_prefix, + ) + # TODO(simon): unify the constructor arguments across language + elif ( + deployment_info.deployment_config.deployment_language + == DeploymentLanguage.JAVA + ): + self._is_cross_language = True + actor_def = ray.cross_language.java_actor_class( + "io.ray.serve.replica.RayServeWrappedReplica" + ) + init_args = ( + # String deploymentName, + self.deployment_name, + # String replicaID, + self.replica_id.to_full_id_str(), + # String deploymentDef + deployment_info.replica_config.deployment_def_name, + # byte[] initArgsbytes + msgpack_serialize( + cloudpickle.loads( + deployment_info.replica_config.serialized_init_args + ) + ) + if self._deployment_is_cross_language + else deployment_info.replica_config.serialized_init_args, + # byte[] deploymentConfigBytes, + deployment_info.deployment_config.to_proto_bytes(), + # byte[] deploymentVersionBytes, + self._version.to_proto().SerializeToString(), + # String controllerName + # String appName + self.app_name, + ) + + actor_options = { + "name": self._actor_name, + "namespace": SERVE_NAMESPACE, + "lifetime": "detached", + "enable_task_events": RAY_SERVE_ENABLE_TASK_EVENTS, + } + actor_options.update(deployment_info.replica_config.ray_actor_options) + + # A replica's default `max_concurrency` value can prevent it from + # respecting the configured `max_ongoing_requests`. To avoid this + # unintentional behavior, use `max_ongoing_requests` to override + # the Actor's `max_concurrency` if it is larger. + if ( + deployment_info.deployment_config.max_ongoing_requests + > ray_constants.DEFAULT_MAX_CONCURRENCY_ASYNC + ): + actor_options[ + "max_concurrency" + ] = deployment_info.deployment_config.max_ongoing_requests + + return ReplicaSchedulingRequest( + replica_id=self.replica_id, + actor_def=actor_def, + actor_resources=self._actor_resources, + actor_options=actor_options, + actor_init_args=init_args, + placement_group_bundles=( + deployment_info.replica_config.placement_group_bundles + ), + placement_group_strategy=( + deployment_info.replica_config.placement_group_strategy + ), + max_replicas_per_node=( + deployment_info.replica_config.max_replicas_per_node + ), + on_scheduled=self.on_scheduled, + ) + + def on_scheduled( + self, + actor_handle: ActorHandle, + placement_group: Optional[PlacementGroup] = None, + ): + self._actor_handle = actor_handle + self._placement_group = placement_group + + # Perform auto method name translation for java handles. + # See https://github.com/ray-project/ray/issues/21474 + deployment_config = copy(self._version.deployment_config) + deployment_config.user_config = self._format_user_config( + deployment_config.user_config + ) + if self._is_cross_language: + self._actor_handle = JavaActorHandleProxy(self._actor_handle) + self._allocated_obj_ref = self._actor_handle.is_allocated.remote() + self._ready_obj_ref = self._actor_handle.is_initialized.remote( + deployment_config.to_proto_bytes() + ) + else: + self._allocated_obj_ref = self._actor_handle.is_allocated.remote() + replica_ready_check_func = self._actor_handle.initialize_and_get_metadata + self._ready_obj_ref = replica_ready_check_func.remote( + deployment_config, + # Ensure that `is_allocated` will execute + # before `initialize_and_get_metadata`, + # because `initialize_and_get_metadata` runs + # user code that could block the replica + # asyncio loop. If that happens before `is_allocated` is executed, + # the `is_allocated` call won't be able to run. + self._allocated_obj_ref, + ) + + def _format_user_config(self, user_config: Any): + temp = copy(user_config) + if user_config is not None and self._deployment_is_cross_language: + if self._is_cross_language: + temp = msgpack_serialize(temp) + else: + temp = msgpack_deserialize(temp) + return temp + + def reconfigure(self, version: DeploymentVersion) -> bool: + """ + Update replica version. Also, updates the deployment config on the actor + behind this DeploymentReplica instance if necessary. + + Returns: whether the actor is being updated. + """ + updating = False + if self._version.requires_actor_reconfigure(version): + # Call into replica actor reconfigure() with updated user config and + # graceful_shutdown_wait_loop_s + updating = True + deployment_config = copy(version.deployment_config) + deployment_config.user_config = self._format_user_config( + deployment_config.user_config + ) + self._ready_obj_ref = self._actor_handle.reconfigure.remote( + deployment_config, version.route_prefix + ) + + self._version = version + return updating + + def recover(self) -> bool: + """Recover replica version from a live replica actor. + + When controller dies, the deployment state loses the info on the version that's + running on each individual replica actor, so as part of the recovery process, we + need to recover the version that is running on the replica actor. + + Also confirm that actor is allocated and initialized before marking as running. + + Returns: False if the replica actor is no longer alive; the + actor could have been killed in the time between when the + controller fetching all Serve actors in the cluster and when + the controller tries to recover it. Otherwise, return True. + """ + logger.info(f"Recovering {self.replica_id}.") + try: + self._actor_handle = ray.get_actor( + self._actor_name, namespace=SERVE_NAMESPACE + ) + except ValueError: + logger.warning( + f"Failed to get handle to replica {self._actor_name} " + "during controller recovery. Marking as dead." + ) + return False + + try: + self._placement_group = ray.util.get_placement_group( + self._actor_name, + ) + except ValueError: + # ValueError is raised if the placement group does not exist. + self._placement_group = None + + # Re-fetch initialization proof + self._allocated_obj_ref = self._actor_handle.is_allocated.remote() + + # Running actor handle already has all info needed, thus successful + # starting simply means retrieving replica version hash from actor + if self._is_cross_language: + self._ready_obj_ref = self._actor_handle.check_health.remote() + else: + self._ready_obj_ref = ( + self._actor_handle.initialize_and_get_metadata.remote() + ) + + return True + + def check_ready(self) -> Tuple[ReplicaStartupStatus, Optional[str]]: + """ + Check if current replica has started by making ray API calls on + relevant actor / object ref. + + Replica initialization calls __init__(), reconfigure(), and check_health(). + + Returns: + state (ReplicaStartupStatus): + PENDING_ALLOCATION: replica is waiting for a worker to start + PENDING_INITIALIZATION: replica initialization hasn't finished. + FAILED: replica initialization failed. + SUCCEEDED: replica initialization succeeded. + error_msg: + None: for PENDING_ALLOCATION, PENDING_INITIALIZATION or SUCCEEDED states + str: for FAILED state + """ + + # Check whether the replica has been allocated. + if self._allocated_obj_ref is None or not check_obj_ref_ready_nowait( + self._allocated_obj_ref + ): + return ReplicaStartupStatus.PENDING_ALLOCATION, None + + if not self._is_cross_language: + try: + ( + self._pid, + self._actor_id, + self._worker_id, + self._node_id, + self._node_ip, + self._node_instance_id, + self._log_file_path, + ) = ray.get(self._allocated_obj_ref) + except RayTaskError as e: + logger.exception( + f"Exception in {self._replica_id}, the replica will be stopped." + ) + return ReplicaStartupStatus.FAILED, str(e.as_instanceof_cause()) + except RuntimeEnvSetupError as e: + msg = f"Exception when allocating {self._replica_id}: {str(e)}" + logger.exception(msg) + return ReplicaStartupStatus.FAILED, msg + except Exception: + msg = ( + f"Exception when allocating {self._replica_id}:\n" + + traceback.format_exc() + ) + logger.exception(msg) + return ReplicaStartupStatus.FAILED, msg + + # Check whether replica initialization has completed. + replica_ready = check_obj_ref_ready_nowait(self._ready_obj_ref) + # In case of deployment constructor failure, ray.get will help to + # surface exception to each update() cycle. + if not replica_ready: + return ReplicaStartupStatus.PENDING_INITIALIZATION, None + else: + try: + # TODO(simon): fully implement reconfigure for Java replicas. + if self._is_cross_language: + return ReplicaStartupStatus.SUCCEEDED, None + + # todo: The replica's userconfig whitch java client created + # is different from the controller's userconfig + if not self._deployment_is_cross_language: + # This should only update version if the replica is being recovered. + # If this is checking on a replica that is newly started, this + # should return a version that is identical to what's already stored + ( + _, + self._version, + self._initialization_latency_s, + self._port, + self._docs_path, + ) = ray.get(self._ready_obj_ref) + except RayTaskError as e: + logger.exception( + f"Exception in {self._replica_id}, the replica will be stopped." + ) + # NOTE(zcin): we should use str(e) instead of traceback.format_exc() + # here because the full details of the error is not displayed properly + # with traceback.format_exc(). + return ReplicaStartupStatus.FAILED, str(e.as_instanceof_cause()) + except Exception as e: + logger.exception( + f"Exception in {self._replica_id}, the replica will be stopped." + ) + return ReplicaStartupStatus.FAILED, repr(e) + + return ReplicaStartupStatus.SUCCEEDED, None + + @property + def actor_resources(self) -> Optional[Dict[str, float]]: + return self._actor_resources + + @property + def available_resources(self) -> Dict[str, float]: + return ray.available_resources() + + def graceful_stop(self) -> Duration: + """Request the actor to exit gracefully. + + Returns the timeout after which to kill the actor. + """ + try: + handle = ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE) + if self._is_cross_language: + handle = JavaActorHandleProxy(handle) + self._graceful_shutdown_ref = handle.perform_graceful_shutdown.remote() + except ValueError: + # ValueError thrown from ray.get_actor means actor has already been deleted. + pass + + return self.graceful_shutdown_timeout_s + + def check_stopped(self) -> bool: + """Check if the actor has exited.""" + try: + handle = ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE) + stopped = check_obj_ref_ready_nowait(self._graceful_shutdown_ref) + if stopped: + try: + ray.get(self._graceful_shutdown_ref) + except Exception: + logger.exception( + "Exception when trying to gracefully shutdown replica:\n" + + traceback.format_exc() + ) + + ray.kill(handle, no_restart=True) + except ValueError: + # ValueError thrown from ray.get_actor means actor has already been deleted. + stopped = True + finally: + # Remove the placement group both if the actor has already been deleted or + # it was just killed above. + if stopped and self._placement_group is not None: + ray.util.remove_placement_group(self._placement_group) + + return stopped + + def _check_active_health_check(self) -> ReplicaHealthCheckResponse: + """Check the active health check (if any). + + self._health_check_ref will be reset to `None` when the active health + check is deemed to have succeeded or failed. This method *does not* + start a new health check, that's up to the caller. + + Returns: + - NONE if there's no active health check, or it hasn't returned + yet and the timeout is not up. + - SUCCEEDED if the active health check succeeded. + - APP_FAILURE if the active health check failed (or didn't return + before the timeout). + - ACTOR_CRASHED if the underlying actor crashed. + """ + if self._health_check_ref is None: + # There is no outstanding health check. + response = ReplicaHealthCheckResponse.NONE + elif check_obj_ref_ready_nowait(self._health_check_ref): + # Object ref is ready, ray.get it to check for exceptions. + try: + ray.get(self._health_check_ref) + # Health check succeeded without exception. + response = ReplicaHealthCheckResponse.SUCCEEDED + except RayActorError: + # Health check failed due to actor crashing. + response = ReplicaHealthCheckResponse.ACTOR_CRASHED + except RayError as e: + # Health check failed due to application-level exception. + logger.warning(f"Health check for {self._replica_id} failed: {e}") + response = ReplicaHealthCheckResponse.APP_FAILURE + elif time.time() - self._last_health_check_time > self.health_check_timeout_s: + # Health check hasn't returned and the timeout is up, consider it failed. + logger.warning( + "Didn't receive health check response for replica " + f"{self._replica_id} after " + f"{self.health_check_timeout_s}s, marking it unhealthy." + ) + response = ReplicaHealthCheckResponse.APP_FAILURE + else: + # Health check hasn't returned and the timeout isn't up yet. + response = ReplicaHealthCheckResponse.NONE + + if response is not ReplicaHealthCheckResponse.NONE: + self._health_check_ref = None + + return response + + def _should_start_new_health_check(self) -> bool: + """Determines if a new health check should be kicked off. + + A health check will be started if: + 1) There is not already an active health check. + 2) It has been more than health_check_period_s since the + previous health check was *started*. + + This assumes that self._health_check_ref is reset to `None` when an + active health check succeeds or fails (due to returning or timeout). + """ + if self._health_check_ref is not None: + # There's already an active health check. + return False + + # If there's no active health check, kick off another and reset + # the timer if it's been long enough since the last health + # check. Add some randomness to avoid synchronizing across all + # replicas. + time_since_last = time.time() - self._last_health_check_time + randomized_period = self.health_check_period_s * random.uniform(0.9, 1.1) + return time_since_last > randomized_period + + def _should_record_routing_stats(self) -> bool: + """Determines if a new record routing stats should be kicked off. + + A record routing stats will be started if: + 1) There is not already an active record routing stats. + 2) It has been more than request_routing_stats_period_s since + the previous record routing stats was *started*. + + This assumes that self._record_routing_stats_ref is reset to `None` + when an active record routing stats succeeds or fails (due to + returning or timeout). + """ + if self._record_routing_stats_ref is not None: + # There's already an active record routing stats. + return False + + # If there's no active record routing stats, kick off another and + # reset the timer if it's been long enough since the last record + # routing stats. Add some randomness to avoid synchronizing across + # all replicas. + time_since_last = time.time() - self._last_record_routing_stats_time + randomized_period = self.request_routing_stats_period_s * random.uniform( + 0.9, 1.1 + ) + return time_since_last > randomized_period + + def check_health(self) -> bool: + """Check if the actor is healthy. + + self._healthy should *only* be modified in this method. + + This is responsible for: + 1) Checking the outstanding health check (if any). + 2) Determining the replica health based on the health check results. + 3) Kicking off a new health check if needed. + """ + response: ReplicaHealthCheckResponse = self._check_active_health_check() + if response is ReplicaHealthCheckResponse.NONE: + # No info; don't update replica health. + pass + elif response is ReplicaHealthCheckResponse.SUCCEEDED: + # Health check succeeded. Reset the consecutive failure counter + # and mark the replica healthy. + if self._consecutive_health_check_failures > 0: + logger.info( + f"{self._replica_id} passed the health check after " + f"{self._consecutive_health_check_failures} consecutive failures." + ) + self._consecutive_health_check_failures = 0 + self._healthy = True + elif response is ReplicaHealthCheckResponse.APP_FAILURE: + # Health check failed. If it has failed more than N times in a row, + # mark the replica unhealthy. + self._consecutive_health_check_failures += 1 + if ( + self._consecutive_health_check_failures + >= REPLICA_HEALTH_CHECK_UNHEALTHY_THRESHOLD + ): + logger.warning( + f"Replica {self._replica_id} failed the health " + f"check {self._consecutive_health_check_failures} " + "times in a row, marking it unhealthy." + ) + self._healthy = False + elif response is ReplicaHealthCheckResponse.ACTOR_CRASHED: + # Actor crashed, mark the replica unhealthy immediately. + logger.warning( + f"Actor for {self._replica_id} crashed, marking " + "it unhealthy immediately." + ) + self._healthy = False + else: + assert False, f"Unknown response type: {response}." + + if self._should_start_new_health_check(): + self._last_health_check_time = time.time() + self._health_check_ref = self._actor_handle.check_health.remote() + + return self._healthy + + def get_routing_stats(self) -> Dict[str, Any]: + """Get the routing stats for the replica.""" + if self._record_routing_stats_ref is None: + # There's no active record routing stats. + pass + elif check_obj_ref_ready_nowait(self._record_routing_stats_ref): + # Object ref is ready, ray.get it to check for exceptions. + try: + self._routing_stats = ray.get(self._record_routing_stats_ref) + except Exception: + logger.exception( + "Exception when trying to get routing stats:\n" + + traceback.format_exc() + ) + self._record_routing_stats_ref = None + elif ( + time.time() - self._last_record_routing_stats_time + > self.request_routing_stats_timeout_s + ): + # Record routing stats hasn't returned and the timeout is up, retrying. + logger.warning( + "Didn't receive routing stats response for replica " + f"{self._replica_id} after " + f"{self.request_routing_stats_timeout_s}s, retrying." + ) + self._record_routing_stats_ref = None + + if self._should_record_routing_stats(): + self._last_record_routing_stats_time = time.time() + self._record_routing_stats_ref = ( + self._actor_handle.record_routing_stats.remote() + ) + + return self._routing_stats + + def force_stop(self, log_shutdown_message: bool = False): + """Force the actor to exit without shutting down gracefully.""" + if ( + self._ingress + and RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY + ): + if log_shutdown_message: + logger.info( + f"{self.replica_id} did not shut down because it had not finished draining requests. " + "Going to wait until the draining is complete. You can force-stop the replica by " + "setting RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY to 0." + ) + return + + try: + ray.kill(ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE)) + except ValueError: + pass + + +class DeploymentReplica: + """Manages state transitions for deployment replicas. + + This is basically a checkpointable lightweight state machine. + """ + + def __init__( + self, + replica_id: ReplicaID, + version: DeploymentVersion, + ): + self._replica_id = replica_id + self._actor = ActorReplicaWrapper(replica_id, version) + self._start_time = None + self._actor_details = ReplicaDetails( + actor_name=replica_id.to_full_id_str(), + replica_id=self._replica_id.unique_id, + state=ReplicaState.STARTING, + start_time_s=0, + ) + self._multiplexed_model_ids: List[str] = [] + self._routing_stats: Dict[str, Any] = {} + self._logged_shutdown_message = False + + def get_running_replica_info( + self, cluster_node_info_cache: ClusterNodeInfoCache + ) -> RunningReplicaInfo: + return RunningReplicaInfo( + replica_id=self._replica_id, + node_id=self.actor_node_id, + node_ip=self._actor.node_ip, + availability_zone=cluster_node_info_cache.get_node_az(self.actor_node_id), + actor_handle=self._actor.actor_handle, + max_ongoing_requests=self._actor.max_ongoing_requests, + is_cross_language=self._actor.is_cross_language, + multiplexed_model_ids=self.multiplexed_model_ids, + routing_stats=self.routing_stats, + port=self._actor._port, + ) + + def record_multiplexed_model_ids(self, multiplexed_model_ids: List[str]): + """Record the multiplexed model ids for this replica.""" + self._multiplexed_model_ids = multiplexed_model_ids + + def record_routing_stats(self, routing_stats: Optional[Dict[str, Any]]): + """Record the routing stats for this replica. + + Recording routing_stats as an empty dictionary is valid. But skip + update if the routing_stats is None. + """ + if routing_stats is not None: + self._routing_stats = routing_stats + + @property + def multiplexed_model_ids(self) -> List[str]: + return self._multiplexed_model_ids + + @property + def routing_stats(self) -> Dict[str, Any]: + return self._routing_stats + + @property + def actor_details(self) -> ReplicaDetails: + return self._actor_details + + @property + def replica_id(self) -> ReplicaID: + return self._replica_id + + @property + def deployment_name(self) -> str: + return self._replica_id.deployment_id.name + + @property + def app_name(self) -> str: + return self._replica_id.deployment_id.app_name + + @property + def version(self): + return self._actor.version + + @property + def docs_path(self) -> Optional[str]: + return self._actor.docs_path + + @property + def actor_id(self) -> str: + return self._actor.actor_id + + @property + def actor_handle(self) -> ActorHandle: + return self._actor.actor_handle + + @property + def actor_node_id(self) -> Optional[str]: + """Returns the node id of the actor, None if not placed.""" + return self._actor.node_id + + @property + def actor_pid(self) -> Optional[int]: + """Returns the node id of the actor, None if not placed.""" + return self._actor.pid + + @property + def initialization_latency_s(self) -> Optional[float]: + """Returns how long the replica took to initialize.""" + + return self._actor.initialization_latency_s + + def start(self, deployment_info: DeploymentInfo) -> ReplicaSchedulingRequest: + """ + Start a new actor for current DeploymentReplica instance. + """ + replica_scheduling_request = self._actor.start(deployment_info) + self._start_time = time.time() + self._logged_shutdown_message = False + self.update_actor_details(start_time_s=self._start_time) + return replica_scheduling_request + + def reconfigure(self, version: DeploymentVersion) -> bool: + """ + Update replica version. Also, updates the deployment config on the actor + behind this DeploymentReplica instance if necessary. + + Returns: whether the actor is being updated. + """ + return self._actor.reconfigure(version) + + def recover(self) -> bool: + """ + Recover states in DeploymentReplica instance by fetching running actor + status + + Returns: False if the replica is no longer alive at the time + when this method is called. + """ + # If replica is no longer alive + if not self._actor.recover(): + return False + + self._start_time = time.time() + self.update_actor_details(start_time_s=self._start_time) + return True + + def check_started( + self, + ) -> Tuple[ReplicaStartupStatus, Optional[str], Optional[float]]: + """Check if the replica has started. If so, transition to RUNNING. + + Should handle the case where the replica has already stopped. + + Returns: + status: Most recent state of replica by + querying actor obj ref + """ + is_ready = self._actor.check_ready() + self.update_actor_details( + pid=self._actor.pid, + node_id=self._actor.node_id, + node_ip=self._actor.node_ip, + node_instance_id=self._actor.node_instance_id, + actor_id=self._actor.actor_id, + worker_id=self._actor.worker_id, + log_file_path=self._actor.log_file_path, + ) + + return is_ready + + def stop(self, graceful: bool = True) -> None: + """Stop the replica. + + Should handle the case where the replica is already stopped. + """ + state = self._actor_details.state + logger.info( + f"Stopping {self.replica_id} (currently {state}).", + extra={"log_to_stderr": False}, + ) + timeout_s = self._actor.graceful_stop() + if not graceful: + timeout_s = 0 + self._shutdown_deadline = time.time() + timeout_s + + def check_stopped(self) -> bool: + """Check if the replica has finished stopping.""" + if self._actor.check_stopped(): + return True + + timeout_passed = time.time() >= self._shutdown_deadline + if timeout_passed: + if ( + not self._logged_shutdown_message + and not RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY + ): + logger.info( + f"{self.replica_id} did not shut down after grace " + "period, force-killing it. " + ) + + self._actor.force_stop( + log_shutdown_message=not self._logged_shutdown_message + ) + self._logged_shutdown_message = True + return False + + def check_health(self) -> bool: + """Check if the replica is healthy. + + Returns `True` if the replica is healthy, else `False`. + """ + return self._actor.check_health() + + def pull_routing_stats(self) -> Optional[Dict[str, Any]]: + """Get the latest response from the routing stats on the replica. + + Returns None if the replica is still calculating the stats. + """ + return self._actor.get_routing_stats() + + def update_state(self, state: ReplicaState) -> None: + """Updates state in actor details.""" + self.update_actor_details(state=state) + + def update_actor_details(self, **kwargs) -> None: + details_kwargs = self._actor_details.dict() + details_kwargs.update(kwargs) + self._actor_details = ReplicaDetails(**details_kwargs) + + def resource_requirements(self) -> Tuple[str, str]: + """Returns required and currently available resources. + + Only resources with nonzero requirements will be included in the + required dict and only resources in the required dict will be + included in the available dict (filtered for relevance). + """ + if self._actor.actor_resources is None: + return "UNKNOWN", "UNKNOWN" + + if self._actor.placement_group_bundles is not None: + required = self._actor.placement_group_bundles + else: + required = { + k: v + for k, v in self._actor.actor_resources.items() + if v is not None and v > 0 + } + + available = { + k: v for k, v in self._actor.available_resources.items() if k in required + } + + # Use json.dumps() instead of str() here to avoid double-quoting keys + # when dumping these objects. See + # https://github.com/ray-project/ray/issues/26210 for the issue. + return json.dumps(required), json.dumps(available) + + +class ReplicaStateContainer: + """Container for mapping ReplicaStates to lists of DeploymentReplicas.""" + + def __init__(self): + self._replicas: Dict[ReplicaState, List[DeploymentReplica]] = defaultdict(list) + + def add(self, state: ReplicaState, replica: DeploymentReplica): + """Add the provided replica under the provided state. + + Args: + state: state to add the replica under. + replica: replica to add. + """ + assert isinstance(state, ReplicaState), f"Type: {type(state)}" + replica.update_state(state) + self._replicas[state].append(replica) + + def get( + self, states: Optional[List[ReplicaState]] = None + ) -> List[DeploymentReplica]: + """Get all replicas of the given states. + + This does not remove them from the container. Replicas are returned + in order of state as passed in. + + Args: + states: states to consider. If not specified, all replicas + are considered. + """ + if states is None: + states = ALL_REPLICA_STATES + + assert isinstance(states, list) + + return sum((self._replicas[state] for state in states), []) + + def pop( + self, + exclude_version: Optional[DeploymentVersion] = None, + states: Optional[List[ReplicaState]] = None, + max_replicas: Optional[int] = math.inf, + ) -> List[DeploymentReplica]: + """Get and remove all replicas of the given states. + + This removes the replicas from the container. Replicas are returned + in order of state as passed in. + + Args: + exclude_version: if specified, replicas of the + provided version will *not* be removed. + states: states to consider. If not specified, all replicas + are considered. + max_replicas: max number of replicas to return. If not + specified, will pop all replicas matching the criteria. + """ + if states is None: + states = ALL_REPLICA_STATES + + assert exclude_version is None or isinstance(exclude_version, DeploymentVersion) + assert isinstance(states, list) + + replicas = [] + for state in states: + popped = [] + remaining = [] + + for replica in self._replicas[state]: + if len(replicas) + len(popped) == max_replicas: + remaining.append(replica) + elif exclude_version is not None and replica.version == exclude_version: + remaining.append(replica) + else: + popped.append(replica) + + self._replicas[state] = remaining + replicas.extend(popped) + + return replicas + + def count( + self, + exclude_version: Optional[DeploymentVersion] = None, + version: Optional[DeploymentVersion] = None, + states: Optional[List[ReplicaState]] = None, + ): + """Get the total count of replicas of the given states. + + Args: + exclude_version: version to exclude. If not + specified, all versions are considered. + version: version to filter to. If not specified, + all versions are considered. + states: states to consider. If not specified, all replicas + are considered. + """ + if states is None: + states = ALL_REPLICA_STATES + assert isinstance(states, list) + assert exclude_version is None or isinstance(exclude_version, DeploymentVersion) + assert version is None or isinstance(version, DeploymentVersion) + if exclude_version is None and version is None: + return sum(len(self._replicas[state]) for state in states) + elif exclude_version is None and version is not None: + return sum( + len(list(filter(lambda r: r.version == version, self._replicas[state]))) + for state in states + ) + elif exclude_version is not None and version is None: + return sum( + len( + list( + filter( + lambda r: r.version != exclude_version, + self._replicas[state], + ) + ) + ) + for state in states + ) + else: + raise ValueError( + "Only one of `version` or `exclude_version` may be provided." + ) + + def __str__(self): + return str(self._replicas) + + def __repr__(self): + return repr(self._replicas) + + +class DeploymentState: + """Manages the target state and replicas for a single deployment.""" + + FORCE_STOP_UNHEALTHY_REPLICAS = RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS + + def __init__( + self, + id: DeploymentID, + long_poll_host: LongPollHost, + deployment_scheduler: DeploymentScheduler, + cluster_node_info_cache: ClusterNodeInfoCache, + autoscaling_state_manager: AutoscalingStateManager, + ): + self._id = id + self._long_poll_host: LongPollHost = long_poll_host + self._deployment_scheduler = deployment_scheduler + self._cluster_node_info_cache = cluster_node_info_cache + self._autoscaling_state_manager = autoscaling_state_manager + + # Each time we set a new deployment goal, we're trying to save new + # DeploymentInfo and bring current deployment to meet new status. + self._target_state: DeploymentTargetState = DeploymentTargetState.default() + + self._prev_startup_warning: float = time.time() + self._replica_constructor_error_msg: Optional[str] = None + # Counter for how many times replicas failed to start. This is reset to 0 when: + # (1) The deployment is deployed / re-deployed. + # (2) The deployment reaches the HEALTHY state. + self._replica_constructor_retry_counter: int = 0 + # Flag for whether any replicas of the target version has successfully started. + # This is reset to False when the deployment is re-deployed. + self._replica_has_started: bool = False + + self._replicas: ReplicaStateContainer = ReplicaStateContainer() + self._curr_status_info: DeploymentStatusInfo = DeploymentStatusInfo( + self._id.name, + DeploymentStatus.UPDATING, + DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + ) + + self.replica_average_ongoing_requests: Dict[str, float] = {} + + self.health_check_gauge = metrics.Gauge( + "serve_deployment_replica_healthy", + description=( + "Tracks whether this deployment replica is healthy. 1 means " + "healthy, 0 means unhealthy." + ), + tag_keys=("deployment", "replica", "application"), + ) + + # Whether the request routing info have been updated since the last + # time we checked. + self._request_routing_info_updated = False + + self._last_broadcasted_running_replica_infos: List[RunningReplicaInfo] = [] + self._last_broadcasted_availability: bool = True + self._last_broadcasted_deployment_config = None + + self._docs_path: Optional[str] = None + + def should_autoscale(self) -> bool: + """ + Check if the deployment is under autoscaling + """ + return self._id in self._autoscaling_state_manager._autoscaling_states + + def get_checkpoint_data(self) -> DeploymentTargetState: + """ + Return deployment's target state submitted by user's deployment call. + Should be persisted and outlive current ray cluster. + """ + return self._target_state + + def recover_target_state_from_checkpoint( + self, target_state_checkpoint: DeploymentTargetState + ): + logger.info(f"Recovering target state for {self._id} from checkpoint.") + self._target_state = target_state_checkpoint + self._deployment_scheduler.on_deployment_deployed( + self._id, self._target_state.info.replica_config + ) + if self._target_state.info.deployment_config.autoscaling_config: + self._autoscaling_state_manager.register_deployment( + self._id, + self._target_state.info, + self._target_state.target_num_replicas, + ) + + def recover_current_state_from_replica_actor_names( + self, replica_actor_names: List[str] + ): + """Recover deployment state from live replica actors found in the cluster.""" + + assert self._target_state is not None, ( + "Target state should be recovered successfully first before " + "recovering current state from replica actor names." + ) + logger.info( + f"Recovering current state for {self._id} " + f"from {len(replica_actor_names)} live actors." + ) + # All current states use default value, only attach running replicas. + for replica_actor_name in replica_actor_names: + replica_id = ReplicaID.from_full_id_str(replica_actor_name) + new_deployment_replica = DeploymentReplica( + replica_id, + self._target_state.version, + ) + # If replica is no longer alive, simply don't add it to the + # deployment state manager to track. + if not new_deployment_replica.recover(): + logger.warning(f"{replica_id} died before controller could recover it.") + continue + + self._replicas.add(ReplicaState.RECOVERING, new_deployment_replica) + self._deployment_scheduler.on_replica_recovering(replica_id) + logger.debug(f"RECOVERING {replica_id}.") + + # TODO(jiaodong): this currently halts all traffic in the cluster + # briefly because we will broadcast a replica update with everything in + # RECOVERING. We should have a grace period where we recover the state + # of the replicas before doing this update. + + @property + def target_info(self) -> DeploymentInfo: + return self._target_state.info + + @property + def target_version(self) -> DeploymentVersion: + return self._target_state.version + + @property + def target_num_replicas(self) -> int: + return self._target_state.target_num_replicas + + @property + def curr_status_info(self) -> DeploymentStatusInfo: + return self._curr_status_info + + @property + def deployment_name(self) -> str: + return self._id.name + + @property + def app_name(self) -> str: + return self._id.app_name + + @property + def docs_path(self) -> Optional[str]: + return self._docs_path + + @property + def _failed_to_start_threshold(self) -> int: + return min( + MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT, + self._target_state.target_num_replicas * MAX_PER_REPLICA_RETRY_COUNT, + ) + + def _replica_startup_failing(self) -> bool: + """Check whether replicas are currently failing and the number of + failures has exceeded a threshold. + """ + return ( + self._target_state.target_num_replicas > 0 + and self._replica_constructor_retry_counter + >= self._failed_to_start_threshold + ) + + def _terminally_failed(self) -> bool: + """Check whether the current version is terminally errored. + + The version is considered terminally errored if the number of + replica failures has exceeded a threshold, and there hasn't been + any replicas of the target version that has successfully started. + """ + return not self._replica_has_started and self._replica_startup_failing() + + def get_alive_replica_actor_ids(self) -> Set[str]: + return {replica.actor_id for replica in self._replicas.get()} + + def get_running_replica_ids(self) -> List[ReplicaID]: + return [ + replica.replica_id + for replica in self._replicas.get( + [ReplicaState.RUNNING, ReplicaState.PENDING_MIGRATION] + ) + ] + + def get_running_replica_infos(self) -> List[RunningReplicaInfo]: + return [ + replica.get_running_replica_info(self._cluster_node_info_cache) + for replica in self._replicas.get( + [ReplicaState.RUNNING, ReplicaState.PENDING_MIGRATION] + ) + ] + + def get_num_running_replicas(self, version: DeploymentVersion = None) -> int: + return self._replicas.count(states=[ReplicaState.RUNNING], version=version) + + def get_active_node_ids(self) -> Set[str]: + """Get the node ids of all running replicas in this deployment. + + This is used to determine which node has replicas. Only nodes with replicas and + head node should have active proxies. + """ + active_states = [ + ReplicaState.STARTING, + ReplicaState.UPDATING, + ReplicaState.RECOVERING, + ReplicaState.RUNNING, + # NOTE(zcin): We still want a proxy to run on a draining + # node before all the replicas are migrated. + ReplicaState.PENDING_MIGRATION, + ] + return { + replica.actor_node_id + for replica in self._replicas.get(active_states) + if replica.actor_node_id is not None + } + + def list_replica_details(self) -> List[ReplicaDetails]: + return [replica.actor_details for replica in self._replicas.get()] + + def broadcast_running_replicas_if_changed(self) -> None: + """Broadcasts the set of running replicas over long poll if it has changed. + + Keeps an in-memory record of the last set of running replicas that was broadcast + to determine if it has changed. + + The set will also be broadcast if any replicas have an updated set of + multiplexed model IDs. + """ + running_replica_infos = self.get_running_replica_infos() + is_available = not self._terminally_failed() + + running_replicas_changed = ( + set(self._last_broadcasted_running_replica_infos) + != set(running_replica_infos) + or self._request_routing_info_updated + ) + availability_changed = is_available != self._last_broadcasted_availability + if not running_replicas_changed and not availability_changed: + return + + deployment_metadata = DeploymentTargetInfo( + is_available=is_available, + running_replicas=running_replica_infos, + ) + self._long_poll_host.notify_changed( + { + ( + LongPollNamespace.DEPLOYMENT_TARGETS, + self._id, + ): deployment_metadata, + # NOTE(zcin): notify changed for Java routers. Since Java only + # supports 1.x API, there is no concept of applications in Java, + # so the key should remain a string describing the deployment + # name. If there are no Java routers, this is a no-op. + ( + LongPollNamespace.DEPLOYMENT_TARGETS, + self._id.name, + ): deployment_metadata, + } + ) + self._last_broadcasted_running_replica_infos = running_replica_infos + self._last_broadcasted_availability = is_available + self._request_routing_info_updated = False + + def broadcast_deployment_config_if_changed(self) -> None: + """Broadcasts the deployment config over long poll if it has changed. + + Keeps an in-memory record of the last config that was broadcast to determine + if it has changed. + """ + current_deployment_config = self._target_state.info.deployment_config + if self._last_broadcasted_deployment_config == current_deployment_config: + return + + self._long_poll_host.notify_changed( + {(LongPollNamespace.DEPLOYMENT_CONFIG, self._id): current_deployment_config} + ) + + self._last_broadcasted_deployment_config = current_deployment_config + + def _set_target_state_deleting(self) -> None: + """Set the target state for the deployment to be deleted.""" + target_state = DeploymentTargetState.create( + info=self._target_state.info, + target_num_replicas=0, + deleting=True, + ) + + self._target_state = target_state + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.DELETE + ) + logger.info( + f"Deleting {self._id}", + extra={"log_to_stderr": False}, + ) + + def _set_target_state( + self, + target_info: DeploymentInfo, + target_num_replicas: int, + ) -> None: + """Set the target state for the deployment to the provided info. + + Args: + target_info: The info with which to set the target state. + target_num_replicas: The number of replicas that this deployment + should attempt to run. + status_trigger: The driver that triggered this change of state. + """ + new_target_state = DeploymentTargetState.create( + target_info, target_num_replicas, deleting=False + ) + + if self._target_state.version == new_target_state.version: + # Record either num replica or autoscaling config lightweight update + if ( + self._target_state.version.deployment_config.autoscaling_config + != new_target_state.version.deployment_config.autoscaling_config + ): + ServeUsageTag.AUTOSCALING_CONFIG_LIGHTWEIGHT_UPDATED.record("True") + elif ( + self._target_state.version.deployment_config.num_replicas + != new_target_state.version.deployment_config.num_replicas + ): + ServeUsageTag.NUM_REPLICAS_LIGHTWEIGHT_UPDATED.record("True") + + self._target_state = new_target_state + + def deploy(self, deployment_info: DeploymentInfo) -> bool: + """Deploy the deployment. + + If the deployment already exists with the same version, config, + target_capacity, and target_capacity_direction, + this method returns False. + + Returns: + bool: Whether or not the deployment is being updated. + """ + + curr_deployment_info = self._target_state.info + if curr_deployment_info is not None: + # Redeploying should not reset the deployment's start time. + if not self._target_state.deleting: + deployment_info.start_time_ms = curr_deployment_info.start_time_ms + + deployment_settings_changed = ( + self._target_state.deleting + or curr_deployment_info.deployment_config + != deployment_info.deployment_config + or curr_deployment_info.replica_config.ray_actor_options + != deployment_info.replica_config.ray_actor_options + or curr_deployment_info.route_prefix != deployment_info.route_prefix + or deployment_info.version is None + or curr_deployment_info.version != deployment_info.version + ) + target_capacity_changed = ( + curr_deployment_info.target_capacity != deployment_info.target_capacity + or curr_deployment_info.target_capacity_direction + != deployment_info.target_capacity_direction + ) + else: + deployment_settings_changed = True + target_capacity_changed = True + + # Exit early if the deployment info hasn't changed. Ensures this method + # is idempotent. + if not deployment_settings_changed and not target_capacity_changed: + return False + + if deployment_info.deployment_config.autoscaling_config: + target_num_replicas = self._autoscaling_state_manager.register_deployment( + self._id, deployment_info, self._target_state.target_num_replicas + ) + else: + self._autoscaling_state_manager.deregister_deployment(self._id) + target_num_replicas = get_capacity_adjusted_num_replicas( + deployment_info.deployment_config.num_replicas, + deployment_info.target_capacity, + ) + + old_target_state = self._target_state + self._set_target_state(deployment_info, target_num_replicas=target_num_replicas) + self._deployment_scheduler.on_deployment_deployed( + self._id, deployment_info.replica_config + ) + + # Determine if the updated target state simply scales the current state. + # Although the else branch handles the CONFIG_UPDATE, we also take this branch + # for a config update whose only effect is changing `num_replicas`. + # Treating it as a scaling event keeps the user-visible deployment status more + # consistent for observability. + if self._target_state.is_scaled_copy_of(old_target_state): + old_num = old_target_state.target_num_replicas + new_num = self._target_state.target_num_replicas + + if new_num > old_num: + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS, # noqa: E501 + message=f"Upscaling from {old_num} to {new_num} replicas.", + ) + elif new_num < old_num: + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS, # noqa: E501 + message=f"Downscaling from {old_num} to {new_num} replicas.", + ) + else: + # Otherwise, the deployment configuration has actually been updated. + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.CONFIG_UPDATE + ) + + logger.info( + f"Deploying new version of {self._id} " + f"(initial target replicas: {target_num_replicas})." + ) + self._replica_constructor_retry_counter = 0 + self._replica_has_started = False + return True + + def autoscale(self) -> int: + """Autoscale the deployment based on metrics.""" + + if self._target_state.deleting: + return + + decision_num_replicas = self._autoscaling_state_manager.get_target_num_replicas( + deployment_id=self._id, + curr_target_num_replicas=self._target_state.target_num_replicas, + ) + + if ( + decision_num_replicas is None + or decision_num_replicas == self._target_state.target_num_replicas + ): + return + + new_info = copy(self._target_state.info) + new_info.version = self._target_state.version.code_version + + old_num = self._target_state.target_num_replicas + self._set_target_state(new_info, decision_num_replicas) + + # The deployment should only transition to UPSCALING/DOWNSCALING + # if it's within the autoscaling bounds + if not self._autoscaling_state_manager.is_within_bounds( + self._id, + self._replicas.count( + states=[ReplicaState.RUNNING], version=self._target_state.version + ), + ): + return + + curr_stats_str = ( + f"Current ongoing requests: " + f"{self._autoscaling_state_manager.get_total_num_requests(self._id):.2f}, " + f"current running replicas: " + f"{self._replicas.count(states=[ReplicaState.RUNNING])}." + ) + new_num = self._target_state.target_num_replicas + if new_num > old_num: + logger.info( + f"Upscaling {self._id} from {old_num} to {new_num} replicas. " + f"{curr_stats_str}" + ) + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.AUTOSCALE_UP, + message=f"Upscaling from {old_num} to {new_num} replicas.", + ) + elif new_num < old_num: + logger.info( + f"Downscaling {self._id} from {old_num} to {new_num} replicas. " + f"{curr_stats_str}" + ) + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.AUTOSCALE_DOWN, + message=f"Downscaling from {old_num} to {new_num} replicas.", + ) + + def delete(self) -> None: + if not self._target_state.deleting: + self._set_target_state_deleting() + + def _stop_or_update_outdated_version_replicas(self, max_to_stop=math.inf) -> bool: + """Stop or update replicas with outdated versions. + + Stop replicas with versions that require the actor to be restarted, and + reconfigure replicas that require refreshing deployment config values. + + Args: + max_to_stop: max number of replicas to stop, by default, + it stops all replicas with an outdated version. + """ + replicas_to_update = self._replicas.pop( + exclude_version=self._target_state.version, + states=[ + ReplicaState.STARTING, + ReplicaState.PENDING_MIGRATION, + ReplicaState.RUNNING, + ], + ) + replicas_changed = False + code_version_changes = 0 + reconfigure_changes = 0 + for replica in replicas_to_update: + if (code_version_changes + reconfigure_changes) >= max_to_stop: + self._replicas.add(replica.actor_details.state, replica) + # If the new version requires the actors to be restarted, stop the replica. + # A new one with the correct version will be started later as part of the + # normal scale-up process. + elif replica.version.requires_actor_restart(self._target_state.version): + code_version_changes += 1 + # If the replica is still `STARTING`, we don't need to go through the + # graceful stop period. + graceful_stop = replica.actor_details.state == ReplicaState.RUNNING + self._stop_replica(replica, graceful_stop=graceful_stop) + replicas_changed = True + # Otherwise, only lightweight options in deployment config is a mismatch, so + # we update it dynamically without restarting the replica. + elif replica.actor_details.state == ReplicaState.RUNNING: + reconfigure_changes += 1 + if replica.version.requires_long_poll_broadcast( + self._target_state.version + ): + replicas_changed = True + actor_updating = replica.reconfigure(self._target_state.version) + if actor_updating: + self._replicas.add(ReplicaState.UPDATING, replica) + else: + self._replicas.add(ReplicaState.RUNNING, replica) + # We don't allow going from STARTING, PENDING_MIGRATION to UPDATING. + else: + self._replicas.add(replica.actor_details.state, replica) + + if code_version_changes > 0: + logger.info( + f"Stopping {code_version_changes} replicas of {self._id} " + "with outdated versions." + ) + + if reconfigure_changes > 0: + logger.info( + f"Updating {reconfigure_changes} replicas of {self._id} " + "with outdated deployment configs." + ) + # Record user config lightweight update + ServeUsageTag.USER_CONFIG_LIGHTWEIGHT_UPDATED.record("True") + + return replicas_changed + + def _check_and_stop_outdated_version_replicas(self) -> bool: + """Stops replicas with outdated versions to implement rolling updates. + + This includes both explicit code version updates and changes to the + user_config. + + Returns whether any replicas were stopped. + """ + # Short circuit if target replicas is 0 (the deployment is being + # deleted) because this will be handled in the main loop. + if self._target_state.target_num_replicas == 0: + return False + + # We include STARTING and UPDATING replicas here + # because if there are replicas still pending startup, we may as well + # terminate them and start new version replicas instead. + old_running_replicas = self._replicas.count( + exclude_version=self._target_state.version, + states=[ + ReplicaState.STARTING, + ReplicaState.UPDATING, + ReplicaState.RUNNING, + ], + ) + old_stopping_replicas = self._replicas.count( + exclude_version=self._target_state.version, states=[ReplicaState.STOPPING] + ) + new_running_replicas = self._replicas.count( + version=self._target_state.version, states=[ReplicaState.RUNNING] + ) + + # If the deployment is currently scaling down, let the scale down + # complete before doing a rolling update. + if ( + self._target_state.target_num_replicas + < old_running_replicas + old_stopping_replicas + ): + return False + + # The number of replicas that are currently in transition between + # an old version and the new version. Note that we cannot directly + # count the number of stopping replicas because once replicas finish + # stopping, they are removed from the data structure. + pending_replicas = ( + self._target_state.target_num_replicas + - new_running_replicas + - old_running_replicas + ) + + # Maximum number of replicas that can be updating at any given time. + # There should never be more than rollout_size old replicas stopping + # or rollout_size new replicas starting. + rollout_size = max(int(0.2 * self._target_state.target_num_replicas), 1) + max_to_stop = max(rollout_size - pending_replicas, 0) + + return self._stop_or_update_outdated_version_replicas(max_to_stop) + + def scale_deployment_replicas( + self, + ) -> Tuple[List[ReplicaSchedulingRequest], DeploymentDownscaleRequest]: + """Scale the given deployment to the number of replicas.""" + + assert ( + self._target_state.target_num_replicas >= 0 + ), "Target number of replicas must be greater than or equal to 0." + + upscale = [] + downscale = None + + self._check_and_stop_outdated_version_replicas() + + current_replicas = self._replicas.count( + states=[ReplicaState.STARTING, ReplicaState.UPDATING, ReplicaState.RUNNING] + ) + recovering_replicas = self._replicas.count(states=[ReplicaState.RECOVERING]) + + delta_replicas = ( + self._target_state.target_num_replicas + - current_replicas + - recovering_replicas + ) + if delta_replicas == 0: + return (upscale, downscale) + + elif delta_replicas > 0: + to_add = delta_replicas + if to_add > 0 and not self._terminally_failed(): + logger.info(f"Adding {to_add} replica{'s' * (to_add>1)} to {self._id}.") + for _ in range(to_add): + replica_id = ReplicaID(get_random_string(), deployment_id=self._id) + new_deployment_replica = DeploymentReplica( + replica_id, + self._target_state.version, + ) + upscale.append( + new_deployment_replica.start(self._target_state.info) + ) + + self._replicas.add(ReplicaState.STARTING, new_deployment_replica) + + elif delta_replicas < 0: + to_remove = -delta_replicas + removed_replicas = f"{to_remove} replica{'s' if to_remove > 1 else ''}" + logger.info(f"Removing {removed_replicas} from {self._id}.") + downscale = DeploymentDownscaleRequest( + deployment_id=self._id, num_to_stop=to_remove + ) + + return upscale, downscale + + def check_curr_status(self) -> Tuple[bool, bool]: + """Check the current deployment status. + + Checks the difference between the target vs. running replica count for + the target version. + + This will update the current deployment status depending on the state + of the replicas. + + Returns (deleted, any_replicas_recovering). + """ + # TODO(edoakes): we could make this more efficient in steady-state by + # having a "healthy" flag that gets flipped if an update or replica + # failure happens. + + target_version = self._target_state.version + + any_replicas_recovering = ( + self._replicas.count(states=[ReplicaState.RECOVERING]) > 0 + ) + all_running_replica_cnt = self._replicas.count(states=[ReplicaState.RUNNING]) + running_at_target_version_replica_cnt = self._replicas.count( + states=[ReplicaState.RUNNING], version=target_version + ) + + # Got to make a call to complete current deploy() goal after + # start failure threshold reached, while we might still have + # pending replicas in current goal. + if running_at_target_version_replica_cnt > 0: + # At least one RUNNING replica at target state, partial + # success; We can stop tracking constructor failures and + # leave it to the controller to fully scale to target + # number of replicas and only return as completed once + # reached target replica count + self._replica_has_started = True + elif self._replica_startup_failing(): + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED, + message=( + "The deployment failed to start " + f"{self._replica_constructor_retry_counter} times " + "in a row. This may be due to a problem with its " + "constructor or initial health check failing. See " + "controller logs for details. Error:\n" + f"{self._replica_constructor_error_msg}" + ), + ) + return False, any_replicas_recovering + + # If we have pending ops, the current goal is *not* ready. + if ( + self._replicas.count( + states=[ + ReplicaState.STARTING, + ReplicaState.UPDATING, + ReplicaState.RECOVERING, + ReplicaState.STOPPING, + ] + ) + == 0 + ): + # Check for deleting and a non-zero number of deployments. + if self._target_state.deleting and all_running_replica_cnt == 0: + return True, any_replicas_recovering + + if ( + self._target_state.target_num_replicas + == running_at_target_version_replica_cnt + and running_at_target_version_replica_cnt == all_running_replica_cnt + ): + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.HEALTHY + ) + self._replica_constructor_retry_counter = 0 + return False, any_replicas_recovering + + return False, any_replicas_recovering + + def _check_startup_replicas( + self, original_state: ReplicaState, stop_on_slow=False + ) -> List[Tuple[DeploymentReplica, ReplicaStartupStatus]]: + """ + Common helper function for startup actions tracking and status + transition: STARTING, UPDATING and RECOVERING. + + Args: + stop_on_slow: If we consider a replica failed upon observing it's + slow to reach running state. + """ + slow_replicas = [] + for replica in self._replicas.pop(states=[original_state]): + start_status, error_msg = replica.check_started() + if start_status == ReplicaStartupStatus.SUCCEEDED: + # This replica should be now be added to handle's replica + # set. + self._replicas.add(ReplicaState.RUNNING, replica) + self._deployment_scheduler.on_replica_running( + replica.replica_id, replica.actor_node_id + ) + + # if replica version is the same as the target version, + # we update the docs path + if replica.version == self._target_state.version: + self._docs_path = replica.docs_path + + # Log the startup latency. + e2e_replica_start_latency = time.time() - replica._start_time + replica_startup_message = ( + f"{replica.replica_id} started successfully " + f"on node '{replica.actor_node_id}' after " + f"{e2e_replica_start_latency:.1f}s (PID: {replica.actor_pid})." + ) + if replica.initialization_latency_s is not None: + # This condition should always be True. The initialization + # latency is only None before the replica has initialized. + replica_startup_message += ( + " Replica constructor, " + "reconfigure method, and initial health check took " + f"{replica.initialization_latency_s:.1f}s." + ) + logger.info(replica_startup_message, extra={"log_to_stderr": False}) + + elif start_status == ReplicaStartupStatus.FAILED: + # Replica reconfigure (deploy / upgrade) failed + self.record_replica_startup_failure(error_msg) + self._stop_replica(replica) + elif start_status in [ + ReplicaStartupStatus.PENDING_ALLOCATION, + ReplicaStartupStatus.PENDING_INITIALIZATION, + ]: + is_slow = time.time() - replica._start_time > SLOW_STARTUP_WARNING_S + if is_slow: + slow_replicas.append((replica, start_status)) + + # Does it make sense to stop replicas in PENDING_ALLOCATION + # state? + if is_slow and stop_on_slow: + self._stop_replica(replica, graceful_stop=False) + else: + self._replicas.add(original_state, replica) + + return slow_replicas + + def record_replica_startup_failure(self, error_msg: str): + """Record that a replica failed to start.""" + + # There is no need to record replica failures if the target is 0. + if self._target_state.target_num_replicas == 0: + return + + # Increase startup failure counter + self._replica_constructor_retry_counter += 1 + self._replica_constructor_error_msg = error_msg + + # Update the deployment message only if replicas are failing during + # the very first time the controller is trying to start replicas of + # this version. + retrying_msg = "" + if not self._replica_has_started: + remaining_retries = max( + self._failed_to_start_threshold + - self._replica_constructor_retry_counter, + 0, + ) + retrying_msg = f" {remaining_retries} more time(s)" + + message = ( + f"A replica failed to start with exception. Retrying{retrying_msg}. " + f"Error:\n{error_msg}" + ) + self._curr_status_info = self._curr_status_info.update_message(message) + + def stop_replicas(self, replicas_to_stop) -> None: + for replica in self._replicas.pop(): + if replica.replica_id in replicas_to_stop: + self._stop_replica(replica) + else: + self._replicas.add(replica.actor_details.state, replica) + + def _stop_replica(self, replica: DeploymentReplica, graceful_stop=True): + """Stop replica + 1. Stop the replica. + 2. Change the replica into stopping state. + 3. Set the health replica stats to 0. + """ + logger.debug(f"Adding STOPPING to replica: {replica.replica_id}.") + replica.stop(graceful=graceful_stop) + self._replicas.add(ReplicaState.STOPPING, replica) + self._deployment_scheduler.on_replica_stopping(replica.replica_id) + self.health_check_gauge.set( + 0, + tags={ + "deployment": self.deployment_name, + "replica": replica.replica_id.unique_id, + "application": self.app_name, + }, + ) + + def check_and_update_replicas(self): + """ + Check current state of all DeploymentReplica being tracked, and compare + with state container from previous update() cycle to see if any state + transition happened. + """ + + for replica in self._replicas.pop( + states=[ReplicaState.RUNNING, ReplicaState.PENDING_MIGRATION] + ): + if replica.check_health(): + self._replicas.add(replica.actor_details.state, replica) + self.health_check_gauge.set( + 1, + tags={ + "deployment": self.deployment_name, + "replica": replica.replica_id.unique_id, + "application": self.app_name, + }, + ) + routing_stats = replica.pull_routing_stats() + replica.record_routing_stats(routing_stats) + else: + logger.warning( + f"Replica {replica.replica_id} failed health check, stopping it." + ) + self.health_check_gauge.set( + 0, + tags={ + "deployment": self.deployment_name, + "replica": replica.replica_id.unique_id, + "application": self.app_name, + }, + ) + self._stop_replica( + replica, graceful_stop=not self.FORCE_STOP_UNHEALTHY_REPLICAS + ) + # If this is a replica of the target version, the deployment + # enters the "UNHEALTHY" status until the replica is + # recovered or a new deploy happens. + if replica.version == self._target_state.version: + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED, + message="A replica's health check failed. This " + "deployment will be UNHEALTHY until the replica " + "recovers or a new deploy happens.", + ) + + slow_start_replicas = [] + slow_start = self._check_startup_replicas(ReplicaState.STARTING) + slow_update = self._check_startup_replicas(ReplicaState.UPDATING) + slow_recover = self._check_startup_replicas( + ReplicaState.RECOVERING, stop_on_slow=True + ) + + slow_start_replicas = slow_start + slow_update + slow_recover + + if ( + len(slow_start_replicas) + and time.time() - self._prev_startup_warning > SLOW_STARTUP_WARNING_PERIOD_S + ): + pending_allocation = [] + pending_initialization = [] + + for replica, startup_status in slow_start_replicas: + if startup_status == ReplicaStartupStatus.PENDING_ALLOCATION: + pending_allocation.append(replica) + if startup_status == ReplicaStartupStatus.PENDING_INITIALIZATION: + pending_initialization.append(replica) + + if len(pending_allocation) > 0: + required, available = pending_allocation[0].resource_requirements() + message = ( + f"Deployment '{self.deployment_name}' in application " + f"'{self.app_name}' has {len(pending_allocation)} replicas that " + f"have taken more than {SLOW_STARTUP_WARNING_S}s to be scheduled. " + "This may be due to waiting for the cluster to auto-scale or for a " + "runtime environment to be installed. " + f"Resources required for each replica: {required}, " + f"total resources available: {available}. " + "Use `ray status` for more details." + ) + logger.warning(message) + if _SCALING_LOG_ENABLED: + print_verbose_scaling_log() + # If status is UNHEALTHY, leave the status and message as is. + # The issue that caused the deployment to be unhealthy should be + # prioritized over this resource availability issue. + if self._curr_status_info.status not in [ + DeploymentStatus.UNHEALTHY, + DeploymentStatus.DEPLOY_FAILED, + ]: + self._curr_status_info = self._curr_status_info.update_message( + message + ) + + if len(pending_initialization) > 0: + message = ( + f"Deployment '{self.deployment_name}' in application " + f"'{self.app_name}' has {len(pending_initialization)} replicas " + f"that have taken more than {SLOW_STARTUP_WARNING_S}s to " + "initialize.\n" + "This may be caused by a slow __init__ or reconfigure method." + ) + logger.warning(message) + # If status is UNHEALTHY, leave the status and message as is. + # The issue that caused the deployment to be unhealthy should be + # prioritized over this resource availability issue. + if self._curr_status_info.status not in [ + DeploymentStatus.UNHEALTHY, + DeploymentStatus.DEPLOY_FAILED, + ]: + self._curr_status_info = self._curr_status_info.update_message( + message + ) + + self._prev_startup_warning = time.time() + + for replica in self._replicas.pop(states=[ReplicaState.STOPPING]): + stopped = replica.check_stopped() + if not stopped: + self._replicas.add(ReplicaState.STOPPING, replica) + else: + logger.info(f"{replica.replica_id} is stopped.") + self._autoscaling_state_manager.on_replica_stopped(replica.replica_id) + + def _choose_pending_migration_replicas_to_stop( + self, + replicas: List[DeploymentReplica], + deadlines: Dict[str, int], + min_replicas_to_stop: int, + ) -> Tuple[List[DeploymentReplica], List[DeploymentReplica]]: + """Returns a partition of replicas to stop and to keep. + + Args: + replicas: The current list of replicas pending migration. + deadlines: The current draining node deadlines. + min_replicas_to_stop: The minimum number of replicas to stop. + """ + to_stop = [] + remaining = [] + + # Stop replicas whose deadline is up + for replica in replicas: + assert replica.actor_node_id in deadlines + + curr_timestamp_ms = time.time() * 1000 + timeout_ms = replica._actor.graceful_shutdown_timeout_s * 1000 + if curr_timestamp_ms >= deadlines[replica.actor_node_id] - timeout_ms: + to_stop.append(replica) + else: + remaining.append(replica) + + # Stop excess PENDING_MIGRATION replicas when new "replacement" + # replicas have transitioned to RUNNING. The replicas with the + # earliest deadlines should be chosen greedily. + remaining.sort(key=lambda r: deadlines[r.actor_node_id]) + num_excess = min_replicas_to_stop - len(to_stop) + + if num_excess > 0: + to_stop.extend(remaining[:num_excess]) + remaining = remaining[num_excess:] + + return to_stop, remaining + + def migrate_replicas_on_draining_nodes(self, draining_nodes: Dict[str, int]): + # Move replicas back to running if they are no longer on a draining node. + # If this causes the number of replicas to exceed the target state, + # they will be scaled down because `scale_deployment_replicas` is called on + # each deployment after this + for replica in self._replicas.pop(states=[ReplicaState.PENDING_MIGRATION]): + if replica.actor_node_id not in draining_nodes: + self._replicas.add(ReplicaState.RUNNING, replica) + else: + self._replicas.add(ReplicaState.PENDING_MIGRATION, replica) + + # Migrate replicas on draining nodes + for replica in self._replicas.pop( + states=[ReplicaState.UPDATING, ReplicaState.RUNNING, ReplicaState.STARTING] + ): + if replica.actor_node_id in draining_nodes: + # For RUNNING replicas, migrate them safely by starting + # a replacement replica first. + if replica.actor_details.state == ReplicaState.RUNNING: + logger.info( + f"Migrating {replica.replica_id} from draining node " + f"'{replica.actor_node_id}'. A new replica will be created on " + "another node." + ) + self._replicas.add(ReplicaState.PENDING_MIGRATION, replica) + # For replicas that are STARTING or UPDATING, might as + # well terminate them immediately to allow replacement + # replicas to start. Otherwise we need to wait for them + # to transition to RUNNING before starting migration. + else: + self._stop_replica(replica, graceful_stop=True) + else: + self._replicas.add(replica.actor_details.state, replica) + + num_running = self._replicas.count(states=[ReplicaState.RUNNING]) + num_draining = self._replicas.count(states=[ReplicaState.PENDING_MIGRATION]) + num_pending_migration_replicas_to_stop = ( + num_running + num_draining - self._target_state.target_num_replicas + ) + + ( + replicas_to_stop, + replicas_to_keep, + ) = self._choose_pending_migration_replicas_to_stop( + self._replicas.pop(states=[ReplicaState.PENDING_MIGRATION]), + draining_nodes, + num_pending_migration_replicas_to_stop, + ) + for replica in replicas_to_stop: + logger.info( + f"Stopping {replica.replica_id} " + f"on draining node {replica.actor_node_id}." + ) + self._stop_replica(replica, graceful_stop=True) + + for replica in replicas_to_keep: + self._replicas.add(ReplicaState.PENDING_MIGRATION, replica) + + def record_request_routing_info(self, info: RequestRoutingInfo) -> None: + """Records the multiplexed model IDs of a replica. + + Args: + info: RequestRoutingInfo including deployment name, replica tag, + multiplex model ids, and routing stats. + """ + # Find the replica + for replica in self._replicas.get(): + if replica.replica_id == info.replica_id: + if info.multiplexed_model_ids is not None: + replica.record_multiplexed_model_ids(info.multiplexed_model_ids) + if info.routing_stats is not None: + replica.record_routing_stats(info.routing_stats) + self._request_routing_info_updated = True + return + + logger.warning(f"{info.replica_id} not found.") + + def _stop_one_running_replica_for_testing(self): + running_replicas = self._replicas.pop(states=[ReplicaState.RUNNING]) + replica_to_stop = running_replicas.pop() + replica_to_stop.stop(graceful=False) + self._replicas.add(ReplicaState.STOPPING, replica_to_stop) + for replica in running_replicas: + self._replicas.add(ReplicaState.RUNNING, replica) + + +class DeploymentStateManager: + """Manages all state for deployments in the system. + + This class is *not* thread safe, so any state-modifying methods should be + called with a lock held. + """ + + def __init__( + self, + kv_store: KVStoreBase, + long_poll_host: LongPollHost, + all_current_actor_names: List[str], + all_current_placement_group_names: List[str], + cluster_node_info_cache: ClusterNodeInfoCache, + autoscaling_state_manager: AutoscalingStateManager, + head_node_id_override: Optional[str] = None, + create_placement_group_fn_override: Optional[Callable] = None, + ): + self._kv_store = kv_store + self._long_poll_host = long_poll_host + self._cluster_node_info_cache = cluster_node_info_cache + self._deployment_scheduler = default_impl.create_deployment_scheduler( + cluster_node_info_cache, + head_node_id_override, + create_placement_group_fn_override, + ) + self._autoscaling_state_manager = autoscaling_state_manager + + self._shutting_down = False + + self._deployment_states: Dict[DeploymentID, DeploymentState] = {} + self._app_deployment_mapping: Dict[str, Set[str]] = defaultdict(set) + + self._recover_from_checkpoint( + all_current_actor_names, all_current_placement_group_names + ) + + def _create_deployment_state(self, deployment_id): + self._deployment_scheduler.on_deployment_created( + deployment_id, SpreadDeploymentSchedulingPolicy() + ) + + return DeploymentState( + deployment_id, + self._long_poll_host, + self._deployment_scheduler, + self._cluster_node_info_cache, + self._autoscaling_state_manager, + ) + + def _map_actor_names_to_deployment( + self, all_current_actor_names: List[str] + ) -> Dict[str, List[str]]: + """ + Given a list of all actor names queried from current ray cluster, + map them to corresponding deployments. + + Example: + Args: + [A#zxc123, B#xcv234, A#qwe234] + Returns: + { + A: [A#zxc123, A#qwe234] + B: [B#xcv234] + } + """ + all_replica_names = [ + actor_name + for actor_name in all_current_actor_names + if ReplicaID.is_full_id_str(actor_name) + ] + deployment_to_current_replicas = defaultdict(list) + if len(all_replica_names) > 0: + for replica_name in all_replica_names: + replica_id = ReplicaID.from_full_id_str(replica_name) + deployment_to_current_replicas[replica_id.deployment_id].append( + replica_name + ) + + return deployment_to_current_replicas + + def _detect_and_remove_leaked_placement_groups( + self, + all_current_actor_names: List[str], + all_current_placement_group_names: List[str], + ): + """Detect and remove any placement groups not associated with a replica. + + This can happen under certain rare circumstances: + - The controller creates a placement group then crashes before creating + the associated replica actor. + - While the controller is down, a replica actor crashes but its placement + group still exists. + + In both of these (or any other unknown cases), we simply need to remove the + leaked placement groups. + """ + leaked_pg_names = [] + for pg_name in all_current_placement_group_names: + if ( + ReplicaID.is_full_id_str(pg_name) + and pg_name not in all_current_actor_names + ): + leaked_pg_names.append(pg_name) + + if len(leaked_pg_names) > 0: + logger.warning( + f"Detected leaked placement groups: {leaked_pg_names}. " + "The placement groups will be removed. This can happen in rare " + "circumstances when the controller crashes and should not cause any " + "issues. If this happens repeatedly, please file an issue on GitHub." + ) + + for leaked_pg_name in leaked_pg_names: + try: + pg = ray.util.get_placement_group(leaked_pg_name) + ray.util.remove_placement_group(pg) + except Exception: + logger.exception( + f"Failed to remove leaked placement group {leaked_pg_name}." + ) + + def _recover_from_checkpoint( + self, + all_current_actor_names: List[str], + all_current_placement_group_names: List[str], + ): + """ + Recover from checkpoint upon controller failure with all actor names + found in current cluster. + + Each deployment resumes target state from checkpoint if available. + + For current state it will prioritize reconstructing from current + actor names found that matches deployment tag if applicable. + """ + self._detect_and_remove_leaked_placement_groups( + all_current_actor_names, + all_current_placement_group_names, + ) + + deployment_to_current_replicas = self._map_actor_names_to_deployment( + all_current_actor_names + ) + checkpoint = self._kv_store.get(CHECKPOINT_KEY) + if checkpoint is not None: + deployment_state_info = cloudpickle.loads(checkpoint) + + for deployment_id, checkpoint_data in deployment_state_info.items(): + deployment_state = self._create_deployment_state(deployment_id) + deployment_state.recover_target_state_from_checkpoint(checkpoint_data) + if len(deployment_to_current_replicas[deployment_id]) > 0: + deployment_state.recover_current_state_from_replica_actor_names( # noqa: E501 + deployment_to_current_replicas[deployment_id] + ) + self._deployment_states[deployment_id] = deployment_state + self._app_deployment_mapping[deployment_id.app_name].add( + deployment_id.name + ) + + def shutdown(self): + """ + Shutdown all running replicas by notifying the controller, and leave + it to the controller event loop to take actions afterwards. + + Once shutdown signal is received, it will also prevent any new + deployments or replicas from being created. + + One can send multiple shutdown signals but won't effectively make any + difference compare to calling it once. + """ + self._shutting_down = True + + for deployment_state in self._deployment_states.values(): + deployment_state.delete() + + # TODO(jiaodong): This might not be 100% safe since we deleted + # everything without ensuring all shutdown goals are completed + # yet. Need to address in follow-up PRs. + self._kv_store.delete(CHECKPOINT_KEY) + + # TODO(jiaodong): Need to add some logic to prevent new replicas + # from being created once shutdown signal is sent. + + def is_ready_for_shutdown(self) -> bool: + """Return whether all deployments are shutdown. + + Check there are no deployment states and no checkpoints. + """ + return ( + self._shutting_down + and len(self._deployment_states) == 0 + and self._kv_store.get(CHECKPOINT_KEY) is None + ) + + def save_checkpoint(self) -> None: + """Write a checkpoint of all deployment states.""" + if self._shutting_down: + # Once we're told to shut down, stop writing checkpoints. + # Calling .shutdown() deletes any existing checkpoint. + return + + deployment_state_info = { + deployment_id: deployment_state.get_checkpoint_data() + for deployment_id, deployment_state in self._deployment_states.items() + } + + self._kv_store.put( + CHECKPOINT_KEY, + cloudpickle.dumps(deployment_state_info), + ) + + def get_running_replica_infos( + self, + ) -> Dict[DeploymentID, List[RunningReplicaInfo]]: + return { + id: deployment_state.get_running_replica_infos() + for id, deployment_state in self._deployment_states.items() + } + + def get_deployment_infos(self) -> Dict[DeploymentID, DeploymentInfo]: + infos: Dict[DeploymentID, DeploymentInfo] = {} + for deployment_id, deployment_state in self._deployment_states.items(): + infos[deployment_id] = deployment_state.target_info + + return infos + + def get_deployment(self, deployment_id: DeploymentID) -> Optional[DeploymentInfo]: + if deployment_id in self._deployment_states: + return self._deployment_states[deployment_id].target_info + else: + return None + + def get_deployment_docs_path(self, deployment_id: DeploymentID) -> Optional[str]: + if deployment_id in self._deployment_states: + return self._deployment_states[deployment_id].docs_path + + def get_deployment_details(self, id: DeploymentID) -> Optional[DeploymentDetails]: + """Gets detailed info on a deployment. + + Returns: + DeploymentDetails: if the deployment is live. + None: if the deployment is deleted. + """ + statuses = self.get_deployment_statuses([id]) + if len(statuses) == 0: + return None + else: + status_info = statuses[0] + deployment_state = self._deployment_states[id] + return DeploymentDetails( + name=id.name, + status=status_info.status, + status_trigger=status_info.status_trigger, + message=status_info.message, + deployment_config=_deployment_info_to_schema( + id.name, self.get_deployment(id) + ), + target_num_replicas=deployment_state._target_state.target_num_replicas, + required_resources=deployment_state.target_info.replica_config.resource_dict, + replicas=deployment_state.list_replica_details(), + ) + + def get_deployment_statuses( + self, ids: Optional[List[DeploymentID]] = None + ) -> List[DeploymentStatusInfo]: + """ + Return the statuses of the deployments with the given `ids`. + If `ids` is `None`, returns the status of all deployments. + """ + if ids is None: + # fast path for returning all deployments, + # avoids checking `if ids is None` in a loop + return [ + state.curr_status_info for state in self._deployment_states.values() + ] + else: + statuses = [] + for id in ids: + state = self._deployment_states.get(id) + if state is not None: + statuses.append(state.curr_status_info) + return statuses + + def get_alive_replica_actor_ids(self) -> Set[str]: + alive_replica_actor_ids = set() + for ds in self._deployment_states.values(): + alive_replica_actor_ids |= ds.get_alive_replica_actor_ids() + + return alive_replica_actor_ids + + def deploy( + self, + deployment_id: DeploymentID, + deployment_info: DeploymentInfo, + ) -> bool: + """Deploy the deployment. + + If the deployment already exists with the same version and config, + this is a no-op and returns False. + + Returns: + bool: Whether or not the deployment is being updated. + """ + if deployment_id not in self._deployment_states: + self._deployment_states[deployment_id] = self._create_deployment_state( + deployment_id + ) + self._app_deployment_mapping[deployment_id.app_name].add(deployment_id.name) + self._record_deployment_usage() + + return self._deployment_states[deployment_id].deploy(deployment_info) + + def get_deployments_in_application(self, app_name: str) -> List[str]: + """Return list of deployment names in application.""" + return list(self._app_deployment_mapping[app_name]) + + def delete_deployment(self, id: DeploymentID): + # This method must be idempotent. We should validate that the + # specified deployment exists on the client. + if id in self._deployment_states: + self._deployment_states[id].delete() + + def update(self) -> bool: + """Updates the state of all deployments to match their goal state. + + Returns True if any of the deployments have replicas in the RECOVERING state. + """ + + deleted_ids = [] + any_recovering = False + upscales: Dict[DeploymentID, List[ReplicaSchedulingRequest]] = {} + downscales: Dict[DeploymentID, DeploymentDownscaleRequest] = {} + + # STEP 1: Update current state + for deployment_state in self._deployment_states.values(): + if deployment_state.should_autoscale(): + deployment_state.autoscale() + + deployment_state.check_and_update_replicas() + + # STEP 2: Check current status + for deployment_state in self._deployment_states.values(): + deployment_state.check_curr_status() + + # STEP 3: Drain nodes + draining_nodes = self._cluster_node_info_cache.get_draining_nodes() + allow_new_compaction = len(draining_nodes) == 0 and all( + ds.curr_status_info.status == DeploymentStatus.HEALTHY + # TODO(zcin): Make sure that status should never be healthy if + # the number of running replicas at target version is not at + # target number, so we can remove this defensive check. + and ds.get_num_running_replicas(ds.target_version) == ds.target_num_replicas + # To be extra conservative, only actively compact if there + # are no non-running replicas + and len(ds._replicas.get()) == ds.target_num_replicas + for ds in self._deployment_states.values() + ) + if RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY: + # Tuple of target node to compact, and its draining deadline + node_info: Optional[ + Tuple[str, float] + ] = self._deployment_scheduler.get_node_to_compact( + allow_new_compaction=allow_new_compaction + ) + if node_info: + target_node_id, deadline = node_info + draining_nodes = {target_node_id: deadline} + + for deployment_id, deployment_state in self._deployment_states.items(): + deployment_state.migrate_replicas_on_draining_nodes(draining_nodes) + + # STEP 4: Scale replicas + for deployment_id, deployment_state in self._deployment_states.items(): + upscale, downscale = deployment_state.scale_deployment_replicas() + + if upscale: + upscales[deployment_id] = upscale + if downscale: + downscales[deployment_id] = downscale + + # STEP 5: Update status + for deployment_id, deployment_state in self._deployment_states.items(): + deleted, any_replicas_recovering = deployment_state.check_curr_status() + + if deleted: + deleted_ids.append(deployment_id) + any_recovering |= any_replicas_recovering + + # Take a checkpoint before actually affecting the state of the cluster + # by starting/stopping replicas. + self.save_checkpoint() + + # STEP 6: Schedule all STARTING replicas and stop all STOPPING replicas + deployment_to_replicas_to_stop = self._deployment_scheduler.schedule( + upscales, downscales + ) + for deployment_id, replicas_to_stop in deployment_to_replicas_to_stop.items(): + self._deployment_states[deployment_id].stop_replicas(replicas_to_stop) + for deployment_id, scheduling_requests in upscales.items(): + self._handle_scheduling_request_failures(deployment_id, scheduling_requests) + + # STEP 7: Broadcast long poll information + for deployment_id, deployment_state in self._deployment_states.items(): + deployment_state.broadcast_running_replicas_if_changed() + deployment_state.broadcast_deployment_config_if_changed() + if deployment_state.should_autoscale(): + self._autoscaling_state_manager.update_running_replica_ids( + deployment_id=deployment_id, + running_replicas=deployment_state.get_running_replica_ids(), + ) + + # STEP 8: Cleanup + for deployment_id in deleted_ids: + self._deployment_scheduler.on_deployment_deleted(deployment_id) + self._autoscaling_state_manager.deregister_deployment(deployment_id) + del self._deployment_states[deployment_id] + if ( + deployment_id.app_name in self._app_deployment_mapping + and deployment_id.name + in self._app_deployment_mapping[deployment_id.app_name] + ): + self._app_deployment_mapping[deployment_id.app_name].remove( + deployment_id.name + ) + # Clean up the app_name entry if no deployments are left + if not self._app_deployment_mapping[deployment_id.app_name]: + del self._app_deployment_mapping[deployment_id.app_name] + + if len(deleted_ids): + self._record_deployment_usage() + + return any_recovering + + def _handle_scheduling_request_failures( + self, + deployment_id: DeploymentID, + scheduling_requests: List[ReplicaSchedulingRequest], + ): + """Updates internal datastructures when replicas fail to be scheduled.""" + failed_replicas: List[ReplicaID] = [] + for scheduling_request in scheduling_requests: + if ( + scheduling_request.status + == ReplicaSchedulingRequestStatus.PLACEMENT_GROUP_CREATION_FAILED + ): + failed_replicas.append(scheduling_request.replica_id) + self._deployment_states[deployment_id].record_replica_startup_failure( + "Replica scheduling failed. Failed to create a placement " + f"group for replica {scheduling_request.replica_id}. " + "See Serve controller logs for more details." + ) + elif ( + scheduling_request.status + == ReplicaSchedulingRequestStatus.ACTOR_CREATION_FAILED + ): + failed_replicas.append(scheduling_request.replica_id) + self._deployment_states[deployment_id].record_replica_startup_failure( + "Replica scheduling failed. Failed to create an actor " + f"for replica {scheduling_request.replica_id}. " + "See Serve controller logs for more details." + ) + if failed_replicas: + self._deployment_states[deployment_id].stop_replicas(failed_replicas) + + def _record_deployment_usage(self): + ServeUsageTag.NUM_DEPLOYMENTS.record(str(len(self._deployment_states))) + + num_gpu_deployments = 0 + for deployment_state in self._deployment_states.values(): + if ( + deployment_state.target_info is not None + and deployment_state.target_info.replica_config is not None + and deployment_state.target_info.replica_config.ray_actor_options + is not None + and ( + deployment_state.target_info.replica_config.ray_actor_options.get( + "num_gpus", 0 + ) + > 0 + ) + ): + num_gpu_deployments += 1 + ServeUsageTag.NUM_GPU_DEPLOYMENTS.record(str(num_gpu_deployments)) + + def record_request_routing_info(self, info: RequestRoutingInfo) -> None: + """ + Record request routing information for a replica. + + Args: + info: Request routing info including deployment name, replica tag, + multiplex model ids, and routing stats. + """ + deployment_id = info.replica_id.deployment_id + if deployment_id not in self._deployment_states: + app_msg = f" in application '{deployment_id.app_name}'" + logger.error( + f"Deployment '{deployment_id.name}'{app_msg} not found in state " + "manager." + ) + return + self._deployment_states[deployment_id].record_request_routing_info(info) + + def get_active_node_ids(self) -> Set[str]: + """Return set of node ids with running replicas of any deployment. + + This is used to determine which node has replicas. Only nodes with replicas and + head node should have active proxies. + """ + node_ids = set() + for deployment_state in self._deployment_states.values(): + node_ids.update(deployment_state.get_active_node_ids()) + return node_ids diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/endpoint_state.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/endpoint_state.py new file mode 100644 index 0000000000000000000000000000000000000000..fd2074fd66693d750bf64eb49dbe7e84450bed0d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/endpoint_state.py @@ -0,0 +1,109 @@ +import logging +from typing import Any, Dict, Optional + +from ray import cloudpickle +from ray.serve._private.common import DeploymentID, EndpointInfo +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.long_poll import LongPollHost, LongPollNamespace +from ray.serve._private.storage.kv_store import KVStoreBase + +CHECKPOINT_KEY = "serve-endpoint-state-checkpoint" + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class EndpointState: + """Manages all state for endpoints in the system. + + This class is *not* thread safe, so any state-modifying methods should be + called with a lock held. + """ + + def __init__(self, kv_store: KVStoreBase, long_poll_host: LongPollHost): + self._kv_store = kv_store + self._long_poll_host = long_poll_host + self._endpoints: Dict[DeploymentID, EndpointInfo] = dict() + + checkpoint = self._kv_store.get(CHECKPOINT_KEY) + if checkpoint is not None: + self._endpoints = cloudpickle.loads(checkpoint) + + self._notify_route_table_changed() + + def shutdown(self): + self._kv_store.delete(CHECKPOINT_KEY) + + def is_ready_for_shutdown(self) -> bool: + """Returns whether the endpoint checkpoint has been deleted. + + Get the endpoint checkpoint from the kv store. If it is None, then it has been + deleted. + """ + return self._kv_store.get(CHECKPOINT_KEY) is None + + def _checkpoint(self): + self._kv_store.put(CHECKPOINT_KEY, cloudpickle.dumps(self._endpoints)) + + def _notify_route_table_changed(self): + self._long_poll_host.notify_changed( + {LongPollNamespace.ROUTE_TABLE: self._endpoints} + ) + + def _get_endpoint_for_route(self, route: str) -> Optional[DeploymentID]: + for endpoint, info in self._endpoints.items(): + if info.route == route: + return endpoint + + return None + + def update_endpoint( + self, endpoint: DeploymentID, endpoint_info: EndpointInfo + ) -> None: + """Create or update the given endpoint. + + This method is idempotent - if the endpoint already exists it will be + updated to match the given parameters. Calling this twice with the same + arguments is a no-op. + """ + + if self._endpoints.get(endpoint) == endpoint_info: + return + + existing_route_endpoint = self._get_endpoint_for_route(endpoint_info.route) + if existing_route_endpoint is not None and existing_route_endpoint != endpoint: + logger.debug( + f'route_prefix "{endpoint_info.route}" is currently ' + f'registered to deployment "{existing_route_endpoint.name}". ' + f'Re-registering route_prefix "{endpoint_info.route}" to ' + f'deployment "{endpoint.name}".' + ) + del self._endpoints[existing_route_endpoint] + + self._endpoints[endpoint] = endpoint_info + + self._checkpoint() + self._notify_route_table_changed() + + def get_endpoint_route(self, endpoint: DeploymentID) -> Optional[str]: + if endpoint in self._endpoints: + return self._endpoints[endpoint].route + return None + + def get_endpoints(self) -> Dict[DeploymentID, Dict[str, Any]]: + endpoints = {} + for endpoint, info in self._endpoints.items(): + endpoints[endpoint] = { + "route": info.route, + } + return endpoints + + def delete_endpoint(self, endpoint: DeploymentID) -> None: + # This method must be idempotent. We should validate that the + # specified endpoint exists on the client. + if endpoint not in self._endpoints: + return + + del self._endpoints[endpoint] + + self._checkpoint() + self._notify_route_table_changed() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/grpc_util.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/grpc_util.py new file mode 100644 index 0000000000000000000000000000000000000000..147f68bff9bd6ba81ab1068a25699d72b60529f0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/grpc_util.py @@ -0,0 +1,179 @@ +import asyncio +import logging +from copy import deepcopy +from typing import Callable, List, Optional, Sequence, Tuple +from unittest.mock import Mock + +import grpc +from grpc.aio._server import Server + +from ray.exceptions import RayActorError, RayTaskError +from ray.serve._private.constants import ( + DEFAULT_GRPC_SERVER_OPTIONS, + RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S, + SERVE_LOGGER_NAME, +) +from ray.serve._private.proxy_request_response import ResponseStatus +from ray.serve.config import gRPCOptions +from ray.serve.exceptions import BackPressureError, DeploymentUnavailableError +from ray.serve.generated.serve_pb2_grpc import add_RayServeAPIServiceServicer_to_server + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class gRPCGenericServer(Server): + """Custom gRPC server that will override all service method handlers. + + Original implementation see: https://github.com/grpc/grpc/blob/ + 60c1701f87cacf359aa1ad785728549eeef1a4b0/src/python/grpcio/grpc/aio/_server.py + """ + + def __init__( + self, + service_handler_factory: Callable, + *, + extra_options: Optional[List[Tuple[str, str]]] = None, + ): + super().__init__( + thread_pool=None, + generic_handlers=(), + interceptors=(), + maximum_concurrent_rpcs=None, + compression=None, + options=DEFAULT_GRPC_SERVER_OPTIONS + (extra_options or []), + ) + self.generic_rpc_handlers = [] + self.service_handler_factory = service_handler_factory + + def add_generic_rpc_handlers( + self, generic_rpc_handlers: Sequence[grpc.GenericRpcHandler] + ): + """Override generic_rpc_handlers before adding to the gRPC server. + + This function will override all user defined handlers to have + 1. None `response_serializer` so the server can pass back the + raw protobuf bytes to the user. + 2. `unary_unary` is always calling the unary function generated via + `self.service_handler_factory` + 3. `unary_stream` is always calling the streaming function generated via + `self.service_handler_factory` + """ + serve_rpc_handlers = {} + rpc_handler = generic_rpc_handlers[0] + for service_method, method_handler in rpc_handler._method_handlers.items(): + serve_method_handler = method_handler._replace( + response_serializer=None, + unary_unary=self.service_handler_factory( + service_method=service_method, + stream=False, + ), + unary_stream=self.service_handler_factory( + service_method=service_method, + stream=True, + ), + ) + serve_rpc_handlers[service_method] = serve_method_handler + generic_rpc_handlers[0]._method_handlers = serve_rpc_handlers + self.generic_rpc_handlers.append(generic_rpc_handlers) + super().add_generic_rpc_handlers(generic_rpc_handlers) + + +async def start_grpc_server( + service_handler_factory: Callable, + grpc_options: gRPCOptions, + *, + event_loop: asyncio.AbstractEventLoop, + enable_so_reuseport: bool = False, +) -> asyncio.Task: + """Start a gRPC server that handles requests with the service handler factory. + + Returns a task that blocks until the server exits (e.g., due to error). + """ + from ray.serve._private.default_impl import add_grpc_address + + server = gRPCGenericServer( + service_handler_factory, + extra_options=[("grpc.so_reuseport", str(int(enable_so_reuseport)))], + ) + add_grpc_address(server, f"[::]:{grpc_options.port}") + + # Add built-in gRPC service and user-defined services to the server. + # We pass a mock servicer because the actual implementation will be overwritten + # in the gRPCGenericServer implementation. + mock_servicer = Mock() + for servicer_fn in [ + add_RayServeAPIServiceServicer_to_server + ] + grpc_options.grpc_servicer_func_callable: + servicer_fn(mock_servicer, server) + + await server.start() + return event_loop.create_task(server.wait_for_termination()) + + +def get_grpc_response_status( + exc: BaseException, request_timeout_s: float, request_id: str +) -> ResponseStatus: + if isinstance(exc, TimeoutError): + message = f"Request timed out after {request_timeout_s}s." + return ResponseStatus( + code=grpc.StatusCode.DEADLINE_EXCEEDED, + is_error=True, + message=message, + ) + elif isinstance(exc, asyncio.CancelledError): + message = f"Client for request {request_id} disconnected." + return ResponseStatus( + code=grpc.StatusCode.CANCELLED, + is_error=True, + message=message, + ) + elif isinstance(exc, BackPressureError): + return ResponseStatus( + code=grpc.StatusCode.RESOURCE_EXHAUSTED, + is_error=True, + message=exc.message, + ) + elif isinstance(exc, DeploymentUnavailableError): + if isinstance(exc, RayTaskError): + logger.warning(f"Request failed: {exc}", extra={"log_to_stderr": False}) + return ResponseStatus( + code=grpc.StatusCode.UNAVAILABLE, + is_error=True, + message=exc.message, + ) + else: + if isinstance(exc, (RayActorError, RayTaskError)): + logger.warning(f"Request failed: {exc}", extra={"log_to_stderr": False}) + else: + logger.exception("Request failed due to unexpected error.") + return ResponseStatus( + code=grpc.StatusCode.INTERNAL, + is_error=True, + message=str(exc), + ) + + +def set_grpc_code_and_details( + context: grpc._cython.cygrpc._ServicerContext, status: ResponseStatus +): + # Only the latest code and details will take effect. If the user already + # set them to a truthy value in the context, skip setting them with Serve's + # default values. By default, if nothing is set, the code is 0 and the + # details is "", which both are falsy. So if the user did not set them or + # if they're explicitly set to falsy values, such as None, Serve will + # continue to set them with our default values. + if not context.code(): + context.set_code(status.code) + if not context.details(): + context.set_details(status.message) + + +def set_proxy_default_grpc_options(grpc_options) -> gRPCOptions: + grpc_options = deepcopy(grpc_options) or gRPCOptions() + + if grpc_options.request_timeout_s or RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S: + grpc_options.request_timeout_s = ( + grpc_options.request_timeout_s or RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S + ) + + return grpc_options diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/handle_options.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/handle_options.py new file mode 100644 index 0000000000000000000000000000000000000000..86ac4bc78ad27a4799652308b3b6606425017ad4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/handle_options.py @@ -0,0 +1,76 @@ +from abc import ABC, abstractmethod +from dataclasses import dataclass, fields + +import ray +from ray.serve._private.common import DeploymentHandleSource +from ray.serve._private.constants import RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP +from ray.serve._private.utils import DEFAULT + + +@dataclass(frozen=True) +class InitHandleOptionsBase(ABC): + """Init options for each ServeHandle instance. + + These fields can be set by calling `.init()` on a handle before + sending the first request. + """ + + _prefer_local_routing: bool = False + _source: DeploymentHandleSource = DeploymentHandleSource.UNKNOWN + _run_router_in_separate_loop: bool = RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP + + @classmethod + @abstractmethod + def create(cls, **kwargs) -> "InitHandleOptionsBase": + raise NotImplementedError + + +@dataclass(frozen=True) +class InitHandleOptions(InitHandleOptionsBase): + @classmethod + def create(cls, **kwargs) -> "InitHandleOptions": + for k in list(kwargs.keys()): + if kwargs[k] == DEFAULT.VALUE: + # Use default value + del kwargs[k] + + # Detect replica source for handles + if ( + "_source" not in kwargs + and ray.serve.context._get_internal_replica_context() is not None + ): + kwargs["_source"] = DeploymentHandleSource.REPLICA + + return cls(**kwargs) + + +@dataclass(frozen=True) +class DynamicHandleOptionsBase(ABC): + """Dynamic options for each ServeHandle instance. + + These fields can be changed by calling `.options()` on a handle. + """ + + method_name: str = "__call__" + multiplexed_model_id: str = "" + stream: bool = False + + @abstractmethod + def copy_and_update(self, **kwargs) -> "DynamicHandleOptionsBase": + pass + + +@dataclass(frozen=True) +class DynamicHandleOptions(DynamicHandleOptionsBase): + _by_reference: bool = True + + def copy_and_update(self, **kwargs) -> "DynamicHandleOptions": + new_kwargs = {} + + for f in fields(self): + if f.name not in kwargs or kwargs[f.name] == DEFAULT.VALUE: + new_kwargs[f.name] = getattr(self, f.name) + else: + new_kwargs[f.name] = kwargs[f.name] + + return DynamicHandleOptions(**new_kwargs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/http_util.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/http_util.py new file mode 100644 index 0000000000000000000000000000000000000000..2da5b8223964a3076f8092f59fb9bd2c9bba6be6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/http_util.py @@ -0,0 +1,832 @@ +import asyncio +import inspect +import json +import logging +import pickle +import socket +from collections import deque +from copy import deepcopy +from dataclasses import dataclass +from typing import ( + Any, + AsyncGenerator, + Awaitable, + Callable, + List, + Optional, + Tuple, + Type, + Union, +) + +import starlette +import uvicorn +from fastapi import FastAPI +from fastapi.encoders import jsonable_encoder +from packaging import version +from starlette.datastructures import MutableHeaders +from starlette.middleware import Middleware +from starlette.types import ASGIApp, Message, Receive, Scope, Send +from uvicorn.config import Config +from uvicorn.lifespan.on import LifespanOn + +from ray._common.pydantic_compat import IS_PYDANTIC_2 +from ray.exceptions import RayActorError, RayTaskError +from ray.serve._private.common import RequestMetadata +from ray.serve._private.constants import ( + RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S, + RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH, + RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S, + SERVE_HTTP_REQUEST_ID_HEADER, + SERVE_LOGGER_NAME, +) +from ray.serve._private.proxy_request_response import ResponseStatus +from ray.serve._private.utils import ( + call_function_from_import_path, + generate_request_id, + serve_encoders, +) +from ray.serve.config import HTTPOptions +from ray.serve.exceptions import ( + BackPressureError, + DeploymentUnavailableError, + RayServeException, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@dataclass(frozen=True) +class ASGIArgs: + scope: Scope + receive: Receive + send: Send + + def to_args_tuple(self) -> Tuple[Scope, Receive, Send]: + return (self.scope, self.receive, self.send) + + def to_starlette_request(self) -> starlette.requests.Request: + return starlette.requests.Request( + *self.to_args_tuple(), + ) + + +def make_buffered_asgi_receive(serialized_body: bytes) -> Receive: + """Returns an ASGI receiver that returns the provided buffered body.""" + + # Simulates receiving HTTP body from TCP socket. In reality, the body has + # already been streamed in chunks and stored in serialized_body. + received = False + + async def mock_receive(): + nonlocal received + + # If the request has already been received, starlette will keep polling + # for HTTP disconnect. We will pause forever. The coroutine should be + # cancelled by starlette after the response has been sent. + if received: + block_forever = asyncio.Event() + await block_forever.wait() + + received = True + return {"body": serialized_body, "type": "http.request", "more_body": False} + + return mock_receive + + +def convert_object_to_asgi_messages( + obj: Optional[Any] = None, status_code: int = 200 +) -> List[Message]: + """Serializes the provided object and converts it to ASGI messages. + + These ASGI messages can be sent via an ASGI `send` interface to comprise an HTTP + response. + """ + body = None + content_type = None + if obj is None: + body = b"" + content_type = b"text/plain" + elif isinstance(obj, bytes): + body = obj + content_type = b"text/plain" + elif isinstance(obj, str): + body = obj.encode("utf-8") + content_type = b"text/plain; charset=utf-8" + else: + # `separators=(",", ":")` will remove all whitespaces between separators in the + # json string and return a minimized json string. This helps to reduce the size + # of the response similar to Starlette's JSONResponse. + body = json.dumps( + jsonable_encoder(obj, custom_encoder=serve_encoders), + separators=(",", ":"), + ).encode() + content_type = b"application/json" + + return [ + { + "type": "http.response.start", + "status": status_code, + "headers": [[b"content-type", content_type]], + }, + {"type": "http.response.body", "body": body}, + ] + + +class Response: + """ASGI compliant response class. + + It is expected to be called in async context and pass along + `scope, receive, send` as in ASGI spec. + + >>> from ray.serve.http_util import Response # doctest: +SKIP + >>> scope, receive = ... # doctest: +SKIP + >>> await Response({"k": "v"}).send(scope, receive, send) # doctest: +SKIP + """ + + def __init__(self, content=None, status_code=200): + """Construct a HTTP Response based on input type. + + Args: + content: Any JSON serializable object. + status_code (int, optional): Default status code is 200. + """ + self._messages = convert_object_to_asgi_messages( + obj=content, + status_code=status_code, + ) + + async def send(self, scope, receive, send): + for message in self._messages: + await send(message) + + +async def receive_http_body(scope, receive, send): + body_buffer = [] + more_body = True + while more_body: + message = await receive() + assert message["type"] == "http.request" + + more_body = message["more_body"] + body_buffer.append(message["body"]) + + return b"".join(body_buffer) + + +class MessageQueue(Send): + """Queue enables polling for received or sent messages. + + Implements the ASGI `Send` interface. + + This class: + - Is *NOT* thread safe and should only be accessed from a single asyncio + event loop. + - Assumes a single consumer of the queue (concurrent calls to + `get_messages_nowait` and `wait_for_message` is undefined behavior). + """ + + def __init__(self): + self._message_queue = deque() + self._new_message_event = asyncio.Event() + self._closed = False + self._error = None + + def close(self): + """Close the queue, rejecting new messages. + + Once the queue is closed, existing messages will be returned from + `get_messages_nowait` and subsequent calls to `wait_for_message` will + always return immediately. + """ + self._closed = True + self._new_message_event.set() + + def set_error(self, e: BaseException): + self._error = e + + def put_nowait(self, message: Message): + self._message_queue.append(message) + self._new_message_event.set() + + async def __call__(self, message: Message): + """Send a message, putting it on the queue. + + `RuntimeError` is raised if the queue has been closed using `.close()`. + """ + if self._closed: + raise RuntimeError("New messages cannot be sent after the queue is closed.") + + self.put_nowait(message) + + async def wait_for_message(self): + """Wait until at least one new message is available. + + If a message is available, this method will return immediately on each call + until `get_messages_nowait` is called. + + After the queue is closed using `.close()`, this will always return + immediately. + """ + if not self._closed: + await self._new_message_event.wait() + + def get_messages_nowait(self) -> List[Message]: + """Returns all messages that are currently available (non-blocking). + + At least one message will be present if `wait_for_message` had previously + returned and a subsequent call to `wait_for_message` blocks until at + least one new message is available. + """ + messages = [] + while len(self._message_queue) > 0: + messages.append(self._message_queue.popleft()) + + self._new_message_event.clear() + return messages + + async def get_one_message(self) -> Message: + """This blocks until a message is ready. + + This method should not be used together with get_messages_nowait. + Please use either `get_one_message` or `get_messages_nowait`. + + Raises: + StopAsyncIteration: if the queue is closed and there are no + more messages. + Exception (self._error): if there are no more messages in + the queue and an error has been set. + """ + + if self._error: + raise self._error + + await self._new_message_event.wait() + + if len(self._message_queue) > 0: + msg = self._message_queue.popleft() + + if len(self._message_queue) == 0 and not self._closed: + self._new_message_event.clear() + + return msg + elif len(self._message_queue) == 0 and self._error: + raise self._error + elif len(self._message_queue) == 0 and self._closed: + raise StopAsyncIteration + + async def fetch_messages_from_queue( + self, call_fut: asyncio.Future + ) -> AsyncGenerator[List[Any], None]: + """Repeatedly consume messages from the queue and yield them. + + This is used to fetch queue messages in the system event loop in + a thread-safe manner. + + Args: + call_fut: The async Future pointing to the task from the user + code event loop that is pushing messages onto the queue. + + Yields: + List[Any]: Messages from the queue. + """ + # Repeatedly consume messages from the queue. + wait_for_msg_task = None + try: + while True: + wait_for_msg_task = asyncio.create_task(self.wait_for_message()) + done, _ = await asyncio.wait( + [call_fut, wait_for_msg_task], return_when=asyncio.FIRST_COMPLETED + ) + + messages = self.get_messages_nowait() + if messages: + yield messages + + # Exit once `call_fut` has finished. In this case, all + # messages must have already been sent. + if call_fut in done: + break + + e = call_fut.exception() + if e is not None: + raise e from None + finally: + if not call_fut.done(): + call_fut.cancel() + + if wait_for_msg_task is not None and not wait_for_msg_task.done(): + wait_for_msg_task.cancel() + + +class ASGIReceiveProxy: + """Proxies ASGI receive from an actor. + + The `receive_asgi_messages` callback will be called repeatedly to fetch messages + until a disconnect message is received. + """ + + def __init__( + self, + scope: Scope, + request_metadata: RequestMetadata, + receive_asgi_messages: Callable[[RequestMetadata], Awaitable[bytes]], + ): + self._type = scope["type"] # Either 'http' or 'websocket'. + # Lazy init the queue to ensure it is created in the user code event loop. + self._queue = None + self._request_metadata = request_metadata + self._receive_asgi_messages = receive_asgi_messages + self._disconnect_message = None + + def _get_default_disconnect_message(self) -> Message: + """Return the appropriate disconnect message based on the connection type. + + HTTP ASGI spec: + https://asgi.readthedocs.io/en/latest/specs/www.html#disconnect-receive-event + + WS ASGI spec: + https://asgi.readthedocs.io/en/latest/specs/www.html#disconnect-receive-event-ws + """ + if self._type == "websocket": + return { + "type": "websocket.disconnect", + # 1005 is the default disconnect code according to the ASGI spec. + "code": 1005, + } + else: + return {"type": "http.disconnect"} + + @property + def queue(self) -> asyncio.Queue: + if self._queue is None: + self._queue = asyncio.Queue() + + return self._queue + + async def fetch_until_disconnect(self): + """Fetch messages repeatedly until a disconnect message is received. + + If a disconnect message is received, this function exits and returns it. + + If an exception occurs, it will be raised on the next __call__ and no more + messages will be received. + """ + while True: + try: + pickled_messages = await self._receive_asgi_messages( + self._request_metadata + ) + for message in pickle.loads(pickled_messages): + self.queue.put_nowait(message) + + if message["type"] in {"http.disconnect", "websocket.disconnect"}: + self._disconnect_message = message + return + except KeyError: + # KeyError can be raised if the request is no longer active in the proxy + # (i.e., the user disconnects). This is expected behavior and we should + # not log an error: https://github.com/ray-project/ray/issues/43290. + message = self._get_default_disconnect_message() + self.queue.put_nowait(message) + self._disconnect_message = message + return + except Exception as e: + # Raise unexpected exceptions in the next `__call__`. + self.queue.put_nowait(e) + return + + async def __call__(self) -> Message: + """Return the next message once available. + + This will repeatedly return a disconnect message once it's been received. + """ + if self.queue.empty() and self._disconnect_message is not None: + return self._disconnect_message + + message = await self.queue.get() + if isinstance(message, Exception): + raise message + + return message + + +def make_fastapi_class_based_view(fastapi_app, cls: Type) -> None: + """Transform the `cls`'s methods and class annotations to FastAPI routes. + + Modified from + https://github.com/dmontagu/fastapi-utils/blob/master/fastapi_utils/cbv.py + + Usage: + >>> from fastapi import FastAPI + >>> app = FastAPI() # doctest: +SKIP + >>> class A: # doctest: +SKIP + ... @app.route("/{i}") # doctest: +SKIP + ... def func(self, i: int) -> str: # doctest: +SKIP + ... return self.dep + i # doctest: +SKIP + >>> # just running the app won't work, here. + >>> make_fastapi_class_based_view(app, A) # doctest: +SKIP + >>> # now app can be run properly + """ + # Delayed import to prevent ciruclar imports in workers. + from fastapi import APIRouter, Depends + from fastapi.routing import APIRoute, APIWebSocketRoute + + async def get_current_servable_instance(): + from ray import serve + + return serve.get_replica_context().servable_object + + # Find all the class method routes + class_method_routes = [ + route + for route in fastapi_app.routes + if + # User defined routes must all be APIRoute or APIWebSocketRoute. + isinstance(route, (APIRoute, APIWebSocketRoute)) + # We want to find the route that's bound to the `cls`. + # NOTE(simon): we can't use `route.endpoint in inspect.getmembers(cls)` + # because the FastAPI supports different routes for the methods with + # same name. See #17559. + and (cls.__qualname__ in route.endpoint.__qualname__) + ] + + # Modify these routes and mount it to a new APIRouter. + # We need to to this (instead of modifying in place) because we want to use + # the laster fastapi_app.include_router to re-run the dependency analysis + # for each routes. + new_router = APIRouter() + for route in class_method_routes: + fastapi_app.routes.remove(route) + + # This block just adds a default values to the self parameters so that + # FastAPI knows to inject the object when calling the route. + # Before: def method(self, i): ... + # After: def method(self=Depends(...), *, i):... + old_endpoint = route.endpoint + old_signature = inspect.signature(old_endpoint) + old_parameters = list(old_signature.parameters.values()) + if len(old_parameters) == 0: + # TODO(simon): make it more flexible to support no arguments. + raise RayServeException( + "Methods in FastAPI class-based view must have ``self`` as " + "their first argument." + ) + old_self_parameter = old_parameters[0] + new_self_parameter = old_self_parameter.replace( + default=Depends(get_current_servable_instance) + ) + new_parameters = [new_self_parameter] + [ + # Make the rest of the parameters keyword only because + # the first argument is no longer positional. + parameter.replace(kind=inspect.Parameter.KEYWORD_ONLY) + for parameter in old_parameters[1:] + ] + new_signature = old_signature.replace(parameters=new_parameters) + route.endpoint.__signature__ = new_signature + route.endpoint._serve_cls = cls + new_router.routes.append(route) + fastapi_app.include_router(new_router) + + routes_to_remove = list() + for route in fastapi_app.routes: + if not isinstance(route, (APIRoute, APIWebSocketRoute)): + continue + + # If there is a response model, FastAPI creates a copy of the fields. + # But FastAPI creates the field incorrectly by missing the outer_type_. + if ( + # TODO(edoakes): I don't think this check is complete because we need + # to support v1 models in v2 (from pydantic.v1 import *). + not IS_PYDANTIC_2 + and isinstance(route, APIRoute) + and route.response_model + ): + route.secure_cloned_response_field.outer_type_ = ( + route.response_field.outer_type_ + ) + + # Remove endpoints that belong to other class based views. + serve_cls = getattr(route.endpoint, "_serve_cls", None) + if serve_cls is not None and serve_cls != cls: + routes_to_remove.append(route) + fastapi_app.routes[:] = [r for r in fastapi_app.routes if r not in routes_to_remove] + + +def set_socket_reuse_port(sock: socket.socket) -> bool: + """Mutate a socket object to allow multiple process listening on the same port. + + Returns: + success: whether the setting was successful. + """ + try: + # These two socket options will allow multiple process to bind the the + # same port. Kernel will evenly load balance among the port listeners. + # Note: this will only work on Linux. + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, "SO_REUSEPORT"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + # In some Python binary distribution (e.g., conda py3.6), this flag + # was not present at build time but available in runtime. But + # Python relies on compiler flag to include this in binary. + # Therefore, in the absence of socket.SO_REUSEPORT, we try + # to use `15` which is value in linux kernel. + # https://github.com/torvalds/linux/blob/master/tools/include/uapi/asm-generic/socket.h#L27 + else: + sock.setsockopt(socket.SOL_SOCKET, 15, 1) + return True + except Exception as e: + logger.debug( + f"Setting SO_REUSEPORT failed because of {e}. SO_REUSEPORT is disabled." + ) + return False + + +class ASGIAppReplicaWrapper: + """Provides a common wrapper for replicas running an ASGI app.""" + + def __init__(self, app_or_func: Union[ASGIApp, Callable]): + if inspect.isfunction(app_or_func): + self._asgi_app = app_or_func() + else: + self._asgi_app = app_or_func + + # Use uvicorn's lifespan handling code to properly deal with + # startup and shutdown event. + # If log_config is not None, uvicorn will use the default logger. + # and that interferes with our logging setup. + self._serve_asgi_lifespan = LifespanOn( + Config( + self._asgi_app, + lifespan="on", + log_level=None, + log_config=None, + access_log=False, + ) + ) + + # Replace uvicorn logger with our own. + self._serve_asgi_lifespan.logger = logger + + @property + def app(self) -> ASGIApp: + return self._asgi_app + + @property + def docs_path(self) -> Optional[str]: + if isinstance(self._asgi_app, FastAPI): + return self._asgi_app.docs_url + + async def _run_asgi_lifespan_startup(self): + # LifespanOn's logger logs in INFO level thus becomes spammy + # Within this block we temporarily uplevel for cleaner logging + from ray.serve._private.logging_utils import LoggingContext + + with LoggingContext(self._serve_asgi_lifespan.logger, level=logging.WARNING): + await self._serve_asgi_lifespan.startup() + if self._serve_asgi_lifespan.should_exit: + raise RuntimeError( + "ASGI lifespan startup failed. Check replica logs for details." + ) + + async def __call__( + self, + scope: Scope, + receive: Receive, + send: Send, + ) -> Optional[ASGIApp]: + """Calls into the wrapped ASGI app.""" + await self._asgi_app( + scope, + receive, + send, + ) + + # NOTE: __del__ must be async so that we can run ASGI shutdown + # in the same event loop. + async def __del__(self): + # LifespanOn's logger logs in INFO level thus becomes spammy. + # Within this block we temporarily uplevel for cleaner logging. + from ray.serve._private.logging_utils import LoggingContext + + with LoggingContext(self._serve_asgi_lifespan.logger, level=logging.WARNING): + await self._serve_asgi_lifespan.shutdown() + + +def validate_http_proxy_callback_return( + middlewares: Any, +) -> [Middleware]: + """Validate the return value of HTTP proxy callback. + + Middlewares should be a list of Starlette middlewares. If it is None, we + will treat it as an empty list. If it is not a list, we will raise an + error. If it is a list, we will check if all the items in the list are + Starlette middlewares. + """ + + if middlewares is None: + middlewares = [] + if not isinstance(middlewares, list): + raise ValueError( + "HTTP proxy callback must return a list of Starlette middlewares." + ) + else: + # All middlewares must be Starlette middlewares. + # https://www.starlette.io/middleware/#using-pure-asgi-middleware + for middleware in middlewares: + if not issubclass(type(middleware), Middleware): + raise ValueError( + "HTTP proxy callback must return a list of Starlette middlewares, " + f"instead got {type(middleware)} type item in the list." + ) + return middlewares + + +class RequestIdMiddleware: + def __init__(self, app: ASGIApp): + self._app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send): + headers = MutableHeaders(scope=scope) + request_id = headers.get(SERVE_HTTP_REQUEST_ID_HEADER) + + if request_id is None: + request_id = generate_request_id() + headers.append(SERVE_HTTP_REQUEST_ID_HEADER, request_id) + + async def send_with_request_id(message: Message): + if message["type"] == "http.response.start": + headers = MutableHeaders(scope=message) + headers.append("X-Request-ID", request_id) + if message["type"] == "websocket.accept": + message["X-Request-ID"] = request_id + await send(message) + + await self._app(scope, receive, send_with_request_id) + + +def _apply_middlewares(app: ASGIApp, middlewares: List[Callable]) -> ASGIApp: + """Wrap the ASGI app with the provided middlewares. + + The built-in RequestIdMiddleware will always be applied first. + """ + for middleware in [Middleware(RequestIdMiddleware)] + middlewares: + if version.parse(starlette.__version__) < version.parse("0.35.0"): + app = middleware.cls(app, **middleware.options) + else: + # In starlette >= 0.35.0, middleware.options does not exist: + # https://github.com/encode/starlette/pull/2381. + app = middleware.cls( + app, + *middleware.args, + **middleware.kwargs, + ) + + return app + + +async def start_asgi_http_server( + app: ASGIApp, + http_options: HTTPOptions, + *, + event_loop: asyncio.AbstractEventLoop, + enable_so_reuseport: bool = False, +) -> asyncio.Task: + """Start an HTTP server to run the ASGI app. + + Returns a task that blocks until the server exits (e.g., due to error). + """ + app = _apply_middlewares(app, http_options.middlewares) + + sock = socket.socket() + if enable_so_reuseport: + set_socket_reuse_port(sock) + + try: + sock.bind((http_options.host, http_options.port)) + except OSError as e: + raise RuntimeError( + f"Failed to bind to address '{http_options.host}:{http_options.port}'." + ) from e + + # Even though we set log_level=None, uvicorn adds MessageLoggerMiddleware + # if log level for uvicorn.error is not set. And MessageLoggerMiddleware + # has no use to us. + logging.getLogger("uvicorn.error").level = logging.CRITICAL + + # NOTE: We have to use lower level uvicorn Config and Server + # class because we want to run the server as a coroutine. The only + # alternative is to call uvicorn.run which is blocking. + server = uvicorn.Server( + config=uvicorn.Config( + lambda: app, + factory=True, + host=http_options.host, + port=http_options.port, + root_path=http_options.root_path, + timeout_keep_alive=http_options.keep_alive_timeout_s, + loop=event_loop, + lifespan="off", + access_log=False, + log_level=None, + log_config=None, + ) + ) + + # NOTE(edoakes): we need to override install_signal_handlers here + # because the existing implementation fails if it isn't running in + # the main thread and uvicorn doesn't expose a way to configure it. + server.install_signal_handlers = lambda: None + + return event_loop.create_task(server.serve(sockets=[sock])) + + +def get_http_response_status( + exc: BaseException, request_timeout_s: float, request_id: str +) -> ResponseStatus: + if isinstance(exc, TimeoutError): + return ResponseStatus( + code=408, + is_error=True, + message=f"Request {request_id} timed out after {request_timeout_s}s.", + ) + + elif isinstance(exc, asyncio.CancelledError): + message = f"Client for request {request_id} disconnected, cancelling request." + logger.info(message) + return ResponseStatus( + code=499, + is_error=True, + message=message, + ) + elif isinstance(exc, (BackPressureError, DeploymentUnavailableError)): + if isinstance(exc, RayTaskError): + logger.warning(f"Request failed: {exc}", extra={"log_to_stderr": False}) + return ResponseStatus( + code=503, + is_error=True, + message=exc.message, + ) + else: + if isinstance(exc, (RayActorError, RayTaskError)): + logger.warning(f"Request failed: {exc}", extra={"log_to_stderr": False}) + else: + logger.exception("Request failed due to unexpected error.") + return ResponseStatus( + code=500, + is_error=True, + message=str(exc), + ) + + +def send_http_response_on_exception( + status: ResponseStatus, response_started: bool +) -> List[Message]: + if response_started or status.code not in (408, 503): + return [] + return convert_object_to_asgi_messages( + status.message, + status_code=status.code, + ) + + +def configure_http_options_with_defaults(http_options: HTTPOptions) -> HTTPOptions: + """Enhanced configuration with component-specific options.""" + + http_options = deepcopy(http_options) + + # Apply environment defaults + if (RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S or 0) > 0: + http_options.keep_alive_timeout_s = RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S + + # TODO: Deprecate SERVE_REQUEST_PROCESSING_TIMEOUT_S env var + if http_options.request_timeout_s or RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S: + http_options.request_timeout_s = ( + http_options.request_timeout_s or RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S + ) + + http_options.middlewares = http_options.middlewares or [] + + return http_options + + +def configure_http_middlewares(http_options: HTTPOptions) -> HTTPOptions: + http_options = deepcopy(http_options) + + # Add environment variable middleware + if RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH: + logger.info( + f"Calling user-provided callback from import path " + f"'{RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH}'." + ) + + # noinspection PyTypeChecker + http_options.middlewares.extend( + validate_http_proxy_callback_return( + call_function_from_import_path( + RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH + ) + ) + ) + + return http_options diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/local_testing_mode.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/local_testing_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..c43eb4667a7509730e593f964d209404e94f90a1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/local_testing_mode.py @@ -0,0 +1,344 @@ +import asyncio +import concurrent.futures +import inspect +import logging +import queue +import time +from functools import wraps +from typing import Any, Callable, Coroutine, Dict, Optional, Tuple, Union + +import ray +from ray import cloudpickle +from ray.serve._private.common import DeploymentID, RequestMetadata +from ray.serve._private.constants import ( + RAY_SERVE_RUN_SYNC_IN_THREADPOOL, + SERVE_LOGGER_NAME, +) +from ray.serve._private.replica import UserCallableWrapper +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.router import Router +from ray.serve._private.utils import GENERATOR_COMPOSITION_NOT_SUPPORTED_ERROR +from ray.serve.deployment import Deployment +from ray.serve.exceptions import RequestCancelledError +from ray.serve.handle import ( + DeploymentHandle, + DeploymentResponse, + DeploymentResponseGenerator, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def _validate_deployment_options( + deployment: Deployment, + deployment_id: DeploymentID, +): + if "num_gpus" in deployment.ray_actor_options: + logger.warning( + f"Deployment {deployment_id} has num_gpus configured. " + "CUDA_VISIBLE_DEVICES is not managed automatically in local testing mode. " + ) + + if "runtime_env" in deployment.ray_actor_options: + logger.warning( + f"Deployment {deployment_id} has runtime_env configured. " + "runtime_envs are ignored in local testing mode." + ) + + +def make_local_deployment_handle( + deployment: Deployment, + app_name: str, +) -> DeploymentHandle: + """Constructs an in-process DeploymentHandle. + + This is used in the application build process for local testing mode, + where all deployments of an app run in the local process which enables + faster dev iterations and use of tooling like PDB. + + The user callable will be run on an asyncio loop in a separate thread + (sharing the same code that's used in the replica). + + The constructor for the user callable is run eagerly in this function to + ensure that any exceptions are raised during `serve.run`. + """ + deployment_id = DeploymentID(deployment.name, app_name) + _validate_deployment_options(deployment, deployment_id) + user_callable_wrapper = UserCallableWrapper( + deployment.func_or_class, + deployment.init_args, + deployment.init_kwargs, + deployment_id=deployment_id, + run_sync_methods_in_threadpool=RAY_SERVE_RUN_SYNC_IN_THREADPOOL, + run_user_code_in_separate_thread=True, + local_testing_mode=True, + ) + try: + logger.info(f"Initializing local replica class for {deployment_id}.") + user_callable_wrapper.initialize_callable().result() + user_callable_wrapper.call_reconfigure(deployment.user_config) + except Exception: + logger.exception(f"Failed to initialize deployment {deployment_id}.") + raise + + def _create_local_router( + handle_id: str, deployment_id: DeploymentID, handle_options: Any + ) -> Router: + return LocalRouter( + user_callable_wrapper, + deployment_id=deployment_id, + handle_options=handle_options, + ) + + return DeploymentHandle( + deployment.name, + app_name, + _create_router=_create_local_router, + ) + + +class LocalReplicaResult(ReplicaResult): + """ReplicaResult used by in-process Deployment Handles.""" + + OBJ_REF_NOT_SUPPORTED_ERROR = RuntimeError( + "Converting DeploymentResponses to ObjectRefs is not supported " + "in local testing mode." + ) + REJECTION_NOT_SUPPORTED_ERROR = RuntimeError( + "Request rejection is not supported in local testing mode." + ) + + def __init__( + self, + future: concurrent.futures.Future, + *, + request_id: str, + is_streaming: bool = False, + generator_result_queue: Optional[queue.Queue] = None, + ): + self._future = future + self._lazy_asyncio_future = None + self._request_id = request_id + self._is_streaming = is_streaming + + # For streaming requests, results must be written to this queue. + # The queue will be consumed until the future is completed. + self._generator_result_queue = generator_result_queue + if self._is_streaming: + assert ( + self._generator_result_queue is not None + ), "generator_result_queue must be provided for streaming results." + + @property + def _asyncio_future(self) -> asyncio.Future: + if self._lazy_asyncio_future is None: + self._lazy_asyncio_future = asyncio.wrap_future(self._future) + + return self._lazy_asyncio_future + + def _process_response(f: Union[Callable, Coroutine]): + @wraps(f) + def wrapper(self, *args, **kwargs): + try: + return f(self, *args, **kwargs) + except (asyncio.CancelledError, concurrent.futures.CancelledError): + raise RequestCancelledError(self._request_id) + + @wraps(f) + async def async_wrapper(self, *args, **kwargs): + try: + return await f(self, *args, **kwargs) + except (asyncio.CancelledError, concurrent.futures.CancelledError): + raise RequestCancelledError(self._request_id) + + if inspect.iscoroutinefunction(f): + return async_wrapper + else: + return wrapper + + @_process_response + async def get_rejection_response(self): + raise self.REJECTION_NOT_SUPPORTED_ERROR + + @_process_response + def get(self, timeout_s: Optional[float]): + assert ( + not self._is_streaming + ), "get() can only be called on a non-streaming result." + + try: + return self._future.result(timeout=timeout_s) + except concurrent.futures.TimeoutError: + raise TimeoutError("Timed out waiting for result.") + + @_process_response + async def get_async(self): + assert ( + not self._is_streaming + ), "get_async() can only be called on a non-streaming result." + + return await self._asyncio_future + + @_process_response + def __next__(self): + assert self._is_streaming, "next() can only be called on a streaming result." + + while True: + if self._future.done() and self._generator_result_queue.empty(): + if self._future.exception(): + raise self._future.exception() + else: + raise StopIteration + + try: + return self._generator_result_queue.get(timeout=0.01) + except queue.Empty: + pass + + @_process_response + async def __anext__(self): + assert self._is_streaming, "anext() can only be called on a streaming result." + + # This callback does not pull from the queue, only checks that a result is + # available, else there is a race condition where the future finishes and the + # queue is empty, but this function hasn't returned the result yet. + def _wait_for_result(): + while True: + if self._future.done() or not self._generator_result_queue.empty(): + return + time.sleep(0.01) + + wait_for_result_task = asyncio.get_running_loop().create_task( + asyncio.to_thread(_wait_for_result), + ) + done, _ = await asyncio.wait( + [self._asyncio_future, wait_for_result_task], + return_when=asyncio.FIRST_COMPLETED, + ) + + if not self._generator_result_queue.empty(): + return self._generator_result_queue.get() + + if self._asyncio_future.exception(): + raise self._asyncio_future.exception() + + raise StopAsyncIteration + + def add_done_callback(self, callback: Callable): + self._future.add_done_callback(callback) + + def cancel(self): + self._future.cancel() + + def to_object_ref(self, timeout_s: Optional[float]) -> ray.ObjectRef: + raise self.OBJ_REF_NOT_SUPPORTED_ERROR + + async def to_object_ref_async(self) -> ray.ObjectRef: + raise self.OBJ_REF_NOT_SUPPORTED_ERROR + + def to_object_ref_gen(self) -> ray.ObjectRefGenerator: + raise self.OBJ_REF_NOT_SUPPORTED_ERROR + + +class LocalRouter(Router): + def __init__( + self, + user_callable_wrapper: UserCallableWrapper, + deployment_id: DeploymentID, + handle_options: Any, + ): + self._deployment_id = deployment_id + self._user_callable_wrapper = user_callable_wrapper + assert ( + self._user_callable_wrapper._callable is not None + ), "User callable must already be initialized." + + def running_replicas_populated(self) -> bool: + return True + + def _resolve_deployment_responses( + self, request_args: Tuple[Any], request_kwargs: Dict[str, Any] + ) -> Tuple[Tuple[Any], Dict[str, Any]]: + """Replace DeploymentResponse objects with their results. + + NOTE(edoakes): this currently calls the blocking `.result()` method + on the responses to resolve them to their values. This is a divergence + from the remote codepath where they're resolved concurrently. + """ + + def _new_arg(arg: Any) -> Any: + if isinstance(arg, DeploymentResponse): + new_arg = arg.result(_skip_asyncio_check=True) + elif isinstance(arg, DeploymentResponseGenerator): + raise GENERATOR_COMPOSITION_NOT_SUPPORTED_ERROR + else: + new_arg = arg + + return new_arg + + # Serialize and deserialize the arguments to mimic remote call behavior. + return cloudpickle.loads( + cloudpickle.dumps( + ( + tuple(_new_arg(arg) for arg in request_args), + {k: _new_arg(v) for k, v in request_kwargs.items()}, + ) + ) + ) + + def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> concurrent.futures.Future[LocalReplicaResult]: + request_args, request_kwargs = self._resolve_deployment_responses( + request_args, request_kwargs + ) + + if request_meta.is_streaming: + generator_result_queue = queue.Queue() + + def generator_result_callback(item: Any): + generator_result_queue.put_nowait(item) + + else: + generator_result_queue = None + generator_result_callback = None + + # Conform to the router interface of returning a future to the ReplicaResult. + if request_meta.is_http_request: + fut = self._user_callable_wrapper._call_http_entrypoint( + request_meta, + request_args, + request_kwargs, + generator_result_callback=generator_result_callback, + ) + elif request_meta.is_streaming: + fut = self._user_callable_wrapper._call_user_generator( + request_meta, + request_args, + request_kwargs, + enqueue=generator_result_callback, + ) + else: + fut = self._user_callable_wrapper.call_user_method( + request_meta, + request_args, + request_kwargs, + ) + noop_future = concurrent.futures.Future() + noop_future.set_result( + LocalReplicaResult( + fut, + request_id=request_meta.request_id, + is_streaming=request_meta.is_streaming, + generator_result_queue=generator_result_queue, + ) + ) + return noop_future + + def shutdown(self): + noop_future = concurrent.futures.Future() + noop_future.set_result(None) + return noop_future diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/logging_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4688e30e40890154aeb0064caac3872a74b82d24 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/logging_utils.py @@ -0,0 +1,519 @@ +import builtins +import logging +import os +import sys +import traceback +from typing import Any, Optional + +import ray +from ray._common.ray_constants import LOGGING_ROTATE_BACKUP_COUNT, LOGGING_ROTATE_BYTES +from ray._private.ray_logging.filters import CoreContextFilter +from ray._private.ray_logging.formatters import JSONFormatter, TextFormatter +from ray.serve._private.common import ServeComponentType +from ray.serve._private.constants import ( + RAY_SERVE_ENABLE_JSON_LOGGING, + RAY_SERVE_ENABLE_MEMORY_PROFILING, + RAY_SERVE_LOG_TO_STDERR, + SERVE_LOG_APPLICATION, + SERVE_LOG_COMPONENT, + SERVE_LOG_COMPONENT_ID, + SERVE_LOG_DEPLOYMENT, + SERVE_LOG_LEVEL_NAME, + SERVE_LOG_MESSAGE, + SERVE_LOG_RECORD_FORMAT, + SERVE_LOG_REPLICA, + SERVE_LOG_REQUEST_ID, + SERVE_LOG_ROUTE, + SERVE_LOG_TIME, + SERVE_LOG_UNWANTED_ATTRS, + SERVE_LOGGER_NAME, +) +from ray.serve._private.utils import get_component_file_name +from ray.serve.schema import EncodingType, LoggingConfig + +buildin_print = builtins.print + + +def should_skip_context_filter(record: logging.LogRecord) -> bool: + """Check if the log record should skip the context filter.""" + return getattr(record, "skip_context_filter", False) + + +class ServeCoreContextFilter(CoreContextFilter): + def filter(self, record: logging.LogRecord) -> bool: + if should_skip_context_filter(record): + return True + return super().filter(record) + + +class ServeComponentFilter(logging.Filter): + """Serve component filter. + + The filter will add the component name, id, and type to the log record. + """ + + def __init__( + self, + component_name: str, + component_id: str, + component_type: Optional[ServeComponentType] = None, + ): + self.component_name = component_name + self.component_id = component_id + self.component_type = component_type + + def filter(self, record: logging.LogRecord) -> bool: + """Add component attributes to the log record. + + Note: the filter doesn't do any filtering, it only adds the component + attributes. + """ + if should_skip_context_filter(record): + return True + if self.component_type and self.component_type == ServeComponentType.REPLICA: + setattr(record, SERVE_LOG_DEPLOYMENT, self.component_name) + setattr(record, SERVE_LOG_REPLICA, self.component_id) + setattr(record, SERVE_LOG_COMPONENT, self.component_type) + else: + setattr(record, SERVE_LOG_COMPONENT, self.component_name) + setattr(record, SERVE_LOG_COMPONENT_ID, self.component_id) + + return True + + +class ServeContextFilter(logging.Filter): + """Serve context filter. + + The filter will add the route, request id, app name to the log record. + + Note: the filter doesn't do any filtering, it only adds the serve request context + attributes. + """ + + def filter(self, record): + if should_skip_context_filter(record): + return True + request_context = ray.serve.context._get_serve_request_context() + if request_context.route: + setattr(record, SERVE_LOG_ROUTE, request_context.route) + if request_context.request_id: + setattr(record, SERVE_LOG_REQUEST_ID, request_context.request_id) + if request_context.app_name: + setattr(record, SERVE_LOG_APPLICATION, request_context.app_name) + return True + + +class ServeLogAttributeRemovalFilter(logging.Filter): + """Serve log attribute removal filter. + + The filter will remove unwanted attributes on the log record so they won't be + included in the structured logs. + + Note: the filter doesn't do any filtering, it only removes unwanted attributes. + """ + + def filter(self, record): + for key in SERVE_LOG_UNWANTED_ATTRS: + if hasattr(record, key): + delattr(record, key) + + return True + + +class ServeFormatter(TextFormatter): + """Serve Logging Formatter + + The formatter will generate the log format on the fly based on the field of record. + Optimized to pre-compute format strings and formatters for better performance. + """ + + COMPONENT_LOG_FMT = f"%({SERVE_LOG_LEVEL_NAME})s %({SERVE_LOG_TIME})s {{{SERVE_LOG_COMPONENT}}} {{{SERVE_LOG_COMPONENT_ID}}} " # noqa:E501 + + def __init__( + self, + component_name: str, + component_id: str, + fmt: Optional[str] = None, + datefmt: Optional[str] = None, + style: str = "%", + validate: bool = True, + ): + super().__init__(fmt, datefmt, style, validate) + self.component_log_fmt = ServeFormatter.COMPONENT_LOG_FMT.format( + component_name=component_name, component_id=component_id + ) + + # Pre-compute format strings and formatters for performance + self._precompute_formatters() + + def set_additional_log_standard_attrs(self, *args, **kwargs): + super().set_additional_log_standard_attrs(*args, **kwargs) + self._precompute_formatters() + + def _precompute_formatters(self): + self.base_formatter = self._create_formatter([]) + self.request_formatter = self._create_formatter( + [SERVE_LOG_RECORD_FORMAT[SERVE_LOG_REQUEST_ID]] + ) + + def _create_formatter(self, initial_attrs: list) -> logging.Formatter: + attrs = initial_attrs.copy() + attrs.extend([f"%({k})s" for k in self.additional_log_standard_attrs]) + attrs.append(SERVE_LOG_RECORD_FORMAT[SERVE_LOG_MESSAGE]) + + format_string = self.component_log_fmt + " ".join(attrs) + return logging.Formatter(format_string) + + def format(self, record: logging.LogRecord) -> str: + """Format the log record into the format string. + + Args: + record: The log record to be formatted. + Returns: + The formatted log record in string format. + """ + # Use pre-computed formatters for better performance + if SERVE_LOG_REQUEST_ID in record.__dict__: + return self.request_formatter.format(record) + else: + return self.base_formatter.format(record) + + +def access_log_msg(*, method: str, route: str, status: str, latency_ms: float): + """Returns a formatted message for an HTTP or ServeHandle access log.""" + return f"{method} {route} {status} {latency_ms:.1f}ms" + + +def log_to_stderr_filter(record: logging.LogRecord) -> bool: + """Filters log records based on a parameter in the `extra` dictionary.""" + if not hasattr(record, "log_to_stderr") or record.log_to_stderr is None: + return True + + return record.log_to_stderr + + +def log_access_log_filter(record: logging.LogRecord) -> bool: + """Filters ray serve access log based on 'serve_access_log' key in `extra` dict.""" + if not hasattr(record, "serve_access_log") or record.serve_access_log is None: + return True + + return not record.serve_access_log + + +def get_component_logger_file_path() -> Optional[str]: + """Returns the relative file path for the Serve logger, if it exists. + + If a logger was configured through configure_component_logger() for the Serve + component that's calling this function, this returns the location of the log file + relative to the ray logs directory. + """ + logger = logging.getLogger(SERVE_LOGGER_NAME) + for handler in logger.handlers: + if isinstance(handler, logging.handlers.MemoryHandler): + absolute_path = handler.target.baseFilename + ray_logs_dir = ray._private.worker._global_node.get_logs_dir_path() + if absolute_path.startswith(ray_logs_dir): + return absolute_path[len(ray_logs_dir) :] + + +class StreamToLogger(object): + """ + Fake file-like stream object that redirects writes to a logger instance. + + This comes from https://stackoverflow.com/a/36296215 directly. + """ + + def __init__(self, logger: logging.Logger, log_level: int, original_object: Any): + self._logger = logger + self._log_level = log_level + self._original_object = original_object + self._linebuf = "" + + def __getattr__(self, attr: str) -> Any: + # getting attributes from the original object + return getattr(self._original_object, attr) + + @staticmethod + def get_stacklevel() -> int: + """Rewind stack to get the stacklevel for the user code. + + Going from the back of the traceback and traverse until it's no longer in + logging_utils.py or site-packages. + """ + reverse_traces = traceback.extract_stack()[::-1] + for index, trace in enumerate(reverse_traces): + if ( + "logging_utils.py" not in trace.filename + and "site-packages" not in trace.filename + ): + return index + return 1 + + def write(self, buf: str): + temp_linebuf = self._linebuf + buf + self._linebuf = "" + for line in temp_linebuf.splitlines(True): + # From the io.TextIOWrapper docs: + # On output, if newline is None, any '\n' characters written + # are translated to the system default line separator. + # By default sys.stdout.write() expects '\n' newlines and then + # translates them so this is still cross-platform. + if line[-1] == "\n": + self._logger.log( + self._log_level, + line.rstrip(), + stacklevel=self.get_stacklevel(), + ) + else: + self._linebuf += line + + def flush(self): + if self._linebuf != "": + self._logger.log( + self._log_level, + self._linebuf.rstrip(), + stacklevel=self.get_stacklevel(), + ) + self._linebuf = "" + + def isatty(self) -> bool: + return True + + +def redirected_print(*objects, sep=" ", end="\n", file=None, flush=False): + """Implement python's print function to redirect logs to Serve's logger. + + If the file is set to anything other than stdout, stderr, or None, call the + builtin print. Else, construct the message and redirect to Serve's logger. + + See https://docs.python.org/3/library/functions.html#print + """ + if file not in [sys.stdout, sys.stderr, None]: + return buildin_print(objects, sep=sep, end=end, file=file, flush=flush) + + serve_logger = logging.getLogger(SERVE_LOGGER_NAME) + message = sep.join(map(str, objects)) + end + # We monkey patched print function, so this is always at stack level 2. + serve_logger.log(logging.INFO, message, stacklevel=2) + + +def configure_component_logger( + *, + component_name: str, + component_id: str, + logging_config: LoggingConfig, + component_type: Optional[ServeComponentType] = None, + max_bytes: Optional[int] = None, + backup_count: Optional[int] = None, + stream_handler_only: bool = False, + buffer_size: int = 1, +): + """Configure a logger to be used by a Serve component. + + The logger will log using a standard format to make components identifiable + using the provided name and unique ID for this instance (e.g., replica ID). + + This logger will *not* propagate its log messages to the parent logger(s). + """ + logger = logging.getLogger(SERVE_LOGGER_NAME) + logger.propagate = False + logger.setLevel(logging_config.log_level) + logger.handlers.clear() + + serve_formatter = ServeFormatter(component_name, component_id) + json_formatter = JSONFormatter() + if logging_config.additional_log_standard_attrs: + json_formatter.set_additional_log_standard_attrs( + logging_config.additional_log_standard_attrs + ) + serve_formatter.set_additional_log_standard_attrs( + logging_config.additional_log_standard_attrs + ) + + # Only add stream handler if RAY_SERVE_LOG_TO_STDERR is True or if + # `stream_handler_only` is set to True. + if RAY_SERVE_LOG_TO_STDERR or stream_handler_only: + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(serve_formatter) + stream_handler.addFilter(log_to_stderr_filter) + stream_handler.addFilter(ServeContextFilter()) + logger.addHandler(stream_handler) + + # Skip setting up file handler and stdout/stderr redirect if `stream_handler_only` + # is set to True. Logger such as default serve logger can be configured outside the + # context of a Serve component, we don't want those logs to redirect into serve's + # logger and log files. + if stream_handler_only: + return + + if logging_config.logs_dir: + logs_dir = logging_config.logs_dir + else: + logs_dir = get_serve_logs_dir() + os.makedirs(logs_dir, exist_ok=True) + + if max_bytes is None: + max_bytes = ray._private.worker._global_node.max_bytes + if backup_count is None: + backup_count = ray._private.worker._global_node.backup_count + + log_file_name = get_component_file_name( + component_name=component_name, + component_id=component_id, + component_type=component_type, + suffix=".log", + ) + + file_handler = logging.handlers.RotatingFileHandler( + os.path.join(logs_dir, log_file_name), + maxBytes=max_bytes, + backupCount=backup_count, + ) + if RAY_SERVE_ENABLE_JSON_LOGGING: + logger.warning( + "'RAY_SERVE_ENABLE_JSON_LOGGING' is deprecated, please use " + "'LoggingConfig' to enable json format." + ) + if RAY_SERVE_ENABLE_JSON_LOGGING or logging_config.encoding == EncodingType.JSON: + file_handler.addFilter(ServeCoreContextFilter()) + file_handler.addFilter(ServeContextFilter()) + file_handler.addFilter( + ServeComponentFilter(component_name, component_id, component_type) + ) + file_handler.setFormatter(json_formatter) + else: + file_handler.setFormatter(serve_formatter) + + if logging_config.enable_access_log is False: + file_handler.addFilter(log_access_log_filter) + else: + file_handler.addFilter(ServeContextFilter()) + + # Remove unwanted attributes from the log record. + file_handler.addFilter(ServeLogAttributeRemovalFilter()) + + # Redirect print, stdout, and stderr to Serve logger, only when it's on the replica. + if not RAY_SERVE_LOG_TO_STDERR and component_type == ServeComponentType.REPLICA: + builtins.print = redirected_print + sys.stdout = StreamToLogger(logger, logging.INFO, sys.stdout) + sys.stderr = StreamToLogger(logger, logging.INFO, sys.stderr) + + # Create a memory handler that buffers log records and flushes to file handler + # Buffer capacity: buffer_size records + # Flush triggers: buffer full, ERROR messages, or explicit flush + memory_handler = logging.handlers.MemoryHandler( + capacity=buffer_size, + target=file_handler, + flushLevel=logging.ERROR, # Auto-flush on ERROR/CRITICAL + ) + + # Add the memory handler instead of the file handler directly + logger.addHandler(memory_handler) + + +def configure_default_serve_logger(): + """Helper function to configure the default Serve logger that's used outside of + individual Serve components.""" + configure_component_logger( + component_name="serve", + component_id=str(os.getpid()), + logging_config=LoggingConfig(), + max_bytes=LOGGING_ROTATE_BYTES, + backup_count=LOGGING_ROTATE_BACKUP_COUNT, + stream_handler_only=True, + ) + + +def configure_component_memory_profiler( + component_name: str, + component_id: str, + component_type: Optional[ServeComponentType] = None, +): + """Configures the memory logger for this component. + + Does nothing if RAY_SERVE_ENABLE_MEMORY_PROFILING is disabled. + """ + + if RAY_SERVE_ENABLE_MEMORY_PROFILING: + logger = logging.getLogger(SERVE_LOGGER_NAME) + + try: + import memray + + logs_dir = get_serve_logs_dir() + memray_file_name = get_component_file_name( + component_name=component_name, + component_id=component_id, + component_type=component_type, + suffix="_memray_0.bin", + ) + memray_file_path = os.path.join(logs_dir, memray_file_name) + + # If the actor restarted, memray requires a new file to start + # tracking memory. + restart_counter = 1 + while os.path.exists(memray_file_path): + memray_file_name = get_component_file_name( + component_name=component_name, + component_id=component_id, + component_type=component_type, + suffix=f"_memray_{restart_counter}.bin", + ) + memray_file_path = os.path.join(logs_dir, memray_file_name) + restart_counter += 1 + + # Memray usually tracks the memory usage of only a block of code + # within a context manager. We explicitly call __enter__ here + # instead of using a context manager to track memory usage across + # all of the caller's code instead. + memray.Tracker(memray_file_path, native_traces=True).__enter__() + + logger.info( + "RAY_SERVE_ENABLE_MEMORY_PROFILING is enabled. Started a " + "memray tracker on this actor. Tracker file located at " + f'"{memray_file_path}"' + ) + + except ImportError: + logger.warning( + "RAY_SERVE_ENABLE_MEMORY_PROFILING is enabled, but memray " + "is not installed. No memory profiling is happening. " + "`pip install memray` to enable memory profiling." + ) + + +def get_serve_logs_dir() -> str: + """Get the directory that stores Serve log files. + + If `ray._private.worker._global_node` is None (running outside the context of Ray), + then the current working directory with subdirectory of serve is used as the logs + directory. Otherwise, the logs directory is determined by the global node's logs + directory path. + """ + if ray._private.worker._global_node is None: + return os.path.join(os.getcwd(), "serve") + + return os.path.join(ray._private.worker._global_node.get_logs_dir_path(), "serve") + + +class LoggingContext: + """ + Context manager to manage logging behaviors within a particular block, such as: + 1) Overriding logging level + + Source (python3 official documentation) + https://docs.python.org/3/howto/logging-cookbook.html#using-a-context-manager-for-selective-logging # noqa: E501 + """ + + def __init__(self, logger, level=None): + self.logger = logger + self.level = level + + def __enter__(self): + if self.level is not None: + self.old_level = self.logger.level + self.logger.setLevel(self.level) + + def __exit__(self, et, ev, tb): + if self.level is not None: + self.logger.setLevel(self.old_level) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/long_poll.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/long_poll.py new file mode 100644 index 0000000000000000000000000000000000000000..ca09d55bc8a5e07dedb9fe18e190ec14e3409a4d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/long_poll.py @@ -0,0 +1,488 @@ +import asyncio +import contextvars +import logging +import os +import random +from asyncio import sleep +from asyncio.events import AbstractEventLoop +from collections import defaultdict +from collections.abc import Mapping +from dataclasses import dataclass +from enum import Enum, auto +from typing import Any, Callable, DefaultDict, Dict, Optional, Set, Tuple, Union + +import ray +from ray._common.utils import get_or_create_event_loop +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve.generated.serve_pb2 import ( + DeploymentTargetInfo, + EndpointInfo as EndpointInfoProto, + EndpointSet, + LongPollRequest, + LongPollResult, + UpdatedObject as UpdatedObjectProto, +) +from ray.util import metrics + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +# Each LongPollClient will send requests to LongPollHost to poll changes +# as blocking awaitable. This doesn't scale if we have many client instances +# that will slow down, or even block controller actor's event loop if near +# its max_concurrency limit. Therefore we timeout a polling request after +# a few seconds and let each client retry on their end. +# We randomly select a timeout within this range to avoid a "thundering herd" +# when there are many clients subscribing at the same time. +LISTEN_FOR_CHANGE_REQUEST_TIMEOUT_S = ( + float(os.environ.get("LISTEN_FOR_CHANGE_REQUEST_TIMEOUT_S_LOWER_BOUND", "30")), + float(os.environ.get("LISTEN_FOR_CHANGE_REQUEST_TIMEOUT_S_UPPER_BOUND", "60")), +) + + +class LongPollNamespace(Enum): + def __repr__(self): + return f"{self.__class__.__name__}.{self.name}" + + DEPLOYMENT_TARGETS = auto() + ROUTE_TABLE = auto() + GLOBAL_LOGGING_CONFIG = auto() + DEPLOYMENT_CONFIG = auto() + + +@dataclass +class UpdatedObject: + object_snapshot: Any + # The identifier for the object's version. There is not sequential relation + # among different object's snapshot_ids. + snapshot_id: int + + +# Type signature for the update state callbacks. E.g. +# async def update_state(updated_object: Any): +# do_something(updated_object) +UpdateStateCallable = Callable[[Any], None] +KeyType = Union[str, LongPollNamespace, Tuple[LongPollNamespace, str]] + + +class LongPollState(Enum): + TIME_OUT = auto() + + +class LongPollClient: + """The asynchronous long polling client. + + Args: + host_actor: handle to actor embedding LongPollHost. + key_listeners: a dictionary mapping keys to + callbacks to be called on state update for the corresponding keys. + call_in_event_loop: an asyncio event loop + to post the callback into. + """ + + def __init__( + self, + host_actor, + key_listeners: Dict[KeyType, UpdateStateCallable], + call_in_event_loop: AbstractEventLoop, + ) -> None: + # We used to allow this to be optional, but due to Ray Client issue + # we now enforce all long poll client to post callback to event loop + # See https://github.com/ray-project/ray/issues/20971 + assert call_in_event_loop is not None + + self.host_actor = host_actor + self.key_listeners = key_listeners + self.event_loop = call_in_event_loop + self.snapshot_ids: Dict[KeyType, int] = { + # The initial snapshot id for each key is < 0, + # but real snapshot keys in the long poll host are always >= 0, + # so this will always trigger an initial update. + key: -1 + for key in self.key_listeners.keys() + } + self.is_running = True + + # NOTE(edoakes): we schedule the initial _poll_next call with an empty context + # so that Ray will not recursively cancel the underlying `listen_for_change` + # task. See: https://github.com/ray-project/ray/issues/52476. + self.event_loop.call_soon_threadsafe( + self._poll_next, context=contextvars.Context() + ) + + def stop(self) -> None: + """Stop the long poll client after the next RPC returns.""" + self.is_running = False + + def add_key_listeners( + self, key_listeners: Dict[KeyType, UpdateStateCallable] + ) -> None: + """Add more key listeners to the client. + The new listeners will only be included in the *next* long poll request; + the current request will continue with the existing listeners. + + If a key is already in the client, the new listener will replace the old one, + but the snapshot ID will be preserved, so the new listener will only be called + on the *next* update to that key. + """ + # We need to run the underlying method in the same event loop that runs + # the long poll loop, because we need to mutate the mapping of snapshot IDs, + # which also needs to be serialized by the long poll's RPC to the + # Serve Controller. If those happened concurrently in different threads, + # we could get a `RuntimeError: dictionary changed size during iteration`. + # See https://github.com/ray-project/ray/pull/52793 for more details. + self.event_loop.call_soon_threadsafe(self._add_key_listeners, key_listeners) + + def _add_key_listeners( + self, key_listeners: Dict[KeyType, UpdateStateCallable] + ) -> None: + """Inner method that actually adds the key listeners, to be called + via call_soon_threadsafe for thread safety. + """ + # Only initialize snapshot ids for *new* keys. + self.snapshot_ids.update( + {key: -1 for key in key_listeners.keys() if key not in self.key_listeners} + ) + self.key_listeners.update(key_listeners) + + def _on_callback_completed(self, trigger_at: int): + """Called after a single callback is completed. + + When the total number of callback completed equals to trigger_at, + _poll_next() will be called. This is designed to make sure we only + _poll_next() after all the state callbacks completed. This is a + way to serialize the callback invocations between object versions. + """ + self._callbacks_processed_count += 1 + if self._callbacks_processed_count == trigger_at: + self._poll_next() + + def _poll_next(self): + """Poll the update. The callback is expected to scheduler another + _poll_next call. + """ + if not self.is_running: + return + + self._callbacks_processed_count = 0 + self._current_ref = self.host_actor.listen_for_change.remote(self.snapshot_ids) + self._current_ref._on_completed(lambda update: self._process_update(update)) + + def _schedule_to_event_loop(self, callback): + # Schedule the next iteration only if the loop is running. + # The event loop might not be running if users used a cached + # version across loops. + if self.event_loop.is_running(): + self.event_loop.call_soon_threadsafe(callback) + else: + logger.error("The event loop is closed, shutting down long poll client.") + self.is_running = False + + def _process_update(self, updates: Dict[str, UpdatedObject]): + if isinstance(updates, (ray.exceptions.RayActorError)): + # This can happen during shutdown where the controller is + # intentionally killed, the client should just gracefully + # exit. + logger.debug("LongPollClient failed to connect to host. Shutting down.") + self.is_running = False + return + + if isinstance(updates, ConnectionError): + logger.warning("LongPollClient connection failed, shutting down.") + self.is_running = False + return + + if isinstance(updates, (ray.exceptions.RayTaskError)): + # Some error happened in the controller. It could be a bug or + # some undesired state. + logger.error("LongPollHost errored\n" + updates.traceback_str) + # We must call this in event loop so it works in Ray Client. + # See https://github.com/ray-project/ray/issues/20971 + self._schedule_to_event_loop(self._poll_next) + return + + if updates == LongPollState.TIME_OUT: + logger.debug("LongPollClient polling timed out. Retrying.") + self._schedule_to_event_loop(self._poll_next) + return + + logger.debug( + f"LongPollClient {self} received updates for keys: " + f"{list(updates.keys())}.", + extra={"log_to_stderr": False}, + ) + if not updates: # no updates, no callbacks to run, just poll again + self._schedule_to_event_loop(self._poll_next) + for key, update in updates.items(): + self.snapshot_ids[key] = update.snapshot_id + callback = self.key_listeners[key] + + # Bind the parameters because closures are late-binding. + # https://docs.python-guide.org/writing/gotchas/#late-binding-closures # noqa: E501 + def chained(callback=callback, arg=update.object_snapshot): + callback(arg) + self._on_callback_completed(trigger_at=len(updates)) + + self._schedule_to_event_loop(chained) + + +class LongPollHost: + """The server side object that manages long pulling requests. + + The desired use case is to embed this in an Ray actor. Client will be + expected to call actor.listen_for_change.remote(...). On the host side, + you can call host.notify_changed({key: object}) to update the state and + potentially notify whoever is polling for these values. + + Internally, we use snapshot_ids for each object to identify client with + outdated object and immediately return the result. If the client has the + up-to-date version, then the listen_for_change call will only return when + the object is updated. + """ + + def __init__( + self, + listen_for_change_request_timeout_s: Tuple[ + int, int + ] = LISTEN_FOR_CHANGE_REQUEST_TIMEOUT_S, + ): + # Map object_key -> int + self.snapshot_ids: Dict[KeyType, int] = {} + # Map object_key -> object + self.object_snapshots: Dict[KeyType, Any] = {} + # Map object_key -> set(asyncio.Event waiting for updates) + self.notifier_events: DefaultDict[KeyType, Set[asyncio.Event]] = defaultdict( + set + ) + + self._listen_for_change_request_timeout_s = listen_for_change_request_timeout_s + self.transmission_counter = metrics.Counter( + "serve_long_poll_host_transmission_counter", + description="The number of times the long poll host transmits data.", + tag_keys=("namespace_or_state",), + ) + + def _get_num_notifier_events(self, key: Optional[KeyType] = None): + """Used for testing.""" + if key is not None: + return len(self.notifier_events[key]) + else: + return sum(len(events) for events in self.notifier_events.values()) + + def _count_send( + self, timeout_or_data: Union[LongPollState, Dict[KeyType, UpdatedObject]] + ): + """Helper method that tracks the data sent by listen_for_change. + + Records number of times long poll host sends data in the + ray_serve_long_poll_host_send_counter metric. + """ + + if isinstance(timeout_or_data, LongPollState): + # The only LongPollState is TIME_OUT– the long poll + # connection has timed out. + self.transmission_counter.inc( + value=1, tags={"namespace_or_state": "TIMEOUT"} + ) + else: + data = timeout_or_data + for key in data.keys(): + self.transmission_counter.inc( + value=1, tags={"namespace_or_state": str(key)} + ) + + async def listen_for_change( + self, + keys_to_snapshot_ids: Dict[KeyType, int], + ) -> Union[LongPollState, Dict[KeyType, UpdatedObject]]: + """Listen for changed objects. + + This method will return a dictionary of updated objects. It returns + immediately if any of the snapshot_ids are outdated, + otherwise it will block until there's an update. + """ + # If there are no keys to listen for, + # just wait for a short time to provide backpressure, + # then return an empty update. + if not keys_to_snapshot_ids: + await sleep(1) + + updated_objects = {} + self._count_send(updated_objects) + return updated_objects + + # If there are any keys with outdated snapshot ids, + # return their updated values immediately. + updated_objects = {} + for key, client_snapshot_id in keys_to_snapshot_ids.items(): + try: + existing_id = self.snapshot_ids[key] + except KeyError: + # The caller may ask for keys that we don't know about (yet), + # just ignore them. + # This can happen when, for example, + # a deployment handle is manually created for an app + # that hasn't been deployed yet (by bypassing the safety checks). + continue + + if existing_id != client_snapshot_id: + updated_objects[key] = UpdatedObject( + self.object_snapshots[key], existing_id + ) + if len(updated_objects) > 0: + self._count_send(updated_objects) + return updated_objects + + # Otherwise, register asyncio events to be waited. + async_task_to_events = {} + async_task_to_watched_keys = {} + for key in keys_to_snapshot_ids.keys(): + # Create a new asyncio event for this key. + event = asyncio.Event() + + # Make sure future caller of notify_changed will unblock this + # asyncio Event. + self.notifier_events[key].add(event) + + task = get_or_create_event_loop().create_task(event.wait()) + async_task_to_events[task] = event + async_task_to_watched_keys[task] = key + + done, not_done = await asyncio.wait( + async_task_to_watched_keys.keys(), + return_when=asyncio.FIRST_COMPLETED, + timeout=random.uniform(*self._listen_for_change_request_timeout_s), + ) + + for task in not_done: + task.cancel() + try: + event = async_task_to_events[task] + self.notifier_events[async_task_to_watched_keys[task]].remove(event) + except KeyError: + # Because we use `FIRST_COMPLETED` above, a task in `not_done` may + # actually have had its event removed in `notify_changed`. + pass + + if len(done) == 0: + self._count_send(LongPollState.TIME_OUT) + return LongPollState.TIME_OUT + else: + updated_objects = {} + for task in done: + updated_object_key = async_task_to_watched_keys[task] + updated_objects[updated_object_key] = UpdatedObject( + self.object_snapshots[updated_object_key], + self.snapshot_ids[updated_object_key], + ) + self._count_send(updated_objects) + return updated_objects + + async def listen_for_change_java( + self, + keys_to_snapshot_ids_bytes: bytes, + ) -> bytes: + """Listen for changed objects. only call by java proxy/router now. + Args: + keys_to_snapshot_ids_bytes (Dict[str, int]): the protobuf bytes of + keys_to_snapshot_ids (Dict[str, int]). + """ + request_proto = LongPollRequest.FromString(keys_to_snapshot_ids_bytes) + keys_to_snapshot_ids = { + self._parse_xlang_key(xlang_key): snapshot_id + for xlang_key, snapshot_id in request_proto.keys_to_snapshot_ids.items() + } + keys_to_updated_objects = await self.listen_for_change(keys_to_snapshot_ids) + return self._listen_result_to_proto_bytes(keys_to_updated_objects) + + def _parse_poll_namespace(self, name: str): + if name == LongPollNamespace.ROUTE_TABLE.name: + return LongPollNamespace.ROUTE_TABLE + elif name == LongPollNamespace.DEPLOYMENT_TARGETS.name: + return LongPollNamespace.DEPLOYMENT_TARGETS + else: + return name + + def _parse_xlang_key(self, xlang_key: str) -> KeyType: + if xlang_key is None: + raise ValueError("func _parse_xlang_key: xlang_key is None") + if xlang_key.startswith("(") and xlang_key.endswith(")"): + fields = xlang_key[1:-1].split(",") + if len(fields) == 2: + enum_field = self._parse_poll_namespace(fields[0].strip()) + if isinstance(enum_field, LongPollNamespace): + return enum_field, fields[1].strip() + else: + return self._parse_poll_namespace(xlang_key) + raise ValueError("can not parse key type from xlang_key {}".format(xlang_key)) + + def _build_xlang_key(self, key: KeyType) -> str: + if isinstance(key, tuple): + return "(" + key[0].name + "," + key[1] + ")" + elif isinstance(key, LongPollNamespace): + return key.name + else: + return key + + def _object_snapshot_to_proto_bytes( + self, key: KeyType, object_snapshot: Any + ) -> bytes: + if key == LongPollNamespace.ROUTE_TABLE: + # object_snapshot is Dict[DeploymentID, EndpointInfo] + # NOTE(zcin): the endpoint dictionary broadcasted to Java + # HTTP proxies should use string as key because Java does + # not yet support 2.x or applications + xlang_endpoints = { + str(endpoint_tag): EndpointInfoProto(route=endpoint_info.route) + for endpoint_tag, endpoint_info in object_snapshot.items() + } + return EndpointSet(endpoints=xlang_endpoints).SerializeToString() + elif isinstance(key, tuple) and key[0] == LongPollNamespace.DEPLOYMENT_TARGETS: + # object_snapshot.running_replicas is List[RunningReplicaInfo] + actor_name_list = [ + replica_info.replica_id.to_full_id_str() + for replica_info in object_snapshot.running_replicas + ] + return DeploymentTargetInfo( + replica_names=actor_name_list, + is_available=object_snapshot.is_available, + ).SerializeToString() + else: + return str.encode(str(object_snapshot)) + + def _listen_result_to_proto_bytes( + self, keys_to_updated_objects: Dict[KeyType, UpdatedObject] + ) -> bytes: + xlang_keys_to_updated_objects = { + self._build_xlang_key(key): UpdatedObjectProto( + snapshot_id=updated_object.snapshot_id, + object_snapshot=self._object_snapshot_to_proto_bytes( + key, updated_object.object_snapshot + ), + ) + for key, updated_object in keys_to_updated_objects.items() + } + data = { + "updated_objects": xlang_keys_to_updated_objects, + } + proto = LongPollResult(**data) + return proto.SerializeToString() + + def notify_changed(self, updates: Mapping[KeyType, Any]) -> None: + """ + Update the current snapshot of some objects + and notify any long poll clients. + """ + for object_key, updated_object in updates.items(): + try: + self.snapshot_ids[object_key] += 1 + except KeyError: + # Initial snapshot id must be >= 0, so that the long poll client + # can send a negative initial snapshot id to get a fast update. + # They should also be randomized; see + # https://github.com/ray-project/ray/pull/45881#discussion_r1645243485 + self.snapshot_ids[object_key] = random.randint(0, 1_000_000) + self.object_snapshots[object_key] = updated_object + logger.debug(f"LongPollHost: Notify change for key {object_key}.") + + for event in self.notifier_events.pop(object_key, set()): + event.set() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/metrics_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/metrics_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..14efb553ca0981fb9a487800ab47857c2e7cc749 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/metrics_utils.py @@ -0,0 +1,216 @@ +import asyncio +import bisect +import logging +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Callable, DefaultDict, Dict, Hashable, List, Optional + +from ray.serve._private.constants import ( + METRICS_PUSHER_GRACEFUL_SHUTDOWN_TIMEOUT_S, + SERVE_LOGGER_NAME, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@dataclass +class _MetricsTask: + task_func: Callable + interval_s: float + + +class MetricsPusher: + """Periodically runs registered asyncio tasks.""" + + def __init__( + self, + *, + async_sleep: Optional[Callable[[int], None]] = None, + ): + self._async_sleep = async_sleep or asyncio.sleep + self._tasks: Dict[str, _MetricsTask] = dict() + self._async_tasks: Dict[str, asyncio.Task] = dict() + + # The event needs to be lazily initialized because this class may be constructed + # on the main thread but its methods called on a separate asyncio loop. + self._stop_event: Optional[asyncio.Event] = None + + @property + def stop_event(self) -> asyncio.Event: + if self._stop_event is None: + self._stop_event = asyncio.Event() + + return self._stop_event + + def start(self): + self.stop_event.clear() + + async def metrics_task(self, name: str): + """Periodically runs `task_func` every `interval_s` until `stop_event` is set. + + If `task_func` raises an error, an exception will be logged. + """ + + wait_for_stop_event = asyncio.create_task(self.stop_event.wait()) + while True: + if wait_for_stop_event.done(): + return + + try: + self._tasks[name].task_func() + except Exception as e: + logger.exception(f"Failed to run metrics task '{name}': {e}") + + sleep_task = asyncio.create_task( + self._async_sleep(self._tasks[name].interval_s) + ) + await asyncio.wait( + [sleep_task, wait_for_stop_event], + return_when=asyncio.FIRST_COMPLETED, + ) + + if not sleep_task.done(): + sleep_task.cancel() + + def register_or_update_task( + self, + name: str, + task_func: Callable, + interval_s: int, + ) -> None: + """Register a task under the provided name, or update it. + + This method is idempotent - if a task is already registered with + the specified name, it will update it with the most recent info. + """ + + self._tasks[name] = _MetricsTask(task_func, interval_s) + if name not in self._async_tasks or self._async_tasks[name].done(): + self._async_tasks[name] = asyncio.create_task(self.metrics_task(name)) + + def stop_tasks(self): + self.stop_event.set() + self._tasks.clear() + self._async_tasks.clear() + + async def graceful_shutdown(self): + """Shutdown metrics pusher gracefully. + + This method will ensure idempotency of shutdown call. + """ + + self.stop_event.set() + if self._async_tasks: + await asyncio.wait( + list(self._async_tasks.values()), + timeout=METRICS_PUSHER_GRACEFUL_SHUTDOWN_TIMEOUT_S, + ) + + self._tasks.clear() + self._async_tasks.clear() + + +@dataclass(order=True) +class TimeStampedValue: + timestamp: float + value: float = field(compare=False) + + +class InMemoryMetricsStore: + """A very simple, in memory time series database""" + + def __init__(self): + self.data: DefaultDict[Hashable, List[TimeStampedValue]] = defaultdict(list) + + def add_metrics_point(self, data_points: Dict[Hashable, float], timestamp: float): + """Push new data points to the store. + + Args: + data_points: dictionary containing the metrics values. The + key should uniquely identify this time series + and to be used to perform aggregation. + timestamp: the unix epoch timestamp the metrics are + collected at. + """ + for name, value in data_points.items(): + # Using in-sort to insert while maintaining sorted ordering. + bisect.insort(a=self.data[name], x=TimeStampedValue(timestamp, value)) + + def prune_keys_and_compact_data(self, start_timestamp_s: float): + """Prune keys and compact data that are outdated. + + For keys that haven't had new data recorded after the timestamp, + remove them from the database. + For keys that have, compact the datapoints that were recorded + before the timestamp. + """ + for key, datapoints in list(self.data.items()): + if len(datapoints) == 0 or datapoints[-1].timestamp < start_timestamp_s: + del self.data[key] + else: + self.data[key] = self._get_datapoints(key, start_timestamp_s) + + def _get_datapoints( + self, key: Hashable, window_start_timestamp_s: float + ) -> List[float]: + """Get all data points given key after window_start_timestamp_s""" + + datapoints = self.data[key] + + idx = bisect.bisect( + a=datapoints, + x=TimeStampedValue( + timestamp=window_start_timestamp_s, value=0 # dummy value + ), + ) + return datapoints[idx:] + + def window_average( + self, key: Hashable, window_start_timestamp_s: float, do_compact: bool = True + ) -> Optional[float]: + """Perform a window average operation for metric `key` + + Args: + key: the metric name. + window_start_timestamp_s: the unix epoch timestamp for the + start of the window. The computed average will use all datapoints + from this timestamp until now. + do_compact: whether or not to delete the datapoints that's + before `window_start_timestamp_s` to save memory. Default is + true. + Returns: + The average of all the datapoints for the key on and after time + window_start_timestamp_s, or None if there are no such points. + """ + points_after_idx = self._get_datapoints(key, window_start_timestamp_s) + + if do_compact: + self.data[key] = points_after_idx + + if len(points_after_idx) == 0: + return + return sum(point.value for point in points_after_idx) / len(points_after_idx) + + def max( + self, key: Hashable, window_start_timestamp_s: float, do_compact: bool = True + ): + """Perform a max operation for metric `key`. + + Args: + key: the metric name. + window_start_timestamp_s: the unix epoch timestamp for the + start of the window. The computed average will use all datapoints + from this timestamp until now. + do_compact: whether or not to delete the datapoints that's + before `window_start_timestamp_s` to save memory. Default is + true. + Returns: + Max value of the data points for the key on and after time + window_start_timestamp_s, or None if there are no such points. + """ + points_after_idx = self._get_datapoints(key, window_start_timestamp_s) + + if do_compact: + self.data[key] = points_after_idx + + return max((point.value for point in points_after_idx), default=None) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..c9d65fe4afbf33a1e10f6262a4b65153553b60e7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy.py @@ -0,0 +1,1264 @@ +import asyncio +import gc +import json +import logging +import os +import pickle +import time +from abc import ABC, abstractmethod +from typing import Any, Callable, Dict, Generator, Optional, Set, Tuple + +import grpc +import starlette +import starlette.routing +from packaging import version +from starlette.types import Receive + +import ray +from ray._common.utils import get_or_create_event_loop +from ray._private.ray_logging.filters import CoreContextFilter +from ray.serve._private.common import ( + DeploymentID, + EndpointInfo, + NodeId, + ReplicaID, + RequestMetadata, + RequestProtocol, +) +from ray.serve._private.constants import ( + HEALTHY_MESSAGE, + PROXY_MIN_DRAINING_PERIOD_S, + RAY_SERVE_ENABLE_PROXY_GC_OPTIMIZATIONS, + RAY_SERVE_PROXY_GC_THRESHOLD, + RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE, + REQUEST_LATENCY_BUCKETS_MS, + SERVE_CONTROLLER_NAME, + SERVE_HTTP_REQUEST_ID_HEADER, + SERVE_LOG_COMPONENT, + SERVE_LOG_COMPONENT_ID, + SERVE_LOG_REQUEST_ID, + SERVE_LOG_ROUTE, + SERVE_LOGGER_NAME, + SERVE_MULTIPLEXED_MODEL_ID, + SERVE_NAMESPACE, +) +from ray.serve._private.default_impl import get_proxy_handle +from ray.serve._private.grpc_util import ( + get_grpc_response_status, + set_grpc_code_and_details, + start_grpc_server, +) +from ray.serve._private.http_util import ( + MessageQueue, + configure_http_middlewares, + convert_object_to_asgi_messages, + get_http_response_status, + receive_http_body, + send_http_response_on_exception, + start_asgi_http_server, +) +from ray.serve._private.logging_utils import ( + access_log_msg, + configure_component_logger, + configure_component_memory_profiler, + get_component_logger_file_path, +) +from ray.serve._private.long_poll import LongPollClient, LongPollNamespace +from ray.serve._private.proxy_request_response import ( + ASGIProxyRequest, + HandlerMetadata, + ProxyRequest, + ResponseGenerator, + ResponseHandlerInfo, + ResponseStatus, + gRPCProxyRequest, +) +from ray.serve._private.proxy_response_generator import ProxyResponseGenerator +from ray.serve._private.proxy_router import ProxyRouter +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + generate_request_id, + get_head_node_id, + is_grpc_enabled, +) +from ray.serve.config import HTTPOptions, gRPCOptions +from ray.serve.generated.serve_pb2 import HealthzResponse, ListApplicationsResponse +from ray.serve.handle import DeploymentHandle +from ray.serve.schema import EncodingType, LoggingConfig +from ray.util import metrics + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +SOCKET_REUSE_PORT_ENABLED = ( + os.environ.get("SERVE_SOCKET_REUSE_PORT_ENABLED", "1") == "1" +) + +if os.environ.get("SERVE_REQUEST_PROCESSING_TIMEOUT_S") is not None: + logger.warning( + "The `SERVE_REQUEST_PROCESSING_TIMEOUT_S` environment variable has " + "been deprecated. Please set `request_timeout_s` in your Serve config's " + "`http_options` or `grpc_options` field instead. `SERVE_REQUEST_PROCESSING_TIMEOUT_S` will be " + "ignored in future versions. See: https://docs.ray.io/en/releases-2.5.1/serve/a" + "pi/doc/ray.serve.schema.HTTPOptionsSchema.html#ray.serve.schema.HTTPOptionsSch" + "ema.request_timeout_s and https://docs.ray.io/en/latest/serve/api/" + "doc/ray.serve.config.gRPCOptions.request_timeout_s.html#" + "ray.serve.config.gRPCOptions.request_timeout_s" + ) + + +INITIAL_BACKOFF_PERIOD_SEC = 0.05 +MAX_BACKOFF_PERIOD_SEC = 5 + +DRAINING_MESSAGE = "This node is being drained." + + +class GenericProxy(ABC): + """This class is served as the base class for different types of proxies. + It contains all the common setup and methods required for running a proxy. + + The proxy subclass need to implement the following methods: + - `protocol()` + - `not_found_response()` + - `routes_response()` + - `health_response()` + - `setup_request_context_and_handle()` + - `send_request_to_replica()` + """ + + def __init__( + self, + node_id: NodeId, + node_ip_address: str, + is_head: bool, + proxy_router: ProxyRouter, + request_timeout_s: Optional[float] = None, + access_log_context: Dict[str, Any] = None, + ): + self.request_timeout_s = request_timeout_s + if self.request_timeout_s is not None and self.request_timeout_s < 0: + self.request_timeout_s = None + + self._node_id = node_id + self._is_head = is_head + + self.proxy_router = proxy_router + self.request_counter = metrics.Counter( + f"serve_num_{self.protocol.lower()}_requests", + description=f"The number of {self.protocol} requests processed.", + tag_keys=("route", "method", "application", "status_code"), + ) + + self.request_error_counter = metrics.Counter( + f"serve_num_{self.protocol.lower()}_error_requests", + description=f"The number of errored {self.protocol} responses.", + tag_keys=( + "route", + "error_code", + "method", + "application", + ), + ) + + self.deployment_request_error_counter = metrics.Counter( + f"serve_num_deployment_{self.protocol.lower()}_error_requests", + description=( + f"The number of errored {self.protocol} " + "responses returned by each deployment." + ), + tag_keys=( + "deployment", + "error_code", + "method", + "route", + "application", + ), + ) + + # log REQUEST_LATENCY_BUCKET_MS + logger.debug(f"REQUEST_LATENCY_BUCKET_MS: {REQUEST_LATENCY_BUCKETS_MS}") + self.processing_latency_tracker = metrics.Histogram( + f"serve_{self.protocol.lower()}_request_latency_ms", + description=( + f"The end-to-end latency of {self.protocol} requests " + f"(measured from the Serve {self.protocol} proxy)." + ), + boundaries=REQUEST_LATENCY_BUCKETS_MS, + tag_keys=( + "method", + "route", + "application", + "status_code", + ), + ) + + self.num_ongoing_requests_gauge = metrics.Gauge( + name=f"serve_num_ongoing_{self.protocol.lower()}_requests", + description=f"The number of ongoing requests in this {self.protocol} " + "proxy.", + tag_keys=("node_id", "node_ip_address"), + ).set_default_tags( + { + "node_id": node_id, + "node_ip_address": node_ip_address, + } + ) + + # `self._ongoing_requests` is used to count the number of ongoing requests + self._ongoing_requests = 0 + # The time when the node starts to drain. + # The node is not draining if it's None. + self._draining_start_time: Optional[float] = None + + self._access_log_context = access_log_context or {} + + getattr(ServeUsageTag, f"{self.protocol.upper()}_PROXY_USED").record("1") + + @property + @abstractmethod + def protocol(self) -> RequestProtocol: + """Protocol used in the proxy. + + Each proxy needs to implement its own logic for setting up the protocol. + """ + raise NotImplementedError + + def _is_draining(self) -> bool: + """Whether is proxy actor is in the draining status or not.""" + return self._draining_start_time is not None + + def is_drained(self): + """Check whether the proxy actor is drained or not. + + A proxy actor is drained if it has no ongoing requests + AND it has been draining for more than + `PROXY_MIN_DRAINING_PERIOD_S` seconds. + """ + if not self._is_draining(): + return False + + return (not self._ongoing_requests) and ( + (time.time() - self._draining_start_time) > PROXY_MIN_DRAINING_PERIOD_S + ) + + def update_draining(self, draining: bool): + """Update the draining status of the proxy. + + This is called by the proxy state manager + to drain or un-drain the proxy actor. + """ + + if draining and (not self._is_draining()): + logger.info( + f"Start to drain the proxy actor on node {self._node_id}.", + extra={"log_to_stderr": False}, + ) + self._draining_start_time = time.time() + if (not draining) and self._is_draining(): + logger.info( + f"Stop draining the proxy actor on node {self._node_id}.", + extra={"log_to_stderr": False}, + ) + self._draining_start_time = None + + @abstractmethod + async def not_found_response( + self, proxy_request: ProxyRequest + ) -> ResponseGenerator: + raise NotImplementedError + + @abstractmethod + async def routes_response( + self, *, healthy: bool, message: str + ) -> ResponseGenerator: + raise NotImplementedError + + @abstractmethod + async def health_response( + self, *, healthy: bool, message: str + ) -> ResponseGenerator: + raise NotImplementedError + + def _ongoing_requests_start(self): + """Ongoing requests start. + + The current autoscale logic can downscale nodes with ongoing requests if the + node doesn't have replicas and has no primary copies of objects in the object + store. The counter and the dummy object reference will help to keep the node + alive while draining requests, so they are not dropped unintentionally. + """ + self._ongoing_requests += 1 + self.num_ongoing_requests_gauge.set(self._ongoing_requests) + + def _ongoing_requests_end(self): + """Ongoing requests end. + + Decrement the ongoing request counter and drop the dummy object reference + signaling that the node can be downscaled safely. + """ + self._ongoing_requests -= 1 + self.num_ongoing_requests_gauge.set(self._ongoing_requests) + + def _get_health_or_routes_reponse( + self, proxy_request: ProxyRequest + ) -> ResponseHandlerInfo: + """Get the response handler for system health and route endpoints. + + If the proxy is draining or has not yet received a route table update from the + controller, both will return a non-OK status. + """ + router_ready_for_traffic, router_msg = self.proxy_router.ready_for_traffic( + self._is_head + ) + if self._is_draining(): + healthy = False + message = DRAINING_MESSAGE + elif not router_ready_for_traffic: + healthy = False + message = router_msg + else: + healthy = True + message = HEALTHY_MESSAGE + + if proxy_request.is_health_request: + response_generator = self.health_response(healthy=healthy, message=message) + else: + assert proxy_request.is_route_request + response_generator = self.routes_response(healthy=healthy, message=message) + + return ResponseHandlerInfo( + response_generator=response_generator, + metadata=HandlerMetadata( + route=proxy_request.route_path, + ), + should_record_access_log=False, + should_increment_ongoing_requests=False, + ) + + def _get_response_handler_info( + self, proxy_request: ProxyRequest + ) -> ResponseHandlerInfo: + if proxy_request.is_health_request or proxy_request.is_route_request: + return self._get_health_or_routes_reponse(proxy_request) + + matched_route = None + if self.protocol == RequestProtocol.HTTP: + matched_route = self.proxy_router.match_route(proxy_request.route_path) + elif self.protocol == RequestProtocol.GRPC: + matched_route = self.proxy_router.get_handle_for_endpoint( + proxy_request.route_path + ) + + if matched_route is None: + return ResponseHandlerInfo( + response_generator=self.not_found_response(proxy_request), + metadata=HandlerMetadata( + # Don't include the invalid route prefix because it can blow up our + # metrics' cardinality. + # See: https://github.com/ray-project/ray/issues/47999 + route="", + ), + should_record_access_log=True, + should_increment_ongoing_requests=False, + ) + else: + route_prefix, handle, app_is_cross_language = matched_route + # Modify the path and root path so that reverse lookups and redirection + # work as expected. We do this here instead of in replicas so it can be + # changed without restarting the replicas. + route_path = proxy_request.route_path + if route_prefix != "/" and self.protocol == RequestProtocol.HTTP: + assert not route_prefix.endswith("/") + proxy_request.set_root_path(proxy_request.root_path + route_prefix) + # NOTE(edoakes): starlette<0.33.0 expected the ASGI 'root_prefix' + # to be stripped from the 'path', which wasn't technically following + # the standard. See https://github.com/encode/starlette/pull/2352. + if version.parse(starlette.__version__) < version.parse("0.33.0"): + proxy_request.set_path(route_path.replace(route_prefix, "", 1)) + + # NOTE(edoakes): we use the route_prefix instead of the full HTTP path + # for logs & metrics to avoid high cardinality. + # See: https://github.com/ray-project/ray/issues/47999 + logs_and_metrics_route = ( + route_prefix + if self.protocol == RequestProtocol.HTTP + else handle.deployment_id.app_name + ) + internal_request_id = generate_request_id() + handle, request_id = self.setup_request_context_and_handle( + app_name=handle.deployment_id.app_name, + handle=handle, + route=logs_and_metrics_route, + proxy_request=proxy_request, + internal_request_id=internal_request_id, + ) + + response_generator = self.send_request_to_replica( + request_id=request_id, + internal_request_id=internal_request_id, + handle=handle, + proxy_request=proxy_request, + app_is_cross_language=app_is_cross_language, + ) + + return ResponseHandlerInfo( + response_generator=response_generator, + metadata=HandlerMetadata( + application_name=handle.deployment_id.app_name, + deployment_name=handle.deployment_id.name, + route=logs_and_metrics_route, + ), + should_record_access_log=True, + should_increment_ongoing_requests=True, + ) + + async def proxy_request(self, proxy_request: ProxyRequest) -> ResponseGenerator: + """Wrapper for proxy request. + + This method is served as common entry point by the proxy. It handles the + routing, including routes and health checks, ongoing request counter, + and metrics. + """ + assert proxy_request.request_type in {"http", "websocket", "grpc"} + + response_handler_info = self._get_response_handler_info(proxy_request) + + start_time = time.time() + if response_handler_info.should_increment_ongoing_requests: + self._ongoing_requests_start() + + try: + # The final message yielded must always be the `ResponseStatus`. + status: Optional[ResponseStatus] = None + async for message in response_handler_info.response_generator: + if isinstance(message, ResponseStatus): + status = message + + yield message + + assert status is not None and isinstance(status, ResponseStatus) + finally: + # If anything during the request failed, we still want to ensure the ongoing + # request counter is decremented. + if response_handler_info.should_increment_ongoing_requests: + self._ongoing_requests_end() + + latency_ms = (time.time() - start_time) * 1000.0 + if response_handler_info.should_record_access_log: + request_context = ray.serve.context._get_serve_request_context() + self._access_log_context[SERVE_LOG_ROUTE] = request_context.route + self._access_log_context[SERVE_LOG_REQUEST_ID] = request_context.request_id + logger.info( + access_log_msg( + method=proxy_request.method, + route=request_context.route, + status=str(status.code), + latency_ms=latency_ms, + ), + extra=self._access_log_context, + ) + + self.request_counter.inc( + tags={ + "route": response_handler_info.metadata.route, + "method": proxy_request.method, + "application": response_handler_info.metadata.application_name, + "status_code": str(status.code), + } + ) + + self.processing_latency_tracker.observe( + latency_ms, + tags={ + "route": response_handler_info.metadata.route, + "method": proxy_request.method, + "application": response_handler_info.metadata.application_name, + "status_code": str(status.code), + }, + ) + if status.is_error: + self.request_error_counter.inc( + tags={ + "route": response_handler_info.metadata.route, + "method": proxy_request.method, + "application": response_handler_info.metadata.application_name, + "error_code": str(status.code), + } + ) + self.deployment_request_error_counter.inc( + tags={ + "route": response_handler_info.metadata.route, + "method": proxy_request.method, + "application": response_handler_info.metadata.application_name, + "error_code": str(status.code), + "deployment": response_handler_info.metadata.deployment_name, + } + ) + + @abstractmethod + def setup_request_context_and_handle( + self, + app_name: str, + handle: DeploymentHandle, + route: str, + proxy_request: ProxyRequest, + internal_request_id: str, + ) -> Tuple[DeploymentHandle, str]: + """Setup the request context and handle for the request. + + Each proxy needs to implement its own logic for setting up the request context + and handle. + """ + raise NotImplementedError + + @abstractmethod + async def send_request_to_replica( + self, + request_id: str, + internal_request_id: str, + handle: DeploymentHandle, + proxy_request: ProxyRequest, + app_is_cross_language: bool = False, + ) -> ResponseGenerator: + """Send the request to the replica and handle streaming response. + + Each proxy needs to implement its own logic for sending the request and + handling the streaming response. + """ + raise NotImplementedError + + +class gRPCProxy(GenericProxy): + """This class is meant to be instantiated and run by an gRPC server. + + This is the servicer class for the gRPC server. It implements `unary_unary` + as the entry point for unary gRPC request and `unary_stream` as the entry + point for streaming gRPC request. + """ + + @property + def protocol(self) -> RequestProtocol: + return RequestProtocol.GRPC + + async def not_found_response( + self, proxy_request: ProxyRequest + ) -> ResponseGenerator: + if not proxy_request.app_name: + application_message = "Application metadata not set." + else: + application_message = f"Application '{proxy_request.app_name}' not found." + not_found_message = ( + f"{application_message} Ping " + "/ray.serve.RayServeAPIService/ListApplications for available applications." + ) + + yield ResponseStatus( + code=grpc.StatusCode.NOT_FOUND, + message=not_found_message, + is_error=True, + ) + + async def routes_response( + self, *, healthy: bool, message: str + ) -> ResponseGenerator: + yield ListApplicationsResponse( + application_names=[ + endpoint.app_name for endpoint in self.proxy_router.endpoints + ], + ).SerializeToString() + + yield ResponseStatus( + code=grpc.StatusCode.OK if healthy else grpc.StatusCode.UNAVAILABLE, + message=message, + is_error=not healthy, + ) + + async def health_response(self, *, healthy: bool, message) -> ResponseGenerator: + yield HealthzResponse(message=message).SerializeToString() + yield ResponseStatus( + code=grpc.StatusCode.OK if healthy else grpc.StatusCode.UNAVAILABLE, + message=message, + is_error=not healthy, + ) + + def service_handler_factory(self, service_method: str, stream: bool) -> Callable: + async def unary_unary( + request_proto: Any, context: grpc._cython.cygrpc._ServicerContext + ) -> bytes: + """Entry point of the gRPC proxy unary request. + + This method is called by the gRPC server when a unary request is received. + It wraps the request in a ProxyRequest object and calls proxy_request. + The return value is serialized user defined protobuf bytes. + """ + proxy_request = gRPCProxyRequest( + request_proto=request_proto, + context=context, + service_method=service_method, + stream=False, + ) + + status = None + response = None + async for message in self.proxy_request(proxy_request=proxy_request): + if isinstance(message, ResponseStatus): + status = message + else: + response = message + + set_grpc_code_and_details(context, status) + + return response + + async def unary_stream( + request_proto: Any, context: grpc._cython.cygrpc._ServicerContext + ) -> Generator[bytes, None, None]: + """Entry point of the gRPC proxy streaming request. + + This method is called by the gRPC server when a streaming request is + received. It wraps the request in a ProxyRequest object and calls + proxy_request. The return value is a generator of serialized user defined + protobuf bytes. + """ + proxy_request = gRPCProxyRequest( + request_proto=request_proto, + context=context, + service_method=service_method, + stream=True, + ) + + status = None + async for message in self.proxy_request(proxy_request=proxy_request): + if isinstance(message, ResponseStatus): + status = message + else: + yield message + + set_grpc_code_and_details(context, status) + + return unary_stream if stream else unary_unary + + def setup_request_context_and_handle( + self, + app_name: str, + handle: DeploymentHandle, + route: str, + proxy_request: ProxyRequest, + internal_request_id: str, + ) -> Tuple[DeploymentHandle, str]: + """Setup request context and handle for the request. + + Unpack gRPC request metadata and extract info to set up request context and + handle. + """ + multiplexed_model_id = proxy_request.multiplexed_model_id + request_id = proxy_request.request_id + if not request_id: + request_id = generate_request_id() + proxy_request.request_id = request_id + + handle = handle.options( + stream=proxy_request.stream, + multiplexed_model_id=multiplexed_model_id, + method_name=proxy_request.method_name, + ) + + request_context_info = { + "route": route, + "request_id": request_id, + "_internal_request_id": internal_request_id, + "app_name": app_name, + "multiplexed_model_id": multiplexed_model_id, + "grpc_context": proxy_request.ray_serve_grpc_context, + } + ray.serve.context._serve_request_context.set( + ray.serve.context._RequestContext(**request_context_info) + ) + proxy_request.send_request_id(request_id=request_id) + return handle, request_id + + async def send_request_to_replica( + self, + request_id: str, + internal_request_id: str, + handle: DeploymentHandle, + proxy_request: ProxyRequest, + app_is_cross_language: bool = False, + ) -> ResponseGenerator: + response_generator = ProxyResponseGenerator( + handle.remote(proxy_request.serialized_replica_arg()), + timeout_s=self.request_timeout_s, + ) + + try: + async for context, result in response_generator: + context._set_on_grpc_context(proxy_request.context) + yield result + + status = ResponseStatus(code=grpc.StatusCode.OK) + except BaseException as e: + status = get_grpc_response_status(e, self.request_timeout_s, request_id) + + # The status code should always be set. + assert status is not None + yield status + + +class HTTPProxy(GenericProxy): + """This class is meant to be instantiated and run by an ASGI HTTP server.""" + + def __init__( + self, + node_id: NodeId, + node_ip_address: str, + is_head: bool, + proxy_router: ProxyRouter, + self_actor_name: str, + request_timeout_s: Optional[float] = None, + access_log_context: Dict[str, Any] = None, + ): + super().__init__( + node_id, + node_ip_address, + is_head, + proxy_router, + request_timeout_s=request_timeout_s, + access_log_context=access_log_context, + ) + self.self_actor_name = self_actor_name + self.asgi_receive_queues: Dict[str, MessageQueue] = dict() + + @property + def protocol(self) -> RequestProtocol: + return RequestProtocol.HTTP + + async def not_found_response( + self, proxy_request: ProxyRequest + ) -> ResponseGenerator: + status_code = 404 + for message in convert_object_to_asgi_messages( + f"Path '{proxy_request.path}' not found. " + "Ping http://.../-/routes for available routes.", + status_code=status_code, + ): + yield message + + yield ResponseStatus(code=status_code, is_error=True) + + async def routes_response( + self, *, healthy: bool, message: str + ) -> ResponseGenerator: + status_code = 200 if healthy else 503 + if healthy: + response = dict() + for endpoint, info in self.proxy_router.endpoints.items(): + # For 2.x deployments, return {route -> app name} + if endpoint.app_name: + response[info.route] = endpoint.app_name + # Keep compatibility with 1.x deployments. + else: + response[info.route] = endpoint.name + else: + response = message + + for asgi_message in convert_object_to_asgi_messages( + response, + status_code=status_code, + ): + yield asgi_message + + yield ResponseStatus( + code=status_code, + message=message, + is_error=not healthy, + ) + + async def health_response( + self, *, healthy: bool, message: str = "" + ) -> ResponseGenerator: + status_code = 200 if healthy else 503 + for asgi_message in convert_object_to_asgi_messages( + message, + status_code=status_code, + ): + yield asgi_message + + yield ResponseStatus( + code=status_code, + is_error=not healthy, + message=message, + ) + + async def receive_asgi_messages( + self, request_metadata: RequestMetadata + ) -> ResponseGenerator: + queue = self.asgi_receive_queues.get(request_metadata.internal_request_id, None) + if queue is None: + raise KeyError(f"Request ID {request_metadata.request_id} not found.") + + await queue.wait_for_message() + return queue.get_messages_nowait() + + async def __call__(self, scope, receive, send): + """Implements the ASGI protocol. + + See details at: + https://asgi.readthedocs.io/en/latest/specs/index.html. + """ + proxy_request = ASGIProxyRequest(scope=scope, receive=receive, send=send) + async for message in self.proxy_request(proxy_request): + if not isinstance(message, ResponseStatus): + await send(message) + + async def proxy_asgi_receive( + self, receive: Receive, queue: MessageQueue + ) -> Optional[int]: + """Proxies the `receive` interface, placing its messages into the queue. + + Once a disconnect message is received, the call exits and `receive` is no longer + called. + + For HTTP messages, `None` is always returned. + For websocket messages, the disconnect code is returned if a disconnect code is + received. + """ + try: + while True: + msg = await receive() + await queue(msg) + + if msg["type"] == "http.disconnect": + return None + + if msg["type"] == "websocket.disconnect": + return msg["code"] + finally: + # Close the queue so any subsequent calls to fetch messages return + # immediately: https://github.com/ray-project/ray/issues/38368. + queue.close() + + def setup_request_context_and_handle( + self, + app_name: str, + handle: DeploymentHandle, + route: str, + proxy_request: ProxyRequest, + internal_request_id: str, + ) -> Tuple[DeploymentHandle, str]: + """Setup request context and handle for the request. + + Unpack HTTP request headers and extract info to set up request context and + handle. + """ + request_context_info = { + "route": route, + "app_name": app_name, + "_internal_request_id": internal_request_id, + "is_http_request": True, + } + for key, value in proxy_request.headers: + if key.decode() == SERVE_MULTIPLEXED_MODEL_ID: + multiplexed_model_id = value.decode() + handle = handle.options(multiplexed_model_id=multiplexed_model_id) + request_context_info["multiplexed_model_id"] = multiplexed_model_id + if key.decode() == SERVE_HTTP_REQUEST_ID_HEADER: + request_context_info["request_id"] = value.decode() + ray.serve.context._serve_request_context.set( + ray.serve.context._RequestContext(**request_context_info) + ) + return handle, request_context_info["request_id"] + + async def _format_handle_arg_for_java( + self, + proxy_request: ProxyRequest, + ) -> bytes: + """Convert an HTTP request to the Java-accepted format (single byte string).""" + query_string = proxy_request.scope.get("query_string") + http_body_bytes = await receive_http_body( + proxy_request.scope, proxy_request.receive, proxy_request.send + ) + if query_string: + arg = query_string.decode().split("=", 1)[1] + else: + arg = http_body_bytes.decode() + + return arg + + async def send_request_to_replica( + self, + request_id: str, + internal_request_id: str, + handle: DeploymentHandle, + proxy_request: ProxyRequest, + app_is_cross_language: bool = False, + ) -> ResponseGenerator: + """Send the request to the replica and yield its response messages. + + The yielded values will be ASGI messages until the final one, which will be + the status code. + """ + if app_is_cross_language: + handle_arg_bytes = await self._format_handle_arg_for_java(proxy_request) + # Response is returned as raw bytes, convert it to ASGI messages. + result_callback = convert_object_to_asgi_messages + else: + handle_arg_bytes = proxy_request.serialized_replica_arg( + proxy_actor_name=self.self_actor_name, + ) + # Messages are returned as pickled dictionaries. + result_callback = pickle.loads + + # Proxy the receive interface by placing the received messages on a queue. + # The downstream replica must call back into `receive_asgi_messages` on this + # actor to receive the messages. + receive_queue = MessageQueue() + self.asgi_receive_queues[internal_request_id] = receive_queue + proxy_asgi_receive_task = get_or_create_event_loop().create_task( + self.proxy_asgi_receive(proxy_request.receive, receive_queue) + ) + + response_generator = ProxyResponseGenerator( + handle.remote(handle_arg_bytes), + timeout_s=self.request_timeout_s, + disconnected_task=proxy_asgi_receive_task, + result_callback=result_callback, + ) + + status: Optional[ResponseStatus] = None + response_started = False + expecting_trailers = False + try: + async for asgi_message_batch in response_generator: + # See the ASGI spec for message details: + # https://asgi.readthedocs.io/en/latest/specs/www.html. + for asgi_message in asgi_message_batch: + if asgi_message["type"] == "http.response.start": + # HTTP responses begin with exactly one + # "http.response.start" message containing the "status" + # field. Other response types (e.g., WebSockets) may not. + status_code = str(asgi_message["status"]) + status = ResponseStatus( + code=status_code, + is_error=status_code.startswith(("4", "5")), + ) + expecting_trailers = asgi_message.get("trailers", False) + elif asgi_message["type"] == "websocket.accept": + # Websocket code explicitly handles client disconnects, + # so let the ASGI disconnect message propagate instead of + # cancelling the handler. + response_generator.stop_checking_for_disconnect() + elif ( + asgi_message["type"] == "http.response.body" + and not asgi_message.get("more_body", False) + and not expecting_trailers + ): + # If the body is completed and we aren't expecting trailers, the + # response is done so we should stop listening for disconnects. + response_generator.stop_checking_for_disconnect() + elif asgi_message["type"] == "http.response.trailers": + # If we are expecting trailers, the response is only done when + # the trailers message has been sent. + if not asgi_message.get("more_trailers", False): + response_generator.stop_checking_for_disconnect() + elif asgi_message["type"] in [ + "websocket.close", + "websocket.disconnect", + ]: + status_code = str(asgi_message["code"]) + status = ResponseStatus( + code=status_code, + # All status codes are considered errors aside from: + # 1000 (CLOSE_NORMAL), 1001 (CLOSE_GOING_AWAY). + is_error=status_code not in ["1000", "1001"], + ) + response_generator.stop_checking_for_disconnect() + + yield asgi_message + response_started = True + except BaseException as e: + status = get_http_response_status(e, self.request_timeout_s, request_id) + for asgi_message in send_http_response_on_exception( + status, response_started + ): + yield asgi_message + + finally: + # For websocket connection, queue receive task is done when receiving + # disconnect message from client. + receive_client_disconnect_msg = False + if not proxy_asgi_receive_task.done(): + proxy_asgi_receive_task.cancel() + else: + receive_client_disconnect_msg = True + + # If the server disconnects, status_code can be set above from the + # disconnect message. + # If client disconnects, the disconnect code comes from + # a client message via the receive interface. + if status is None and proxy_request.request_type == "websocket": + if receive_client_disconnect_msg: + # The disconnect message is sent from the client. + status = ResponseStatus( + code=str(proxy_asgi_receive_task.result()), + is_error=True, + ) + else: + # The server disconnect without sending a disconnect message + # (otherwise the `status` would be set). + status = ResponseStatus( + code="1000", # [Sihan] is there a better code for this? + is_error=True, + ) + + del self.asgi_receive_queues[internal_request_id] + + # The status code should always be set. + assert status is not None + yield status + + +@ray.remote(num_cpus=0) +class ProxyActor: + def __init__( + self, + http_options: HTTPOptions, + grpc_options: gRPCOptions, + *, + node_id: NodeId, + node_ip_address: str, + logging_config: LoggingConfig, + long_poll_client: Optional[LongPollClient] = None, + ): # noqa: F821 + self._node_id = node_id + self._node_ip_address = node_ip_address + self._http_options = configure_http_middlewares(http_options) + self._grpc_options = grpc_options + grpc_enabled = is_grpc_enabled(self._grpc_options) + + event_loop = get_or_create_event_loop() + self.long_poll_client = long_poll_client or LongPollClient( + ray.get_actor(SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE), + { + LongPollNamespace.GLOBAL_LOGGING_CONFIG: self._update_logging_config, + LongPollNamespace.ROUTE_TABLE: self._update_routes_in_proxies, + }, + call_in_event_loop=event_loop, + ) + + configure_component_logger( + component_name="proxy", + component_id=node_ip_address, + logging_config=logging_config, + buffer_size=RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE, + ) + + startup_msg = f"Proxy starting on node {self._node_id} (HTTP port: {self._http_options.port}" + if grpc_enabled: + startup_msg += f", gRPC port: {self._grpc_options.port})." + else: + startup_msg += ")." + logger.info(startup_msg) + logger.debug( + f"Configure Proxy actor {ray.get_runtime_context().get_actor_id()} " + f"logger with logging config: {logging_config}" + ) + + configure_component_memory_profiler( + component_name="proxy", component_id=node_ip_address + ) + if logging_config.encoding == EncodingType.JSON: + # Create logging context for access logs as a performance optimization. + # While logging_utils can automatically add Ray core and Serve access log context, + # we pre-compute it here since context evaluation is expensive and this context + # will be reused for multiple access log entries. + ray_core_logging_context = CoreContextFilter.get_ray_core_logging_context() + # remove task level log keys from ray core logging context, it would be nice + # to have task level log keys here but we are letting those go in favor of + # performance optimization. Also we cannot include task level log keys here because + # they would referance the current task (__init__) and not the task that is logging. + for key in CoreContextFilter.TASK_LEVEL_LOG_KEYS: + ray_core_logging_context.pop(key, None) + access_log_context = { + **ray_core_logging_context, + SERVE_LOG_COMPONENT: "proxy", + SERVE_LOG_COMPONENT_ID: self._node_ip_address, + "log_to_stderr": False, + "skip_context_filter": True, + "serve_access_log": True, + } + else: + access_log_context = { + "log_to_stderr": False, + "skip_context_filter": True, + "serve_access_log": True, + } + + is_head = self._node_id == get_head_node_id() + self.proxy_router = ProxyRouter(get_proxy_handle) + self.http_proxy = HTTPProxy( + node_id=self._node_id, + node_ip_address=self._node_ip_address, + is_head=is_head, + self_actor_name=ray.get_runtime_context().get_actor_name(), + proxy_router=self.proxy_router, + request_timeout_s=self._http_options.request_timeout_s, + access_log_context=access_log_context, + ) + self.grpc_proxy = ( + gRPCProxy( + node_id=self._node_id, + node_ip_address=self._node_ip_address, + is_head=is_head, + proxy_router=self.proxy_router, + request_timeout_s=self._grpc_options.request_timeout_s, + access_log_context=access_log_context, + ) + if grpc_enabled + else None + ) + + # Start a task to initialize the HTTP server. + # The result of this task is checked in the `ready` method. + self._start_http_server_task = event_loop.create_task( + start_asgi_http_server( + self.http_proxy, + self._http_options, + event_loop=event_loop, + enable_so_reuseport=SOCKET_REUSE_PORT_ENABLED, + ) + ) + # A task that runs the HTTP server until it exits (currently runs forever). + # Populated with the result of self._start_http_server_task. + self._running_http_server_task: Optional[asyncio.Task] = None + + # Start a task to initialize the gRPC server. + # The result of this task is checked in the `ready` method. + self._start_grpc_server_task: Optional[asyncio.Task] = None + if grpc_enabled: + self._start_grpc_server_task = event_loop.create_task( + start_grpc_server( + self.grpc_proxy.service_handler_factory, + self._grpc_options, + event_loop=event_loop, + enable_so_reuseport=SOCKET_REUSE_PORT_ENABLED, + ), + ) + # A task that runs the gRPC server until it exits (currently runs forever). + # Populated with the result of self._start_grpc_server_task. + self._running_grpc_server_task: Optional[asyncio.Task] = None + + _configure_gc_options() + + def _update_routes_in_proxies(self, endpoints: Dict[DeploymentID, EndpointInfo]): + self.proxy_router.update_routes(endpoints) + + def _update_logging_config(self, logging_config: LoggingConfig): + configure_component_logger( + component_name="proxy", + component_id=self._node_ip_address, + logging_config=logging_config, + ) + + def _get_logging_config(self) -> Tuple: + """Get the logging configuration (for testing purposes).""" + log_file_path = None + for handler in logger.handlers: + if isinstance(handler, logging.handlers.MemoryHandler): + log_file_path = handler.target.baseFilename + return log_file_path + + def _dump_ingress_replicas_for_testing(self, route: str) -> Set[ReplicaID]: + _, handle, _ = self.http_proxy.proxy_router.match_route(route) + return handle._router._asyncio_router._request_router._replica_id_set + + async def ready(self) -> str: + """Blocks until the proxy HTTP (and optionally gRPC) servers are running. + + Returns JSON-serialized metadata containing the proxy's worker ID and log + file path. + + Raises any exceptions that occur setting up the HTTP or gRPC server. + """ + try: + self._running_http_server_task = await self._start_http_server_task + except Exception as e: + logger.exception("Failed to start proxy HTTP server.") + raise e from None + + try: + if self._start_grpc_server_task is not None: + self._running_grpc_server_task = await self._start_grpc_server_task + except Exception as e: + logger.exception("Failed to start proxy gRPC server.") + raise e from None + + # Return proxy metadata used by the controller. + # NOTE(zcin): We need to convert the metadata to a json string because + # of cross-language scenarios. Java can't deserialize a Python tuple. + return json.dumps( + [ + ray.get_runtime_context().get_worker_id(), + get_component_logger_file_path(), + ] + ) + + async def update_draining(self, draining: bool, _after: Optional[Any] = None): + """Update the draining status of the HTTP and gRPC proxies. + + Unused `_after` argument is for scheduling: passing an ObjectRef + allows delaying this call until after the `_after` call has returned. + """ + + self.http_proxy.update_draining(draining) + if self.grpc_proxy: + self.grpc_proxy.update_draining(draining) + + async def is_drained(self, _after: Optional[Any] = None): + """Check whether both HTTP and gRPC proxies are drained or not. + + Unused `_after` argument is for scheduling: passing an ObjectRef + allows delaying this call until after the `_after` call has returned. + """ + + return self.http_proxy.is_drained() and ( + self.grpc_proxy is None or self.grpc_proxy.is_drained() + ) + + async def check_health(self): + """No-op method to check on the health of the HTTP Proxy. + + Make sure the async event loop is not blocked. + """ + logger.debug("Received health check.", extra={"log_to_stderr": False}) + + def pong(self): + """Called by the replica to initialize its handle to the proxy.""" + pass + + async def receive_asgi_messages(self, request_metadata: RequestMetadata) -> bytes: + """Get ASGI messages for the provided `request_metadata`. + + After the proxy has stopped receiving messages for this `request_metadata`, + this will always return immediately. + + Raises `KeyError` if this request ID is not found. This will happen when the + request is no longer being handled (e.g., the user disconnects). + """ + return pickle.dumps( + await self.http_proxy.receive_asgi_messages(request_metadata) + ) + + def _get_http_options(self) -> HTTPOptions: + """Internal method to get HTTP options used by the proxy.""" + return self._http_options + + +def _configure_gc_options(): + if not RAY_SERVE_ENABLE_PROXY_GC_OPTIMIZATIONS: + return + + # Collect any objects that exist already and exclude them from future GC. + gc.collect(2) + gc.freeze() + + # Tune the GC threshold to run less frequently (default is 700). + gc.set_threshold(RAY_SERVE_PROXY_GC_THRESHOLD) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_request_response.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_request_response.py new file mode 100644 index 0000000000000000000000000000000000000000..922621f6242487bf842da4a2c3109564a4edf8a6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_request_response.py @@ -0,0 +1,199 @@ +import logging +import pickle +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Any, AsyncIterator, List, Tuple, Union + +import grpc +from starlette.types import Receive, Scope, Send + +from ray.serve._private.common import StreamingHTTPRequest, gRPCRequest +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.utils import DEFAULT +from ray.serve.grpc_util import RayServegRPCContext + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class ProxyRequest(ABC): + """Base ProxyRequest class to use in the common interface among proxies""" + + @property + @abstractmethod + def request_type(self) -> str: + raise NotImplementedError + + @property + @abstractmethod + def method(self) -> str: + raise NotImplementedError + + @property + @abstractmethod + def route_path(self) -> str: + raise NotImplementedError + + @property + @abstractmethod + def is_route_request(self) -> bool: + raise NotImplementedError + + @property + @abstractmethod + def is_health_request(self) -> bool: + raise NotImplementedError + + +class ASGIProxyRequest(ProxyRequest): + """ProxyRequest implementation to wrap ASGI scope, receive, and send.""" + + def __init__(self, scope: Scope, receive: Receive, send: Send): + self.scope = scope + self.receive = receive + self.send = send + + @property + def request_type(self) -> str: + return self.scope.get("type", "") + + @property + def method(self) -> str: + # WebSocket messages don't have a 'method' field. + return self.scope.get("method", "WS").upper() + + @property + def route_path(self) -> str: + return self.scope.get("path", "")[len(self.root_path) :] + + @property + def is_route_request(self) -> bool: + return self.route_path == "/-/routes" + + @property + def is_health_request(self) -> bool: + return self.route_path == "/-/healthz" + + @property + def client(self) -> str: + return self.scope.get("client", "") + + @property + def root_path(self) -> str: + return self.scope.get("root_path", "") + + @property + def path(self) -> str: + return self.scope.get("path", "") + + @property + def headers(self) -> List[Tuple[bytes, bytes]]: + return self.scope.get("headers", []) + + def set_path(self, path: str): + self.scope["path"] = path + + def set_root_path(self, root_path: str): + self.scope["root_path"] = root_path + + def serialized_replica_arg(self, proxy_actor_name: str) -> bytes: + # NOTE(edoakes): it's important that the request is sent as raw bytes to + # skip the Ray cloudpickle serialization codepath for performance. + return pickle.dumps( + StreamingHTTPRequest( + asgi_scope=self.scope, + proxy_actor_name=proxy_actor_name, + ) + ) + + +class gRPCProxyRequest(ProxyRequest): + """ProxyRequest implementation to wrap gRPC request protobuf and metadata.""" + + def __init__( + self, + request_proto: Any, + context: grpc._cython.cygrpc._ServicerContext, + service_method: str, + stream: bool, + ): + self._request_proto = request_proto + self.context = context + self.service_method = service_method + self.stream = stream + self.app_name = "" + self.request_id = None + self.method_name = "__call__" + self.multiplexed_model_id = DEFAULT.VALUE + # ray_serve_grpc_context is a class implemented by us to be able to serialize + # the object and pass it into the deployment. + self.ray_serve_grpc_context = RayServegRPCContext(context) + self.setup_variables() + + def setup_variables(self): + if not self.is_route_request and not self.is_health_request: + service_method_split = self.service_method.split("/") + self.method_name = service_method_split[-1] + for key, value in self.context.invocation_metadata(): + if key == "application": + self.app_name = value + elif key == "request_id": + self.request_id = value + elif key == "multiplexed_model_id": + self.multiplexed_model_id = value + + @property + def request_type(self) -> str: + return "grpc" + + @property + def method(self) -> str: + return self.service_method + + @property + def route_path(self) -> str: + return self.app_name + + @property + def is_route_request(self) -> bool: + return self.service_method == "/ray.serve.RayServeAPIService/ListApplications" + + @property + def is_health_request(self) -> bool: + return self.service_method == "/ray.serve.RayServeAPIService/Healthz" + + def send_request_id(self, request_id: str): + # Setting the trailing metadata on the ray_serve_grpc_context object, so it's + # not overriding the ones set from the user and will be sent back to the + # client altogether. + self.ray_serve_grpc_context.set_trailing_metadata([("request_id", request_id)]) + + def serialized_replica_arg(self) -> bytes: + # NOTE(edoakes): it's important that the request is sent as raw bytes to + # skip the Ray cloudpickle serialization codepath for performance. + return pickle.dumps(gRPCRequest(user_request_proto=self._request_proto)) + + +@dataclass(frozen=True) +class ResponseStatus: + code: Union[str, grpc.StatusCode] # Must be convertible to a string. + is_error: bool = False + message: str = "" + + +# Yields protocol-specific messages followed by a final `ResponseStatus`. +ResponseGenerator = AsyncIterator[Union[Any, ResponseStatus]] + + +@dataclass(frozen=True) +class HandlerMetadata: + application_name: str = "" + deployment_name: str = "" + route: str = "" + + +@dataclass(frozen=True) +class ResponseHandlerInfo: + response_generator: ResponseGenerator + metadata: HandlerMetadata + should_record_access_log: bool + should_increment_ongoing_requests: bool diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_response_generator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_response_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..59f31849d4a6e317997a0213736b82762d4f9060 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_response_generator.py @@ -0,0 +1,181 @@ +import asyncio +import logging +import time +from abc import ABC, abstractmethod +from asyncio.tasks import FIRST_COMPLETED +from typing import Any, Callable, Optional, Union + +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.utils import calculate_remaining_timeout +from ray.serve.exceptions import RequestCancelledError +from ray.serve.handle import DeploymentResponse, DeploymentResponseGenerator + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class _ProxyResponseGeneratorBase(ABC): + def __init__( + self, + *, + timeout_s: Optional[float] = None, + disconnected_task: Optional[asyncio.Task] = None, + result_callback: Optional[Callable[[Any], Any]] = None, + ): + """Implements a generator wrapping a deployment response. + + Args: + - timeout_s: an end-to-end timeout for the request. If this expires and the + response is not completed, the request will be cancelled. If `None`, + there's no timeout. + - disconnected_task: a task whose completion signals that the client has + disconnected. When this happens, the request will be cancelled. If `None`, + disconnects will not be detected. + - result_callback: will be called on each result before it's returned. If + `None`, the unmodified result is returned. + """ + self._timeout_s = timeout_s + self._start_time_s = time.time() + self._disconnected_task = disconnected_task + self._result_callback = result_callback + + def __aiter__(self): + return self + + @abstractmethod + async def __anext__(self): + """Return the next message in the stream. + + Raises: + TimeoutError: On timeout. + asyncio.CancelledError: On disconnect. + StopAsyncIteration: When the stream is completed. + """ + pass + + def stop_checking_for_disconnect(self): + """Once this is called, the disconnected_task will be ignored.""" + self._disconnected_task = None + + +def swallow_cancelled(task: asyncio.Task): + try: + task.result() + except (RequestCancelledError, asyncio.CancelledError): + # We expect RequestCancelledError to be raised because for disconnect or + # timeouts, we explicitly call resp.cancel(). To avoid "Task exception + # was never retrieved" errors from spamming the proxy logs, swallow + # them here. + pass + except Exception: + # For all other exceptions, do not catch and instead re-raise here so that + # they will be logged properly. + raise + + +class ProxyResponseGenerator(_ProxyResponseGeneratorBase): + """Wraps a unary DeploymentResponse or streaming DeploymentResponseGenerator. + + In the case of a unary DeploymentResponse, __anext__ will only ever return one + result. + """ + + def __init__( + self, + response: Union[DeploymentResponse, DeploymentResponseGenerator], + *, + timeout_s: Optional[float] = None, + disconnected_task: Optional[asyncio.Task] = None, + result_callback: Optional[Callable[[Any], Any]] = None, + ): + super().__init__( + timeout_s=timeout_s, + disconnected_task=disconnected_task, + result_callback=result_callback, + ) + self._done = False + self._response = response + + def cancelled(self) -> bool: + return self._response.cancelled() + + async def __anext__(self): + if self._done: + raise StopAsyncIteration + + try: + if isinstance(self._response, DeploymentResponseGenerator): + result = await self._get_next_streaming_result() + else: + result = await self._get_unary_result() + self._done = True + + if self._result_callback is not None: + result = self._result_callback(result) + except asyncio.CancelledError as e: + # This is specifically for gRPC. The cancellation can happen from client + # dropped connection before the request is completed. If self._response is + # not already cancelled, we want to explicitly cancel the task, so it + # doesn't waste cluster resource in this case and can be terminated + # gracefully. + if not self._response.cancelled(): + self._response.cancel() + self._done = True + + raise e from None + except Exception as e: + self._done = True + raise e from None + + return result + + async def _await_response_anext(self) -> Any: + return await self._response.__anext__() + + async def _get_next_streaming_result(self) -> Any: + next_result_task = asyncio.create_task(self._await_response_anext()) + tasks = [next_result_task] + if self._disconnected_task is not None: + tasks.append(self._disconnected_task) + + done, _ = await asyncio.wait( + tasks, + return_when=FIRST_COMPLETED, + timeout=calculate_remaining_timeout( + timeout_s=self._timeout_s, + start_time_s=self._start_time_s, + curr_time_s=time.time(), + ), + ) + if next_result_task in done: + return next_result_task.result() + elif self._disconnected_task in done: + next_result_task.cancel() + next_result_task.add_done_callback(swallow_cancelled) + self._response.cancel() + raise asyncio.CancelledError() + else: + next_result_task.cancel() + next_result_task.add_done_callback(swallow_cancelled) + self._response.cancel() + raise TimeoutError() + + async def _await_response(self) -> Any: + return await self._response + + async def _get_unary_result(self) -> Any: + result_task = asyncio.create_task(self._await_response()) + tasks = [result_task] + if self._disconnected_task is not None: + tasks.append(self._disconnected_task) + + done, _ = await asyncio.wait( + tasks, return_when=FIRST_COMPLETED, timeout=self._timeout_s + ) + if result_task in done: + return result_task.result() + elif self._disconnected_task in done: + self._response.cancel() + raise asyncio.CancelledError() + else: + self._response.cancel() + raise TimeoutError() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_router.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_router.py new file mode 100644 index 0000000000000000000000000000000000000000..7c40cee8b418225859c77adcd41703e5c1440608 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_router.py @@ -0,0 +1,165 @@ +import logging +from typing import Callable, Dict, List, Optional, Tuple + +from ray.serve._private.common import ApplicationName, DeploymentID, EndpointInfo +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve.handle import DeploymentHandle + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +NO_ROUTES_MESSAGE = "Route table is not populated yet." +NO_REPLICAS_MESSAGE = "No replicas are available yet." + + +class ProxyRouter: + """Router interface for the proxy to use.""" + + def __init__( + self, + get_handle: Callable[[str, str], DeploymentHandle], + ): + # Function to get a handle given a name. Used to mock for testing. + self._get_handle = get_handle + # Contains a ServeHandle for each endpoint. + self.handles: Dict[DeploymentID, DeploymentHandle] = dict() + # Flipped to `True` once the route table has been updated at least once. + # The proxy router is not ready for traffic until the route table is populated + self._route_table_populated = False + + # Info used for HTTP proxy + # Routes sorted in order of decreasing length. + self.sorted_routes: List[str] = list() + # Endpoints associated with the routes. + self.route_info: Dict[str, DeploymentID] = dict() + # Map of application name to is_cross_language. + self.app_to_is_cross_language: Dict[ApplicationName, bool] = dict() + + # Info used for gRPC proxy + # Endpoints info associated with endpoints. + self.endpoints: Dict[DeploymentID, EndpointInfo] = dict() + + def ready_for_traffic(self, is_head: bool) -> Tuple[bool, str]: + """Whether the proxy router is ready to serve traffic. + + The first return value will be false if any of the following hold: + - The route table has not been populated yet with a non-empty set of routes + - The route table has been populated, but none of the handles + have received running replicas yet AND it lives on a worker node. + + Otherwise, the first return value will be true. + """ + + if not self._route_table_populated: + return False, NO_ROUTES_MESSAGE + + # NOTE(zcin): For the proxy on the head node, even if none of its handles have + # been populated with running replicas yet, we MUST mark the proxy as ready for + # traffic. This is to handle the case when all deployments have scaled to zero. + # If the deployments (more precisely, ingress deployments) have all scaled down + # to zero, at least one proxy needs to be able to receive incoming requests to + # trigger upscale. + if is_head: + return True, "" + + for handle in self.handles.values(): + if handle.running_replicas_populated(): + return True, "" + + return False, NO_REPLICAS_MESSAGE + + def update_routes(self, endpoints: Dict[DeploymentID, EndpointInfo]): + logger.info( + f"Got updated endpoints: {endpoints}.", extra={"log_to_stderr": True} + ) + if endpoints: + self._route_table_populated = True + + self.endpoints = endpoints + + existing_handles = set(self.handles.keys()) + routes = [] + route_info = {} + app_to_is_cross_language = {} + for endpoint, info in endpoints.items(): + routes.append(info.route) + route_info[info.route] = endpoint + app_to_is_cross_language[endpoint.app_name] = info.app_is_cross_language + if endpoint in self.handles: + existing_handles.remove(endpoint) + else: + self.handles[endpoint] = self._get_handle(endpoint, info) + + # Clean up any handles that are no longer used. + if len(existing_handles) > 0: + logger.info( + f"Deleting {len(existing_handles)} unused handles.", + extra={"log_to_stderr": False}, + ) + for endpoint in existing_handles: + del self.handles[endpoint] + + # Routes are sorted in order of decreasing length to enable longest + # prefix matching. + self.sorted_routes = sorted(routes, key=lambda x: len(x), reverse=True) + self.route_info = route_info + self.app_to_is_cross_language = app_to_is_cross_language + + def match_route( + self, target_route: str + ) -> Optional[Tuple[str, DeploymentHandle, bool]]: + """Return the longest prefix match among existing routes for the route. + Args: + target_route: route to match against. + Returns: + (route, handle, is_cross_language) if found, else None. + """ + + for route in self.sorted_routes: + if target_route.startswith(route): + matched = False + # If the route we matched on ends in a '/', then so does the + # target route and this must be a match. + if route.endswith("/"): + matched = True + # If the route we matched on doesn't end in a '/', we need to + # do another check to ensure that either this is an exact match + # or the next character in the target route is a '/'. This is + # to guard against the scenario where we have '/route' as a + # prefix and there's a request to '/routesuffix'. In this case, + # it should *not* be a match. + elif len(target_route) == len(route) or target_route[len(route)] == "/": + matched = True + + if matched: + endpoint = self.route_info[route] + return ( + route, + self.handles[endpoint], + self.app_to_is_cross_language[endpoint.app_name], + ) + + return None + + def get_handle_for_endpoint( + self, target_app_name: str + ) -> Optional[Tuple[str, DeploymentHandle, bool]]: + """Return the handle that matches with endpoint. + + Args: + target_app_name: app_name to match against. + Returns: + (route, handle, is_cross_language) for the single app if there + is only one, else find the app and handle for exact match. Else return None. + """ + for endpoint_tag, handle in self.handles.items(): + # If the target_app_name matches with the endpoint or if + # there is only one endpoint. + if target_app_name == endpoint_tag.app_name or len(self.handles) == 1: + endpoint_info = self.endpoints[endpoint_tag] + return ( + endpoint_info.route, + handle, + endpoint_info.app_is_cross_language, + ) + + return None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_state.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_state.py new file mode 100644 index 0000000000000000000000000000000000000000..cea71187d1d93c0e809eab92ffdb02aa97df0c0e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/proxy_state.py @@ -0,0 +1,827 @@ +import asyncio +import json +import logging +import os +from abc import ABC, abstractmethod +from copy import deepcopy +from typing import Dict, List, Optional, Set, Tuple, Type + +import ray +from ray import ObjectRef +from ray._common.network_utils import build_address +from ray.actor import ActorHandle +from ray.exceptions import GetTimeoutError, RayActorError +from ray.serve._private.cluster_node_info_cache import ClusterNodeInfoCache +from ray.serve._private.common import NodeId, RequestProtocol +from ray.serve._private.constants import ( + ASYNC_CONCURRENCY, + PROXY_DRAIN_CHECK_PERIOD_S, + PROXY_HEALTH_CHECK_PERIOD_S, + PROXY_HEALTH_CHECK_TIMEOUT_S, + PROXY_HEALTH_CHECK_UNHEALTHY_THRESHOLD, + PROXY_READY_CHECK_TIMEOUT_S, + RAY_SERVE_ALWAYS_RUN_PROXY_ON_HEAD_NODE, + RAY_SERVE_ENABLE_TASK_EVENTS, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, + SERVE_PROXY_NAME, +) +from ray.serve._private.proxy import ProxyActor +from ray.serve._private.utils import ( + Timer, + TimerBase, + format_actor_name, + is_grpc_enabled, +) +from ray.serve.config import DeploymentMode, HTTPOptions, gRPCOptions +from ray.serve.schema import ( + LoggingConfig, + ProxyDetails, + ProxyStatus, + Target, +) +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class ProxyWrapper(ABC): + @property + @abstractmethod + def actor_id(self) -> str: + """Return the actor id of the proxy actor.""" + raise NotImplementedError + + @abstractmethod + def is_ready(self, timeout_s: float) -> Optional[bool]: + """Return whether proxy is ready to be serving requests. + + Since actual readiness check is asynchronous, this method could return + any of the following statuses: + - None: Readiness check is pending + - True: Readiness check completed successfully (proxy is ready) + - False: Readiness check completed with failure (either timing out + or failing) + """ + raise NotImplementedError + + @abstractmethod + def is_healthy(self, timeout_s: float) -> Optional[bool]: + """Return whether the proxy actor is healthy. + + Since actual health-check is asynchronous, this method could return + either of the following statuses: + - None: Health-check is pending + - True: Health-check completed successfully (proxy is healthy) + - False: Health-check completed with failure (either timing out or failing) + """ + raise NotImplementedError + + @abstractmethod + def is_drained(self, timeout_s: float) -> Optional[bool]: + """Return whether the proxy actor is drained. + + Since actual check whether proxy is drained is asynchronous, this method could + return either of the following statuses: + - None: Drain-check is pending + - True: Drain-check completed, node *is drained* + - False: Drain-check completed, node is *NOT* drained + """ + raise NotImplementedError + + @abstractmethod + def is_shutdown(self): + """Return whether the proxy actor is shutdown.""" + raise NotImplementedError + + @abstractmethod + def update_draining(self, draining: bool): + """Update the draining status of the proxy actor.""" + raise NotImplementedError + + @abstractmethod + def kill(self): + """Kill the proxy actor.""" + raise NotImplementedError + + +class ActorProxyWrapper(ProxyWrapper): + def __init__( + self, + logging_config: LoggingConfig, + actor_handle: Optional[ActorHandle] = None, + http_options: Optional[HTTPOptions] = None, + grpc_options: Optional[gRPCOptions] = None, + name: Optional[str] = None, + node_id: Optional[str] = None, + node_ip_address: Optional[str] = None, + port: Optional[int] = None, + proxy_actor_class: Type[ProxyActor] = ProxyActor, + ): + # initialize with provided proxy actor handle or get or create a new one. + self._actor_handle = actor_handle or self._get_or_create_proxy_actor( + http_options=http_options, + grpc_options=grpc_options, + name=name, + node_id=node_id, + node_ip_address=node_ip_address, + port=port, + proxy_actor_class=proxy_actor_class, + logging_config=logging_config, + ) + self._ready_check_future = None + self._health_check_future = None + self._drained_check_future = None + + self._update_draining_obj_ref = None + + self._node_id = node_id + + self.worker_id = None + self.log_file_path = None + + @staticmethod + def _get_or_create_proxy_actor( + http_options: HTTPOptions, + grpc_options: gRPCOptions, + name: str, + node_id: str, + node_ip_address: str, + port: int, + logging_config: LoggingConfig, + proxy_actor_class: Type[ProxyActor] = ProxyActor, + ) -> ProxyWrapper: + """Helper to start or reuse existing proxy. + + Takes the name of the proxy, the node id, and the node ip address, and look up + or creates a new ProxyActor actor handle for the proxy. + """ + proxy = None + try: + proxy = ray.get_actor(name, namespace=SERVE_NAMESPACE) + except ValueError: + addr = build_address(http_options.host, http_options.port) + logger.info( + f"Starting proxy on node '{node_id}' listening on '{addr}'.", + extra={"log_to_stderr": False}, + ) + + return proxy or proxy_actor_class.options( + num_cpus=http_options.num_cpus, + name=name, + namespace=SERVE_NAMESPACE, + lifetime="detached", + max_concurrency=ASYNC_CONCURRENCY, + max_restarts=0, + scheduling_strategy=NodeAffinitySchedulingStrategy(node_id, soft=False), + enable_task_events=RAY_SERVE_ENABLE_TASK_EVENTS, + ).remote( + http_options, + grpc_options=grpc_options, + node_id=node_id, + node_ip_address=node_ip_address, + logging_config=logging_config, + ) + + @property + def actor_id(self) -> str: + """Return the actor id of the proxy actor.""" + return self._actor_handle._actor_id.hex() + + @property + def actor_handle(self) -> ActorHandle: + """Return the actor handle of the proxy actor. + + This is used in _start_controller() in _private/controller.py to check whether + the proxies exist. It is also used in some tests to access proxy's actor handle. + """ + return self._actor_handle + + def is_ready(self, timeout_s: float) -> Optional[bool]: + if self._ready_check_future is None: + self._ready_check_future = wrap_as_future( + self._actor_handle.ready.remote(), timeout_s=timeout_s + ) + + if not self._ready_check_future.done(): + return None + + try: + worker_id, log_file_path = json.loads(self._ready_check_future.result()) + self.worker_id = worker_id + self.log_file_path = log_file_path + return True + except TimeoutError: + logger.warning( + f"Proxy actor readiness check for proxy on {self._node_id}" + f" didn't complete in {timeout_s}s." + ) + except Exception: + logger.exception( + f"Unexpected error invoking readiness check for proxy" + f" on {self._node_id}", + ) + finally: + self._ready_check_future = None + + return False + + def is_healthy(self, timeout_s: float) -> Optional[bool]: + if self._health_check_future is None: + self._health_check_future = wrap_as_future( + self._actor_handle.check_health.remote(), timeout_s=timeout_s + ) + + if not self._health_check_future.done(): + return None + + try: + # NOTE: Since `check_health` method is responding with nothing, sole + # purpose of fetching the result is to extract any potential + # exceptions + self._health_check_future.result() + return True + except TimeoutError: + logger.warning( + f"Didn't receive health check response for proxy" + f" on {self._node_id} after {timeout_s}s." + ) + except Exception: + logger.exception( + f"Unexpected error invoking health check for proxy " + f"on {self._node_id}", + ) + finally: + self._health_check_future = None + + return False + + def is_drained(self, timeout_s: float) -> Optional[bool]: + if self._drained_check_future is None: + self._drained_check_future = wrap_as_future( + self._actor_handle.is_drained.remote(), + timeout_s=timeout_s, + ) + + if not self._drained_check_future.done(): + return None + + try: + is_drained = self._drained_check_future.result() + return is_drained + except TimeoutError: + logger.warning( + f"Didn't receive drain check response for proxy" + f" on {self._node_id} after {timeout_s}s." + ) + except Exception: + logger.exception( + f"Unexpected error invoking drain-check for proxy " + f"on {self._node_id}", + ) + finally: + self._drained_check_future = None + + return False + + def is_shutdown(self) -> bool: + """Return whether the proxy actor is shutdown. + + If the actor is dead, the health check will return RayActorError. + """ + try: + ray.get(self._actor_handle.check_health.remote(), timeout=0) + except RayActorError: + # The actor is dead, so it's ready for shutdown. + return True + except GetTimeoutError: + pass + + # The actor is still alive, so it's not ready for shutdown. + return False + + def update_draining(self, draining: bool): + """Update the draining status of the proxy actor.""" + # NOTE: All update_draining calls are implicitly serialized, by specifying + # `ObjectRef` of the previous call + self._update_draining_obj_ref = self._actor_handle.update_draining.remote( + draining, _after=self._update_draining_obj_ref + ) + # In case of cancelled draining, make sure pending draining check is cancelled + # as well + if not draining: + future = self._drained_check_future + self._drained_check_future = None + if future: + future.cancel() + + def kill(self): + """Kill the proxy actor.""" + ray.kill(self._actor_handle, no_restart=True) + + +class ProxyState: + def __init__( + self, + actor_proxy_wrapper: ProxyWrapper, + actor_name: str, + node_id: str, + node_ip: str, + node_instance_id: str, + proxy_restart_count: int = 0, + timer: TimerBase = Timer(), + ): + self._actor_proxy_wrapper = actor_proxy_wrapper + self._actor_name = actor_name + self._node_id = node_id + self._status = ProxyStatus.STARTING + self._timer = timer + self._shutting_down = False + self._consecutive_health_check_failures: int = 0 + self._proxy_restart_count = proxy_restart_count + self._last_health_check_time: Optional[float] = None + self._last_drain_check_time: Optional[float] = None + + self._actor_details = ProxyDetails( + node_id=node_id, + node_ip=node_ip, + node_instance_id=node_instance_id, + actor_id=self._actor_proxy_wrapper.actor_id, + actor_name=self._actor_name, + status=self._status, + ) + + @property + def actor_handle(self) -> ActorHandle: + return self._actor_proxy_wrapper.actor_handle + + @property + def actor_name(self) -> str: + return self._actor_name + + @property + def actor_id(self) -> str: + return self._actor_proxy_wrapper.actor_id + + @property + def status(self) -> ProxyStatus: + return self._status + + @property + def actor_details(self) -> ProxyDetails: + return self._actor_details + + @property + def proxy_restart_count(self) -> int: + return self._proxy_restart_count + + def _set_status(self, status: ProxyStatus) -> None: + """Sets _status and updates _actor_details with the new status. + + NOTE: This method should not be used directly, instead please + use `try_update_status` method + """ + self._status = status + self.update_actor_details(status=self._status) + + def try_update_status(self, status: ProxyStatus): + """Try update with the new status and only update when the conditions are met. + + Status will only set to UNHEALTHY after PROXY_HEALTH_CHECK_UNHEALTHY_THRESHOLD + consecutive failures. A warning will be logged when the status is set to + UNHEALTHY. Also, when status is set to HEALTHY, we will reset + self._consecutive_health_check_failures to 0. + """ + + if status == ProxyStatus.UNHEALTHY: + self._consecutive_health_check_failures += 1 + # Early return to skip setting UNHEALTHY status if there are still room for + # retry. + if ( + self._consecutive_health_check_failures + < PROXY_HEALTH_CHECK_UNHEALTHY_THRESHOLD + ): + return + else: + # If all retries have been exhausted and setting the status to + # UNHEALTHY, log a warning message to the user. + logger.warning( + f"Proxy {self._actor_name} failed the health check " + f"{self._consecutive_health_check_failures} times in a row, marking" + f" it unhealthy." + ) + else: + # Reset self._consecutive_health_check_failures when status is not + # UNHEALTHY + self._consecutive_health_check_failures = 0 + + self._set_status(status=status) + + def update_actor_details(self, **kwargs) -> None: + """Updates _actor_details with passed in kwargs.""" + details_kwargs = self._actor_details.dict() + details_kwargs.update(kwargs) + self._actor_details = ProxyDetails(**details_kwargs) + + def reconcile(self, draining: bool = False): + try: + self._reconcile_internal(draining) + except Exception as e: + self.try_update_status(ProxyStatus.UNHEALTHY) + logger.error( + "Unexpected error occurred when reconciling stae of " + f"proxy on node {self._node_id}", + exc_info=e, + ) + + def _reconcile_internal(self, draining: bool): + """Update the status of the current proxy. + + The state machine is: + STARTING -> HEALTHY or UNHEALTHY + HEALTHY -> DRAINING or UNHEALTHY + DRAINING -> HEALTHY or UNHEALTHY or DRAINED + + UNHEALTHY is a terminal state upon reaching which, Proxy is going to be + restarted by the controller + """ + if ( + self._shutting_down + or self._status == ProxyStatus.DRAINED + or self._status == ProxyStatus.UNHEALTHY + ): + return + + # Doing a linear backoff for the ready check timeout. + ready_check_timeout = ( + self.proxy_restart_count + 1 + ) * PROXY_READY_CHECK_TIMEOUT_S + + if self._status == ProxyStatus.STARTING: + is_ready_response = self._actor_proxy_wrapper.is_ready(ready_check_timeout) + if is_ready_response is not None: + if is_ready_response: + self.try_update_status(ProxyStatus.HEALTHY) + self.update_actor_details( + worker_id=self._actor_proxy_wrapper.worker_id, + log_file_path=self._actor_proxy_wrapper.log_file_path, + status=self._status, + ) + else: + self.try_update_status(ProxyStatus.UNHEALTHY) + logger.warning( + f"Proxy actor reported not ready on node {self._node_id}" + ) + else: + # At this point, the proxy is either in HEALTHY or DRAINING status. + assert self._status in {ProxyStatus.HEALTHY, ProxyStatus.DRAINING} + + should_check_health = self._last_health_check_time is None or ( + self._timer.time() - self._last_health_check_time + >= PROXY_HEALTH_CHECK_PERIOD_S + ) + # Perform health-check for proxy's actor (if necessary) + if should_check_health: + is_healthy_response = self._actor_proxy_wrapper.is_healthy( + PROXY_HEALTH_CHECK_TIMEOUT_S + ) + if is_healthy_response is not None: + if is_healthy_response: + # At this stage status is either HEALTHY or DRAINING, and here + # we simply reset the status + self.try_update_status(self._status) + else: + self.try_update_status(ProxyStatus.UNHEALTHY) + + self._last_health_check_time = self._timer.time() + + # Handle state transitions (if necessary) + if self._status == ProxyStatus.UNHEALTHY: + return + elif self._status == ProxyStatus.HEALTHY: + if draining: + logger.info(f"Draining proxy on node '{self._node_id}'.") + assert self._last_drain_check_time is None + + self._actor_proxy_wrapper.update_draining(draining=True) + self.try_update_status(ProxyStatus.DRAINING) + elif self._status == ProxyStatus.DRAINING: + if not draining: + logger.info(f"No longer draining proxy on node '{self._node_id}'.") + self._last_drain_check_time = None + + self._actor_proxy_wrapper.update_draining(draining=False) + self.try_update_status(ProxyStatus.HEALTHY) + else: + should_check_drain = self._last_drain_check_time is None or ( + self._timer.time() - self._last_drain_check_time + >= PROXY_DRAIN_CHECK_PERIOD_S + ) + if should_check_drain: + # NOTE: We use the same timeout as for readiness checking + is_drained_response = self._actor_proxy_wrapper.is_drained( + PROXY_READY_CHECK_TIMEOUT_S + ) + if is_drained_response is not None: + if is_drained_response: + self.try_update_status(ProxyStatus.DRAINED) + + self._last_drain_check_time = self._timer.time() + + def shutdown(self): + self._shutting_down = True + self._actor_proxy_wrapper.kill() + + def is_ready_for_shutdown(self) -> bool: + """Return whether the proxy actor is shutdown. + + For a proxy actor to be considered shutdown, it must be marked as + _shutting_down and the actor must be shut down. + """ + if not self._shutting_down: + return False + + return self._actor_proxy_wrapper.is_shutdown() + + +class ProxyStateManager: + """Manages all state for proxies in the system. + + This class is *not* thread safe, so any state-modifying methods should be + called with a lock held. + """ + + def __init__( + self, + http_options: HTTPOptions, + head_node_id: str, + cluster_node_info_cache: ClusterNodeInfoCache, + logging_config: LoggingConfig, + grpc_options: Optional[gRPCOptions] = None, + proxy_actor_class: Type[ProxyActor] = ProxyActor, + actor_proxy_wrapper_class: Type[ProxyWrapper] = ActorProxyWrapper, + timer: TimerBase = Timer(), + ): + self.logging_config = logging_config + self._http_options = http_options or HTTPOptions() + self._grpc_options = grpc_options or gRPCOptions() + self._proxy_states: Dict[NodeId, ProxyState] = dict() + self._proxy_restart_counts: Dict[NodeId, int] = dict() + self._head_node_id: str = head_node_id + self._proxy_actor_class = proxy_actor_class + self._actor_proxy_wrapper_class = actor_proxy_wrapper_class + self._timer = timer + + self._cluster_node_info_cache = cluster_node_info_cache + + assert isinstance(head_node_id, str) + + def reconfigure_logging_config(self, logging_config: LoggingConfig): + self.logging_config = logging_config + + def shutdown(self) -> None: + for proxy_state in self._proxy_states.values(): + proxy_state.shutdown() + + def is_ready_for_shutdown(self) -> bool: + """Return whether all proxies are shutdown. + + Iterate through all proxy states and check if all their proxy actors + are shutdown. + """ + return all( + proxy_state.is_ready_for_shutdown() + for proxy_state in self._proxy_states.values() + ) + + def get_config(self) -> HTTPOptions: + return self._http_options + + def get_grpc_config(self) -> gRPCOptions: + return self._grpc_options + + def get_proxy_handles(self) -> Dict[NodeId, ActorHandle]: + return { + node_id: state.actor_handle for node_id, state in self._proxy_states.items() + } + + def get_proxy_names(self) -> Dict[NodeId, str]: + return { + node_id: state.actor_name for node_id, state in self._proxy_states.items() + } + + def get_proxy_details(self) -> Dict[NodeId, ProxyDetails]: + return { + node_id: state.actor_details + for node_id, state in self._proxy_states.items() + } + + def get_targets(self, protocol: RequestProtocol) -> List[Target]: + """In Ray Serve, every proxy is responsible for routing requests to the + correct application. Here we curate a list of targets for the given protocol. + Where each target represents how to reach a proxy. + + Args: + protocol: Either "http" or "grpc" + """ + targets = [] + if protocol == RequestProtocol.HTTP: + port = self._http_options.port + elif protocol == RequestProtocol.GRPC: + if not is_grpc_enabled(self._grpc_options): + return [] + port = self._grpc_options.port + else: + raise ValueError(f"Invalid protocol: {protocol}") + + targets = [ + Target( + ip=state.actor_details.node_ip, + port=port, + instance_id=state.actor_details.node_instance_id, + ) + for _, state in self._proxy_states.items() + if state.actor_details.status == ProxyStatus.HEALTHY + ] + return targets + + def get_alive_proxy_actor_ids(self) -> Set[str]: + return {state.actor_id for state in self._proxy_states.values()} + + def update(self, proxy_nodes: Set[NodeId] = None) -> Set[str]: + """Update the state of all proxies. + + Start proxies on all nodes if not already exist and stop the proxies on nodes + that are no longer exist. Update all proxy states. Kill and restart + unhealthy proxies. + """ + if proxy_nodes is None: + proxy_nodes = set() + + # Ensure head node always has a proxy (unless FF'd off). + if RAY_SERVE_ALWAYS_RUN_PROXY_ON_HEAD_NODE: + proxy_nodes.add(self._head_node_id) + + target_nodes = self._get_target_nodes(proxy_nodes) + target_node_ids = {node_id for node_id, _, _ in target_nodes} + + for node_id, proxy_state in self._proxy_states.items(): + draining = node_id not in target_node_ids + proxy_state.reconcile(draining) + + self._stop_proxies_if_needed() + self._start_proxies_if_needed(target_nodes) + + def _get_target_nodes(self, proxy_nodes) -> List[Tuple[str, str, str]]: + """Return the list of (node_id, ip_address) to deploy HTTP and gRPC servers + on.""" + location = self._http_options.location + + if location == DeploymentMode.NoServer: + return [] + + target_nodes = [ + (node_id, ip_address, instance_id) + for node_id, ip_address, instance_id in self._cluster_node_info_cache.get_alive_nodes() + if node_id in proxy_nodes + ] + + if location == DeploymentMode.HeadOnly: + nodes = [ + (node_id, ip_address, instance_id) + for node_id, ip_address, instance_id in target_nodes + if node_id == self._head_node_id + ] + assert len(nodes) == 1, ( + f"Head node not found! Head node id: {self._head_node_id}, " + f"all nodes: {target_nodes}." + ) + return nodes + + return target_nodes + + def _generate_actor_name(self, node_id: str) -> str: + return format_actor_name(SERVE_PROXY_NAME, node_id) + + def _start_proxy( + self, + name: str, + node_id: str, + node_ip_address: str, + ) -> ProxyWrapper: + """Helper to start or reuse existing proxy and wrap in the proxy actor wrapper. + + Compute the HTTP port based on `TEST_WORKER_NODE_HTTP_PORT` env var and gRPC + port based on `TEST_WORKER_NODE_GRPC_PORT` env var. Passed all the required + variables into the proxy actor wrapper class and return the proxy actor wrapper. + """ + http_options = self._http_options + grpc_options = self._grpc_options + + if ( + node_id != self._head_node_id + and os.getenv("TEST_WORKER_NODE_HTTP_PORT") is not None + ): + logger.warning( + f"`TEST_WORKER_NODE_HTTP_PORT` env var is set. " + f"Using it for worker node {node_id}." + ) + http_options = deepcopy(http_options) + http_options.port = int(os.getenv("TEST_WORKER_NODE_HTTP_PORT")) + + if ( + node_id != self._head_node_id + and os.getenv("TEST_WORKER_NODE_GRPC_PORT") is not None + ): + logger.warning( + f"`TEST_WORKER_NODE_GRPC_PORT` env var is set. " + f"Using it for worker node {node_id}." + f"{int(os.getenv('TEST_WORKER_NODE_GRPC_PORT'))}" + ) + grpc_options = deepcopy(grpc_options) + grpc_options.port = int(os.getenv("TEST_WORKER_NODE_GRPC_PORT")) + + return self._actor_proxy_wrapper_class( + logging_config=self.logging_config, + http_options=http_options, + grpc_options=grpc_options, + name=name, + node_id=node_id, + node_ip_address=node_ip_address, + proxy_actor_class=self._proxy_actor_class, + ) + + def _start_proxies_if_needed(self, target_nodes) -> None: + """Start a proxy on every node if it doesn't already exist.""" + + for node_id, node_ip_address, node_instance_id in target_nodes: + if node_id in self._proxy_states: + continue + + name = self._generate_actor_name(node_id=node_id) + actor_proxy_wrapper = self._start_proxy( + name=name, + node_id=node_id, + node_ip_address=node_ip_address, + ) + + self._proxy_states[node_id] = ProxyState( + actor_proxy_wrapper=actor_proxy_wrapper, + actor_name=name, + node_id=node_id, + node_ip=node_ip_address, + node_instance_id=node_instance_id, + proxy_restart_count=self._proxy_restart_counts.get(node_id, 0), + timer=self._timer, + ) + + def _stop_proxies_if_needed(self) -> bool: + """Removes proxy actors. + + Removes proxy actors from any nodes that no longer exist or unhealthy proxy. + """ + alive_node_ids = self._cluster_node_info_cache.get_alive_node_ids() + to_stop = [] + for node_id, proxy_state in self._proxy_states.items(): + if node_id not in alive_node_ids: + logger.info(f"Removing proxy on removed node '{node_id}'.") + to_stop.append(node_id) + elif proxy_state.status == ProxyStatus.UNHEALTHY: + logger.info( + f"Proxy on node '{node_id}' is unhealthy. Shutting down " + "the unhealthy proxy and starting a new one." + ) + to_stop.append(node_id) + elif proxy_state.status == ProxyStatus.DRAINED: + logger.info(f"Removing drained proxy on node '{node_id}'.") + to_stop.append(node_id) + + for node_id in to_stop: + proxy_state = self._proxy_states.pop(node_id) + self._proxy_restart_counts[node_id] = proxy_state.proxy_restart_count + 1 + proxy_state.shutdown() + + +def _try_set_exception(fut: asyncio.Future, e: Exception): + if not fut.done(): + fut.set_exception(e) + + +def wrap_as_future(ref: ObjectRef, timeout_s: Optional[float] = None) -> asyncio.Future: + loop = asyncio.get_running_loop() + + aio_fut = asyncio.wrap_future(ref.future()) + + if timeout_s is not None: + assert timeout_s >= 0, "Timeout value should be non-negative" + # Schedule handler to complete future exceptionally + timeout_handler = loop.call_later( + max(timeout_s, 0), + _try_set_exception, + aio_fut, + TimeoutError(f"Future cancelled after timeout {timeout_s}s"), + ) + # Cancel timeout handler upon completion of the future + aio_fut.add_done_callback(lambda _: timeout_handler.cancel()) + + return aio_fut diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/replica.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/replica.py new file mode 100644 index 0000000000000000000000000000000000000000..5ce22606f4b9e20a4d4c94868f5c6a42692cb17c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/replica.py @@ -0,0 +1,1926 @@ +import asyncio +import concurrent.futures +import functools +import inspect +import logging +import os +import pickle +import threading +import time +import traceback +import warnings +from abc import ABC, abstractmethod +from collections import defaultdict, deque +from contextlib import asynccontextmanager, contextmanager +from dataclasses import dataclass +from importlib import import_module +from typing import ( + Any, + AsyncGenerator, + Callable, + Dict, + Generator, + Optional, + Tuple, + Union, +) + +import starlette.responses +from anyio import to_thread +from fastapi import Request +from starlette.applications import Starlette +from starlette.types import ASGIApp, Receive, Scope, Send + +import ray +from ray import cloudpickle +from ray._common.utils import get_or_create_event_loop +from ray._private.ray_logging.filters import CoreContextFilter +from ray.actor import ActorClass, ActorHandle +from ray.remote_function import RemoteFunction +from ray.serve import metrics +from ray.serve._private.common import ( + DeploymentID, + ReplicaID, + ReplicaQueueLengthInfo, + RequestMetadata, + ServeComponentType, + StreamingHTTPRequest, + gRPCRequest, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + GRPC_CONTEXT_ARG_NAME, + HEALTH_CHECK_METHOD, + RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE, + RAY_SERVE_METRICS_EXPORT_INTERVAL_MS, + RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_INTERVAL_S, + RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE, + RAY_SERVE_RUN_SYNC_IN_THREADPOOL, + RAY_SERVE_RUN_SYNC_IN_THREADPOOL_WARNING, + RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD, + RECONFIGURE_METHOD, + REQUEST_LATENCY_BUCKETS_MS, + REQUEST_ROUTING_STATS_METHOD, + SERVE_CONTROLLER_NAME, + SERVE_LOG_APPLICATION, + SERVE_LOG_COMPONENT, + SERVE_LOG_DEPLOYMENT, + SERVE_LOG_REPLICA, + SERVE_LOG_REQUEST_ID, + SERVE_LOG_ROUTE, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.default_impl import ( + create_replica_impl, + create_replica_metrics_manager, +) +from ray.serve._private.http_util import ( + ASGIAppReplicaWrapper, + ASGIArgs, + ASGIReceiveProxy, + MessageQueue, + Response, +) +from ray.serve._private.logging_utils import ( + access_log_msg, + configure_component_logger, + configure_component_memory_profiler, + get_component_logger_file_path, +) +from ray.serve._private.metrics_utils import InMemoryMetricsStore, MetricsPusher +from ray.serve._private.thirdparty.get_asgi_route_name import get_asgi_route_name +from ray.serve._private.utils import ( + Semaphore, + get_component_file_name, # noqa: F401 + parse_import_path, +) +from ray.serve._private.version import DeploymentVersion +from ray.serve.config import AutoscalingConfig +from ray.serve.context import _get_in_flight_requests +from ray.serve.deployment import Deployment +from ray.serve.exceptions import ( + BackPressureError, + DeploymentUnavailableError, + RayServeException, +) +from ray.serve.schema import EncodingType, LoggingConfig + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +ReplicaMetadata = Tuple[ + DeploymentConfig, + DeploymentVersion, + Optional[float], + Optional[int], + Optional[str], +] + + +def _load_deployment_def_from_import_path(import_path: str) -> Callable: + module_name, attr_name = parse_import_path(import_path) + deployment_def = getattr(import_module(module_name), attr_name) + + # For ray or serve decorated class or function, strip to return + # original body. + if isinstance(deployment_def, RemoteFunction): + deployment_def = deployment_def._function + elif isinstance(deployment_def, ActorClass): + deployment_def = deployment_def.__ray_metadata__.modified_class + elif isinstance(deployment_def, Deployment): + logger.warning( + f'The import path "{import_path}" contains a ' + "decorated Serve deployment. The decorator's settings " + "are ignored when deploying via import path." + ) + deployment_def = deployment_def.func_or_class + + return deployment_def + + +class ReplicaMetricsManager: + """Manages metrics for the replica. + + A variety of metrics are managed: + - Fine-grained metrics are set for every request. + - Autoscaling statistics are periodically pushed to the controller. + - Queue length metrics are periodically recorded as user-facing gauges. + """ + + PUSH_METRICS_TO_CONTROLLER_TASK_NAME = "push_metrics_to_controller" + RECORD_METRICS_TASK_NAME = "record_metrics" + SET_REPLICA_REQUEST_METRIC_GAUGE_TASK_NAME = "set_replica_request_metric_gauge" + + def __init__( + self, + replica_id: ReplicaID, + event_loop: asyncio.BaseEventLoop, + autoscaling_config: Optional[AutoscalingConfig], + ingress: bool, + ): + self._replica_id = replica_id + self._metrics_pusher = MetricsPusher() + self._metrics_store = InMemoryMetricsStore() + self._autoscaling_config = autoscaling_config + self._ingress = ingress + self._controller_handle = ray.get_actor( + SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE + ) + self._num_ongoing_requests = 0 + + # If the interval is set to 0, eagerly sets all metrics. + self._cached_metrics_enabled = RAY_SERVE_METRICS_EXPORT_INTERVAL_MS != 0 + self._cached_metrics_interval_s = RAY_SERVE_METRICS_EXPORT_INTERVAL_MS / 1000 + + # Request counter (only set on replica startup). + self._restart_counter = metrics.Counter( + "serve_deployment_replica_starts", + description=( + "The number of times this replica has been restarted due to failure." + ), + ) + self._restart_counter.inc() + + # Per-request metrics. + self._request_counter = metrics.Counter( + "serve_deployment_request_counter", + description=( + "The number of queries that have been processed in this replica." + ), + tag_keys=("route",), + ) + if self._cached_metrics_enabled: + self._cached_request_counter = defaultdict(int) + + self._error_counter = metrics.Counter( + "serve_deployment_error_counter", + description=( + "The number of exceptions that have occurred in this replica." + ), + tag_keys=("route",), + ) + if self._cached_metrics_enabled: + self._cached_error_counter = defaultdict(int) + + # log REQUEST_LATENCY_BUCKET_MS + logger.debug(f"REQUEST_LATENCY_BUCKETS_MS: {REQUEST_LATENCY_BUCKETS_MS}") + self._processing_latency_tracker = metrics.Histogram( + "serve_deployment_processing_latency_ms", + description="The latency for queries to be processed.", + boundaries=REQUEST_LATENCY_BUCKETS_MS, + tag_keys=("route",), + ) + if self._cached_metrics_enabled: + self._cached_latencies = defaultdict(deque) + + self._num_ongoing_requests_gauge = metrics.Gauge( + "serve_replica_processing_queries", + description="The current number of queries being processed.", + ) + + self.set_autoscaling_config(autoscaling_config) + + if self._cached_metrics_enabled: + event_loop.create_task(self._report_cached_metrics_forever()) + + def _report_cached_metrics(self): + for route, count in self._cached_request_counter.items(): + self._request_counter.inc(count, tags={"route": route}) + self._cached_request_counter.clear() + + for route, count in self._cached_error_counter.items(): + self._error_counter.inc(count, tags={"route": route}) + self._cached_error_counter.clear() + + for route, latencies in self._cached_latencies.items(): + for latency_ms in latencies: + self._processing_latency_tracker.observe( + latency_ms, tags={"route": route} + ) + self._cached_latencies.clear() + + self._num_ongoing_requests_gauge.set(self._num_ongoing_requests) + + async def _report_cached_metrics_forever(self): + assert self._cached_metrics_interval_s > 0 + + consecutive_errors = 0 + while True: + try: + await asyncio.sleep(self._cached_metrics_interval_s) + self._report_cached_metrics() + consecutive_errors = 0 + except Exception: + logger.exception("Unexpected error reporting metrics.") + + # Exponential backoff starting at 1s and capping at 10s. + backoff_time_s = min(10, 2**consecutive_errors) + consecutive_errors += 1 + await asyncio.sleep(backoff_time_s) + + async def shutdown(self): + """Stop periodic background tasks.""" + + await self._metrics_pusher.graceful_shutdown() + + def should_collect_metrics(self) -> bool: + return ( + not RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE + and self._autoscaling_config + ) + + def set_autoscaling_config(self, autoscaling_config: Optional[AutoscalingConfig]): + """Dynamically update autoscaling config.""" + + self._autoscaling_config = autoscaling_config + + if self.should_collect_metrics(): + self._metrics_pusher.start() + + # Push autoscaling metrics to the controller periodically. + self._metrics_pusher.register_or_update_task( + self.PUSH_METRICS_TO_CONTROLLER_TASK_NAME, + self._push_autoscaling_metrics, + self._autoscaling_config.metrics_interval_s, + ) + # Collect autoscaling metrics locally periodically. + self._metrics_pusher.register_or_update_task( + self.RECORD_METRICS_TASK_NAME, + self._add_autoscaling_metrics_point, + min( + RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_INTERVAL_S, + self._autoscaling_config.metrics_interval_s, + ), + ) + + def inc_num_ongoing_requests(self, request_metadata: RequestMetadata) -> int: + """Increment the current total queue length of requests for this replica.""" + self._num_ongoing_requests += 1 + if not self._cached_metrics_enabled: + self._num_ongoing_requests_gauge.set(self._num_ongoing_requests) + + def dec_num_ongoing_requests(self, request_metadata: RequestMetadata) -> int: + """Decrement the current total queue length of requests for this replica.""" + self._num_ongoing_requests -= 1 + if not self._cached_metrics_enabled: + self._num_ongoing_requests_gauge.set(self._num_ongoing_requests) + + def get_num_ongoing_requests(self) -> int: + """Get current total queue length of requests for this replica.""" + return self._num_ongoing_requests + + def record_request_metrics(self, *, route: str, latency_ms: float, was_error: bool): + """Records per-request metrics.""" + if self._cached_metrics_enabled: + self._cached_latencies[route].append(latency_ms) + if was_error: + self._cached_error_counter[route] += 1 + else: + self._cached_request_counter[route] += 1 + else: + self._processing_latency_tracker.observe(latency_ms, tags={"route": route}) + if was_error: + self._error_counter.inc(tags={"route": route}) + else: + self._request_counter.inc(tags={"route": route}) + + def _push_autoscaling_metrics(self) -> Dict[str, Any]: + look_back_period = self._autoscaling_config.look_back_period_s + self._controller_handle.record_autoscaling_metrics.remote( + replica_id=self._replica_id, + window_avg=self._metrics_store.window_average( + self._replica_id, time.time() - look_back_period + ), + send_timestamp=time.time(), + ) + + def _add_autoscaling_metrics_point(self) -> None: + self._metrics_store.add_metrics_point( + {self._replica_id: self._num_ongoing_requests}, + time.time(), + ) + + +StatusCodeCallback = Callable[[str], None] + + +class ReplicaBase(ABC): + def __init__( + self, + replica_id: ReplicaID, + deployment_def: Callable, + init_args: Tuple, + init_kwargs: Dict, + deployment_config: DeploymentConfig, + version: DeploymentVersion, + ingress: bool, + route_prefix: str, + ): + self._version = version + self._replica_id = replica_id + self._deployment_id = replica_id.deployment_id + self._deployment_config = deployment_config + self._ingress = ingress + self._route_prefix = route_prefix + self._component_name = f"{self._deployment_id.name}" + if self._deployment_id.app_name: + self._component_name = ( + f"{self._deployment_id.app_name}_" + self._component_name + ) + + self._component_id = self._replica_id.unique_id + self._configure_logger_and_profilers(self._deployment_config.logging_config) + self._event_loop = get_or_create_event_loop() + + self._user_callable_wrapper = UserCallableWrapper( + deployment_def, + init_args, + init_kwargs, + deployment_id=self._deployment_id, + run_sync_methods_in_threadpool=RAY_SERVE_RUN_SYNC_IN_THREADPOOL, + run_user_code_in_separate_thread=RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD, + local_testing_mode=False, + ) + self._semaphore = Semaphore(lambda: self.max_ongoing_requests) + + # Guards against calling the user's callable constructor multiple times. + self._user_callable_initialized = False + self._user_callable_initialized_lock = asyncio.Lock() + self._initialization_latency: Optional[float] = None + + # Flipped to `True` when health checks pass and `False` when they fail. May be + # used by replica subclass implementations. + self._healthy = False + # Flipped to `True` once graceful shutdown is initiated. May be used by replica + # subclass implementations. + self._shutting_down = False + + # Will be populated with the wrapped ASGI app if the user callable is an + # `ASGIAppReplicaWrapper` (i.e., they are using the FastAPI integration). + self._user_callable_asgi_app: Optional[ASGIApp] = None + + # Set metadata for logs and metrics. + # servable_object will be populated in `initialize_and_get_metadata`. + self._set_internal_replica_context(servable_object=None) + + self._metrics_manager = create_replica_metrics_manager( + replica_id=replica_id, + event_loop=self._event_loop, + autoscaling_config=self._deployment_config.autoscaling_config, + ingress=ingress, + ) + + self._port: Optional[int] = None + self._docs_path: Optional[str] = None + + @property + def max_ongoing_requests(self) -> int: + return self._deployment_config.max_ongoing_requests + + def get_num_ongoing_requests(self) -> int: + return self._metrics_manager.get_num_ongoing_requests() + + def get_metadata(self) -> ReplicaMetadata: + return ( + self._version.deployment_config, + self._version, + self._initialization_latency, + self._port, + self._docs_path, + ) + + def _set_internal_replica_context(self, *, servable_object: Callable = None): + ray.serve.context._set_internal_replica_context( + replica_id=self._replica_id, + servable_object=servable_object, + _deployment_config=self._deployment_config, + ) + + def _configure_logger_and_profilers( + self, logging_config: Union[None, Dict, LoggingConfig] + ): + + if logging_config is None: + logging_config = {} + if isinstance(logging_config, dict): + logging_config = LoggingConfig(**logging_config) + + configure_component_logger( + component_type=ServeComponentType.REPLICA, + component_name=self._component_name, + component_id=self._component_id, + logging_config=logging_config, + buffer_size=RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE, + ) + configure_component_memory_profiler( + component_type=ServeComponentType.REPLICA, + component_name=self._component_name, + component_id=self._component_id, + ) + + if logging_config.encoding == EncodingType.JSON: + # Create logging context for access logs as a performance optimization. + # While logging_utils can automatically add Ray core and Serve access log context, + # we pre-compute it here since context evaluation is expensive and this context + # will be reused for multiple access log entries. + ray_core_logging_context = CoreContextFilter.get_ray_core_logging_context() + # remove task level log keys from ray core logging context, it would be nice + # to have task level log keys here but we are letting those go in favor of + # performance optimization. Also we cannot include task level log keys here because + # they would referance the current task (__init__) and not the task that is logging. + for key in CoreContextFilter.TASK_LEVEL_LOG_KEYS: + ray_core_logging_context.pop(key, None) + self._access_log_context = { + **ray_core_logging_context, + SERVE_LOG_DEPLOYMENT: self._component_name, + SERVE_LOG_REPLICA: self._component_id, + SERVE_LOG_COMPONENT: ServeComponentType.REPLICA, + SERVE_LOG_APPLICATION: self._deployment_id.app_name, + "skip_context_filter": True, + "serve_access_log": True, + } + else: + self._access_log_context = { + "skip_context_filter": True, + "serve_access_log": True, + } + + def _can_accept_request(self, request_metadata: RequestMetadata) -> bool: + # This replica gates concurrent request handling with an asyncio.Semaphore. + # Each in-flight request acquires the semaphore. When the number of ongoing + # requests reaches max_ongoing_requests, the semaphore becomes locked. + # A new request can be accepted if the semaphore is currently unlocked. + return not self._semaphore.locked() + + def _maybe_get_http_route( + self, request_metadata: RequestMetadata, request_args: Tuple[Any] + ) -> Optional[str]: + """Get the matched route string for ASGI apps to be used in logs & metrics. + + If this replica does not wrap an ASGI app or there is no matching for the + request, returns the existing route from the request metadata. + """ + route = request_metadata.route + if self._user_callable_asgi_app is not None: + req: StreamingHTTPRequest = request_args[0] + try: + matched_route = get_asgi_route_name( + self._user_callable_asgi_app, req.asgi_scope + ) + except Exception: + matched_route = None + logger.exception( + "Failed unexpectedly trying to get route name for request. " + "Routes in metric tags and log messages may be inaccurate. " + "Please file a GitHub issue containing this traceback." + ) + + # If there is no match in the ASGI app, don't overwrite the route_prefix + # from the proxy. + if matched_route is not None: + route = matched_route + + return route + + @contextmanager + def _handle_errors_and_metrics( + self, request_metadata: RequestMetadata + ) -> Generator[StatusCodeCallback, None, None]: + start_time = time.time() + user_exception = None + + status_code = None + + def _status_code_callback(s: str): + nonlocal status_code + status_code = s + + try: + yield _status_code_callback + except asyncio.CancelledError as e: + user_exception = e + self._on_request_cancelled(request_metadata, e) + except Exception as e: + user_exception = e + logger.exception("Request failed.") + self._on_request_failed(request_metadata, e) + + latency_ms = (time.time() - start_time) * 1000 + self._record_errors_and_metrics( + user_exception, status_code, latency_ms, request_metadata + ) + + if user_exception is not None: + raise user_exception from None + + def _record_errors_and_metrics( + self, + user_exception: Optional[BaseException], + status_code: Optional[str], + latency_ms: float, + request_metadata: RequestMetadata, + ): + http_method = request_metadata._http_method + http_route = request_metadata.route + call_method = request_metadata.call_method + if user_exception is None: + status_str = "OK" + elif isinstance(user_exception, asyncio.CancelledError): + status_str = "CANCELLED" + else: + status_str = "ERROR" + + # Mutating self._access_log_context is not thread safe, but since this + # is only called from the same thread, it is safe. Mutating the same object + # because creating a new dict is expensive. + self._access_log_context[SERVE_LOG_ROUTE] = http_route + self._access_log_context[SERVE_LOG_REQUEST_ID] = request_metadata.request_id + logger.info( + access_log_msg( + method=http_method or "CALL", + route=http_route or call_method, + # Prefer the HTTP status code if it was populated. + status=status_code or status_str, + latency_ms=latency_ms, + ), + extra=self._access_log_context, + ) + self._metrics_manager.record_request_metrics( + route=http_route, + latency_ms=latency_ms, + was_error=user_exception is not None, + ) + + def _unpack_proxy_args( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + ): + if request_metadata.is_http_request: + assert len(request_args) == 1 and isinstance( + request_args[0], StreamingHTTPRequest + ) + request: StreamingHTTPRequest = request_args[0] + scope = request.asgi_scope + receive = ASGIReceiveProxy( + scope, request_metadata, request.receive_asgi_messages + ) + + request_metadata._http_method = scope.get("method", "WS") + request_metadata.route = self._maybe_get_http_route( + request_metadata, request_args + ) + + request_args = (scope, receive) + elif request_metadata.is_grpc_request: + assert len(request_args) == 1 and isinstance(request_args[0], gRPCRequest) + request: gRPCRequest = request_args[0] + + method_info = self._user_callable_wrapper.get_user_method_info( + request_metadata.call_method + ) + request_args = (request.user_request_proto,) + request_kwargs = ( + {GRPC_CONTEXT_ARG_NAME: request_metadata.grpc_context} + if method_info.takes_grpc_context_kwarg + else {} + ) + + return request_args, request_kwargs + + async def handle_request( + self, request_metadata: RequestMetadata, *request_args, **request_kwargs + ) -> Tuple[bytes, Any]: + request_args, request_kwargs = self._unpack_proxy_args( + request_metadata, request_args, request_kwargs + ) + with self._wrap_request(request_metadata): + async with self._start_request(request_metadata): + return await self._user_callable_wrapper.call_user_method( + request_metadata, request_args, request_kwargs + ) + + async def handle_request_streaming( + self, request_metadata: RequestMetadata, *request_args, **request_kwargs + ) -> AsyncGenerator[Any, None]: + """Generator that is the entrypoint for all `stream=True` handle calls.""" + request_args, request_kwargs = self._unpack_proxy_args( + request_metadata, request_args, request_kwargs + ) + with self._wrap_request(request_metadata) as status_code_callback: + async with self._start_request(request_metadata): + if request_metadata.is_http_request: + scope, receive = request_args + async for msgs in self._user_callable_wrapper.call_http_entrypoint( + request_metadata, + status_code_callback, + scope, + receive, + ): + yield pickle.dumps(msgs) + else: + async for result in self._user_callable_wrapper.call_user_generator( + request_metadata, + request_args, + request_kwargs, + ): + yield result + + async def handle_request_with_rejection( + self, request_metadata: RequestMetadata, *request_args, **request_kwargs + ): + # Check if the replica has capacity for the request. + if not self._can_accept_request(request_metadata): + limit = self.max_ongoing_requests + logger.warning( + f"Replica at capacity of max_ongoing_requests={limit}, " + f"rejecting request {request_metadata.request_id}.", + extra={"log_to_stderr": False}, + ) + yield ReplicaQueueLengthInfo(False, self.get_num_ongoing_requests()) + return + + request_args, request_kwargs = self._unpack_proxy_args( + request_metadata, request_args, request_kwargs + ) + with self._wrap_request(request_metadata) as status_code_callback: + async with self._start_request(request_metadata): + yield ReplicaQueueLengthInfo( + accepted=True, + # NOTE(edoakes): `_wrap_request` will increment the number + # of ongoing requests to include this one, so re-fetch the value. + num_ongoing_requests=self.get_num_ongoing_requests(), + ) + + if request_metadata.is_http_request: + scope, receive = request_args + async for msgs in self._user_callable_wrapper.call_http_entrypoint( + request_metadata, + status_code_callback, + scope, + receive, + ): + yield pickle.dumps(msgs) + elif request_metadata.is_streaming: + async for result in self._user_callable_wrapper.call_user_generator( + request_metadata, + request_args, + request_kwargs, + ): + yield result + else: + yield await self._user_callable_wrapper.call_user_method( + request_metadata, request_args, request_kwargs + ) + + @abstractmethod + async def _on_initialized(self): + raise NotImplementedError + + async def initialize(self, deployment_config: DeploymentConfig): + try: + # Ensure that initialization is only performed once. + # When controller restarts, it will call this method again. + async with self._user_callable_initialized_lock: + self._initialization_start_time = time.time() + if not self._user_callable_initialized: + self._user_callable_asgi_app = ( + await self._user_callable_wrapper.initialize_callable() + ) + if self._user_callable_asgi_app: + self._docs_path = ( + self._user_callable_wrapper._callable.docs_path + ) + await self._on_initialized() + self._user_callable_initialized = True + + if deployment_config: + await self._user_callable_wrapper.set_sync_method_threadpool_limit( + deployment_config.max_ongoing_requests + ) + await self._user_callable_wrapper.call_reconfigure( + deployment_config.user_config + ) + + # A new replica should not be considered healthy until it passes + # an initial health check. If an initial health check fails, + # consider it an initialization failure. + await self.check_health() + except Exception: + raise RuntimeError(traceback.format_exc()) from None + + async def reconfigure( + self, deployment_config: DeploymentConfig, route_prefix: Optional[str] = None + ): + try: + user_config_changed = ( + deployment_config.user_config != self._deployment_config.user_config + ) + logging_config_changed = ( + deployment_config.logging_config + != self._deployment_config.logging_config + ) + self._deployment_config = deployment_config + self._version = DeploymentVersion.from_deployment_version( + self._version, deployment_config, route_prefix + ) + + self._metrics_manager.set_autoscaling_config( + deployment_config.autoscaling_config + ) + if logging_config_changed: + self._configure_logger_and_profilers(deployment_config.logging_config) + + await self._user_callable_wrapper.set_sync_method_threadpool_limit( + deployment_config.max_ongoing_requests + ) + if user_config_changed: + await self._user_callable_wrapper.call_reconfigure( + deployment_config.user_config + ) + + # We need to update internal replica context to reflect the new + # deployment_config. + self._set_internal_replica_context( + servable_object=self._user_callable_wrapper.user_callable + ) + + self._route_prefix = self._version.route_prefix + + except Exception: + raise RuntimeError(traceback.format_exc()) from None + + @abstractmethod + def _on_request_cancelled( + self, request_metadata: RequestMetadata, e: asyncio.CancelledError + ): + pass + + @abstractmethod + def _on_request_failed(self, request_metadata: RequestMetadata, e: Exception): + pass + + @abstractmethod + @contextmanager + def _wrap_request( + self, request_metadata: RequestMetadata + ) -> Generator[StatusCodeCallback, None, None]: + pass + + @asynccontextmanager + async def _start_request(self, request_metadata: RequestMetadata): + async with self._semaphore: + try: + self._metrics_manager.inc_num_ongoing_requests(request_metadata) + yield + finally: + self._metrics_manager.dec_num_ongoing_requests(request_metadata) + + async def _drain_ongoing_requests(self): + """Wait for any ongoing requests to finish. + + Sleep for a grace period before the first time we check the number of ongoing + requests to allow the notification to remove this replica to propagate to + callers first. + """ + wait_loop_period_s = self._deployment_config.graceful_shutdown_wait_loop_s + while True: + await asyncio.sleep(wait_loop_period_s) + + num_ongoing_requests = self._metrics_manager.get_num_ongoing_requests() + if num_ongoing_requests > 0: + logger.info( + f"Waiting for an additional {wait_loop_period_s}s to shut down " + f"because there are {num_ongoing_requests} ongoing requests." + ) + else: + logger.info( + "Graceful shutdown complete; replica exiting.", + extra={"log_to_stderr": False}, + ) + break + + async def shutdown(self): + try: + await self._user_callable_wrapper.call_destructor() + except: # noqa: E722 + # We catch a blanket exception since the constructor may still be + # running, so instance variables used by the destructor may not exist. + if self._user_callable_initialized: + logger.exception( + "__del__ ran before replica finished initializing, and " + "raised an exception." + ) + else: + logger.exception("__del__ raised an exception.") + + await self._metrics_manager.shutdown() + + async def perform_graceful_shutdown(self): + self._shutting_down = True + + # If the replica was never initialized it never served traffic, so we + # can skip the wait period. + if self._user_callable_initialized: + await self._drain_ongoing_requests() + + await self.shutdown() + + async def check_health(self): + try: + # If there's no user-defined health check, nothing runs on the user code event + # loop and no future is returned. + f = self._user_callable_wrapper.call_user_health_check() + if f is not None: + await f + self._healthy = True + except Exception as e: + logger.warning("Replica health check failed.") + self._healthy = False + raise e from None + + async def record_routing_stats(self) -> Dict[str, Any]: + try: + f = self._user_callable_wrapper.call_user_record_routing_stats() + if f is not None: + return await f + return {} + except Exception as e: + logger.warning("Replica record routing stats failed.") + raise e from None + + +class Replica(ReplicaBase): + async def _on_initialized(self): + self._set_internal_replica_context( + servable_object=self._user_callable_wrapper.user_callable + ) + + # Save the initialization latency if the replica is initializing + # for the first time. + if self._initialization_latency is None: + self._initialization_latency = time.time() - self._initialization_start_time + + def _on_request_cancelled( + self, metadata: RequestMetadata, e: asyncio.CancelledError + ): + """Recursively cancels child requests.""" + requests_pending_assignment = ( + ray.serve.context._get_requests_pending_assignment( + metadata.internal_request_id + ) + ) + for task in requests_pending_assignment.values(): + task.cancel() + + # Cancel child requests that have already been assigned. + in_flight_requests = _get_in_flight_requests(metadata.internal_request_id) + for replica_result in in_flight_requests.values(): + replica_result.cancel() + + def _on_request_failed(self, request_metadata: RequestMetadata, e: Exception): + if ray.util.pdb._is_ray_debugger_post_mortem_enabled(): + ray.util.pdb._post_mortem() + + @contextmanager + def _wrap_request( + self, request_metadata: RequestMetadata + ) -> Generator[StatusCodeCallback, None, None]: + """Context manager that wraps user method calls. + + 1) Sets the request context var with appropriate metadata. + 2) Records the access log message (if not disabled). + 3) Records per-request metrics via the metrics manager. + """ + ray.serve.context._serve_request_context.set( + ray.serve.context._RequestContext( + route=request_metadata.route, + request_id=request_metadata.request_id, + _internal_request_id=request_metadata.internal_request_id, + app_name=self._deployment_id.app_name, + multiplexed_model_id=request_metadata.multiplexed_model_id, + grpc_context=request_metadata.grpc_context, + ) + ) + + with self._handle_errors_and_metrics(request_metadata) as status_code_callback: + yield status_code_callback + + +class ReplicaActor: + """Actor definition for replicas of Ray Serve deployments. + + This class defines the interface that the controller and deployment handles + (i.e., from proxies and other replicas) use to interact with a replica. + + All interaction with the user-provided callable is done via the + `UserCallableWrapper` class. + """ + + async def __init__( + self, + replica_id: ReplicaID, + serialized_deployment_def: bytes, + serialized_init_args: bytes, + serialized_init_kwargs: bytes, + deployment_config_proto_bytes: bytes, + version: DeploymentVersion, + ingress: bool, + route_prefix: str, + ): + deployment_config = DeploymentConfig.from_proto_bytes( + deployment_config_proto_bytes + ) + deployment_def = cloudpickle.loads(serialized_deployment_def) + if isinstance(deployment_def, str): + deployment_def = _load_deployment_def_from_import_path(deployment_def) + self._replica_impl: ReplicaBase = create_replica_impl( + replica_id=replica_id, + deployment_def=deployment_def, + init_args=cloudpickle.loads(serialized_init_args), + init_kwargs=cloudpickle.loads(serialized_init_kwargs), + deployment_config=deployment_config, + version=version, + ingress=ingress, + route_prefix=route_prefix, + ) + + def push_proxy_handle(self, handle: ActorHandle): + # NOTE(edoakes): it's important to call a method on the proxy handle to + # initialize its state in the C++ core worker. + handle.pong.remote() + + def get_num_ongoing_requests(self) -> int: + """Fetch the number of ongoing requests at this replica (queue length). + + This runs on a separate thread (using a Ray concurrency group) so it will + not be blocked by user code. + """ + return self._replica_impl.get_num_ongoing_requests() + + async def is_allocated(self) -> str: + """poke the replica to check whether it's alive. + + When calling this method on an ActorHandle, it will complete as + soon as the actor has started running. We use this mechanism to + detect when a replica has been allocated a worker slot. + At this time, the replica can transition from PENDING_ALLOCATION + to PENDING_INITIALIZATION startup state. + + Returns: + The PID, actor ID, node ID, node IP, and log filepath id of the replica. + """ + + return ( + os.getpid(), + ray.get_runtime_context().get_actor_id(), + ray.get_runtime_context().get_worker_id(), + ray.get_runtime_context().get_node_id(), + ray.util.get_node_ip_address(), + ray.util.get_node_instance_id(), + get_component_logger_file_path(), + ) + + async def initialize_and_get_metadata( + self, deployment_config: DeploymentConfig = None, _after: Optional[Any] = None + ) -> ReplicaMetadata: + """Handles initializing the replica. + + Returns: 5-tuple containing + 1. DeploymentConfig of the replica + 2. DeploymentVersion of the replica + 3. Initialization duration in seconds + 4. Port + 5. FastAPI `docs_path`, if relevant (i.e. this is an ingress deployment integrated with FastAPI). + """ + # Unused `_after` argument is for scheduling: passing an ObjectRef + # allows delaying this call until after the `_after` call has returned. + await self._replica_impl.initialize(deployment_config) + return self._replica_impl.get_metadata() + + async def check_health(self): + await self._replica_impl.check_health() + + async def record_routing_stats(self) -> Dict[str, Any]: + return await self._replica_impl.record_routing_stats() + + async def reconfigure( + self, deployment_config, route_prefix: Optional[str] = None + ) -> ReplicaMetadata: + await self._replica_impl.reconfigure(deployment_config, route_prefix) + return self._replica_impl.get_metadata() + + def _preprocess_request_args( + self, + pickled_request_metadata: bytes, + request_args: Tuple[Any], + ) -> Tuple[RequestMetadata, Tuple[Any]]: + request_metadata = pickle.loads(pickled_request_metadata) + if request_metadata.is_http_request or request_metadata.is_grpc_request: + request_args = (pickle.loads(request_args[0]),) + + return request_metadata, request_args + + async def handle_request( + self, + pickled_request_metadata: bytes, + *request_args, + **request_kwargs, + ) -> Tuple[bytes, Any]: + """Entrypoint for `stream=False` calls.""" + request_metadata, request_args = self._preprocess_request_args( + pickled_request_metadata, request_args + ) + result = await self._replica_impl.handle_request( + request_metadata, *request_args, **request_kwargs + ) + if request_metadata.is_grpc_request: + result = (request_metadata.grpc_context, result.SerializeToString()) + + return result + + async def handle_request_streaming( + self, + pickled_request_metadata: bytes, + *request_args, + **request_kwargs, + ) -> AsyncGenerator[Any, None]: + """Generator that is the entrypoint for all `stream=True` handle calls.""" + request_metadata, request_args = self._preprocess_request_args( + pickled_request_metadata, request_args + ) + async for result in self._replica_impl.handle_request_streaming( + request_metadata, *request_args, **request_kwargs + ): + if request_metadata.is_grpc_request: + result = (request_metadata.grpc_context, result.SerializeToString()) + + yield result + + async def handle_request_with_rejection( + self, + pickled_request_metadata: bytes, + *request_args, + **request_kwargs, + ) -> AsyncGenerator[Any, None]: + """Entrypoint for all requests with strict max_ongoing_requests enforcement. + + The first response from this generator is always a system message indicating + if the request was accepted (the replica has capacity for the request) or + rejected (the replica is already at max_ongoing_requests). + + For non-streaming requests, there will only be one more message, the unary + result of the user request handler. + + For streaming requests, the subsequent messages will be the results of the + user request handler (which must be a generator). + """ + request_metadata, request_args = self._preprocess_request_args( + pickled_request_metadata, request_args + ) + async for result in self._replica_impl.handle_request_with_rejection( + request_metadata, *request_args, **request_kwargs + ): + if isinstance(result, ReplicaQueueLengthInfo): + yield pickle.dumps(result) + else: + if request_metadata.is_grpc_request: + result = (request_metadata.grpc_context, result.SerializeToString()) + + yield result + + async def handle_request_from_java( + self, + proto_request_metadata: bytes, + *request_args, + **request_kwargs, + ) -> Any: + from ray.serve.generated.serve_pb2 import ( + RequestMetadata as RequestMetadataProto, + ) + + proto = RequestMetadataProto.FromString(proto_request_metadata) + request_metadata: RequestMetadata = RequestMetadata( + request_id=proto.request_id, + internal_request_id=proto.internal_request_id, + call_method=proto.call_method, + multiplexed_model_id=proto.multiplexed_model_id, + route=proto.route, + ) + return await self._replica_impl.handle_request( + request_metadata, *request_args, **request_kwargs + ) + + async def perform_graceful_shutdown(self): + await self._replica_impl.perform_graceful_shutdown() + + +@dataclass +class UserMethodInfo: + """Wrapper for a user method and its relevant metadata.""" + + callable: Callable + name: str + is_asgi_app: bool + takes_any_args: bool + takes_grpc_context_kwarg: bool + + @classmethod + def from_callable(cls, c: Callable, *, is_asgi_app: bool) -> "UserMethodInfo": + params = inspect.signature(c).parameters + return cls( + callable=c, + name=c.__name__, + is_asgi_app=is_asgi_app, + takes_any_args=len(params) > 0, + takes_grpc_context_kwarg=GRPC_CONTEXT_ARG_NAME in params, + ) + + +class UserCallableWrapper: + """Wraps a user-provided callable that is used to handle requests to a replica.""" + + service_unavailable_exceptions = (BackPressureError, DeploymentUnavailableError) + + def __init__( + self, + deployment_def: Callable, + init_args: Tuple, + init_kwargs: Dict, + *, + deployment_id: DeploymentID, + run_sync_methods_in_threadpool: bool, + run_user_code_in_separate_thread: bool, + local_testing_mode: bool, + ): + if not (inspect.isfunction(deployment_def) or inspect.isclass(deployment_def)): + raise TypeError( + "deployment_def must be a function or class. Instead, its type was " + f"{type(deployment_def)}." + ) + + self._deployment_def = deployment_def + self._init_args = init_args + self._init_kwargs = init_kwargs + self._is_function = inspect.isfunction(deployment_def) + self._deployment_id = deployment_id + self._local_testing_mode = local_testing_mode + self._destructor_called = False + self._run_sync_methods_in_threadpool = run_sync_methods_in_threadpool + self._run_user_code_in_separate_thread = run_user_code_in_separate_thread + self._warned_about_sync_method_change = False + self._cached_user_method_info: Dict[str, UserMethodInfo] = {} + # This is for performance optimization https://docs.python.org/3/howto/logging.html#optimization + self._is_enabled_for_debug = logger.isEnabledFor(logging.DEBUG) + # Will be populated in `initialize_callable`. + self._callable = None + + if self._run_user_code_in_separate_thread: + # All interactions with user code run on this loop to avoid blocking the + # replica's main event loop. + self._user_code_event_loop: asyncio.AbstractEventLoop = ( + asyncio.new_event_loop() + ) + + def _run_user_code_event_loop(): + # Required so that calls to get the current running event loop work + # properly in user code. + asyncio.set_event_loop(self._user_code_event_loop) + self._user_code_event_loop.run_forever() + + self._user_code_event_loop_thread = threading.Thread( + daemon=True, + target=_run_user_code_event_loop, + ) + self._user_code_event_loop_thread.start() + else: + self._user_code_event_loop = asyncio.get_running_loop() + + @property + def event_loop(self) -> asyncio.AbstractEventLoop: + return self._user_code_event_loop + + def _run_user_code(f: Callable) -> Callable: + """Decorator to run a coroutine method on the user code event loop. + + The method will be modified to be a sync function that returns a + `asyncio.Future` if user code is running in a separate event loop. + Otherwise, it will return the coroutine directly. + """ + assert inspect.iscoroutinefunction( + f + ), "_run_user_code can only be used on coroutine functions." + + @functools.wraps(f) + def wrapper(self, *args, **kwargs) -> Any: + coro = f(self, *args, **kwargs) + if self._run_user_code_in_separate_thread: + fut = asyncio.run_coroutine_threadsafe(coro, self._user_code_event_loop) + if self._local_testing_mode: + return fut + + return asyncio.wrap_future(fut) + else: + return coro + + return wrapper + + @_run_user_code + async def set_sync_method_threadpool_limit(self, limit: int): + # NOTE(edoakes): the limit is thread local, so this must + # be run on the user code event loop. + to_thread.current_default_thread_limiter().total_tokens = limit + + def get_user_method_info(self, method_name: str) -> UserMethodInfo: + """Get UserMethodInfo for the provided call method name. + + This method is cached to avoid repeated expensive calls to `inspect.signature`. + """ + if method_name in self._cached_user_method_info: + return self._cached_user_method_info[method_name] + + if self._is_function: + user_method = self._callable + elif hasattr(self._callable, method_name): + user_method = getattr(self._callable, method_name) + else: + # Filter to methods that don't start with '__' prefix. + def callable_method_filter(attr): + if attr.startswith("__"): + return False + elif not callable(getattr(self._callable, attr)): + return False + + return True + + methods = list(filter(callable_method_filter, dir(self._callable))) + raise RayServeException( + f"Tried to call a method '{method_name}' " + "that does not exist. Available methods: " + f"{methods}." + ) + + info = UserMethodInfo.from_callable( + user_method, + is_asgi_app=isinstance(self._callable, ASGIAppReplicaWrapper), + ) + self._cached_user_method_info[method_name] = info + return info + + async def _send_user_result_over_asgi( + self, + result: Any, + asgi_args: ASGIArgs, + ): + """Handle the result from user code and send it over the ASGI interface. + + If the result is already a Response type, it is sent directly. Otherwise, it + is converted to a custom Response type that handles serialization for + common Python objects. + """ + scope, receive, send = asgi_args.to_args_tuple() + if isinstance(result, starlette.responses.Response): + await result(scope, receive, send) + else: + await Response(result).send(scope, receive, send) + + async def _call_func_or_gen( + self, + callable: Callable, + *, + args: Optional[Tuple[Any]] = None, + kwargs: Optional[Dict[str, Any]] = None, + is_streaming: bool = False, + generator_result_callback: Optional[Callable] = None, + run_sync_methods_in_threadpool_override: Optional[bool] = None, + ) -> Tuple[Any, bool]: + """Call the callable with the provided arguments. + + This is a convenience wrapper that will work for `def`, `async def`, + generator, and async generator functions. + + Returns the result and a boolean indicating if the result was a sync generator + that has already been consumed. + """ + sync_gen_consumed = False + args = args if args is not None else tuple() + kwargs = kwargs if kwargs is not None else dict() + run_sync_in_threadpool = ( + self._run_sync_methods_in_threadpool + if run_sync_methods_in_threadpool_override is None + else run_sync_methods_in_threadpool_override + ) + is_sync_method = ( + inspect.isfunction(callable) or inspect.ismethod(callable) + ) and not ( + inspect.iscoroutinefunction(callable) + or inspect.isasyncgenfunction(callable) + ) + + if is_sync_method and run_sync_in_threadpool: + is_generator = inspect.isgeneratorfunction(callable) + if is_generator: + sync_gen_consumed = True + if not is_streaming: + # TODO(edoakes): make this check less redundant with the one in + # _handle_user_method_result. + raise TypeError( + f"Method '{callable.__name__}' returned a generator. " + "You must use `handle.options(stream=True)` to call " + "generators on a deployment." + ) + + def run_callable(): + result = callable(*args, **kwargs) + if is_generator: + for r in result: + generator_result_callback(r) + + result = None + + return result + + # NOTE(edoakes): we use anyio.to_thread here because it's what Starlette + # uses (and therefore FastAPI too). The max size of the threadpool is + # set to max_ongoing_requests in the replica wrapper. + # anyio.to_thread propagates ContextVars to the worker thread automatically. + result = await to_thread.run_sync(run_callable) + else: + if ( + is_sync_method + and not self._warned_about_sync_method_change + and run_sync_methods_in_threadpool_override is None + ): + self._warned_about_sync_method_change = True + warnings.warn( + RAY_SERVE_RUN_SYNC_IN_THREADPOOL_WARNING.format( + method_name=callable.__name__, + ) + ) + + result = callable(*args, **kwargs) + if inspect.iscoroutine(result): + result = await result + + return result, sync_gen_consumed + + @property + def user_callable(self) -> Optional[Callable]: + return self._callable + + async def _initialize_asgi_callable(self) -> None: + self._callable: ASGIAppReplicaWrapper + + app: Starlette = self._callable.app + + # The reason we need to do this is because BackPressureError is a serve internal exception + # and FastAPI doesn't know how to handle it, so it treats it as a 500 error. + # With same reasoning, we are not handling TimeoutError because it's a generic exception + # the FastAPI knows how to handle. See https://www.starlette.io/exceptions/ + def handle_exception(_: Request, exc: Exception): + return self.handle_exception(exc) + + for exc in self.service_unavailable_exceptions: + app.add_exception_handler(exc, handle_exception) + + await self._callable._run_asgi_lifespan_startup() + + @_run_user_code + async def initialize_callable(self) -> Optional[ASGIApp]: + """Initialize the user callable. + + If the callable is an ASGI app wrapper (e.g., using @serve.ingress), returns + the ASGI app object, which may be used *read only* by the caller. + """ + if self._callable is not None: + raise RuntimeError("initialize_callable should only be called once.") + + # This closure initializes user code and finalizes replica + # startup. By splitting the initialization step like this, + # we can already access this actor before the user code + # has finished initializing. + # The supervising state manager can then wait + # for allocation of this replica by using the `is_allocated` + # method. After that, it calls `reconfigure` to trigger + # user code initialization. + logger.info( + "Started initializing replica.", + extra={"log_to_stderr": False}, + ) + + if self._is_function: + self._callable = self._deployment_def + else: + # This allows deployments to define an async __init__ + # method (mostly used for testing). + self._callable = self._deployment_def.__new__(self._deployment_def) + await self._call_func_or_gen( + self._callable.__init__, + args=self._init_args, + kwargs=self._init_kwargs, + # Always run the constructor on the main user code thread. + run_sync_methods_in_threadpool_override=False, + ) + + if isinstance(self._callable, ASGIAppReplicaWrapper): + await self._initialize_asgi_callable() + + self._user_health_check = getattr(self._callable, HEALTH_CHECK_METHOD, None) + self._user_record_routing_stats = getattr( + self._callable, REQUEST_ROUTING_STATS_METHOD, None + ) + + logger.info( + "Finished initializing replica.", + extra={"log_to_stderr": False}, + ) + + return ( + self._callable.app + if isinstance(self._callable, ASGIAppReplicaWrapper) + else None + ) + + def _raise_if_not_initialized(self, method_name: str): + if self._callable is None: + raise RuntimeError( + f"`initialize_callable` must be called before `{method_name}`." + ) + + def call_user_health_check(self) -> Optional[concurrent.futures.Future]: + self._raise_if_not_initialized("call_user_health_check") + + # If the user provided a health check, call it on the user code thread. If user + # code blocks the event loop the health check may time out. + # + # To avoid this issue for basic cases without a user-defined health check, skip + # interacting with the user callable entirely. + if self._user_health_check is not None: + return self._call_user_health_check() + + return None + + def call_user_record_routing_stats(self) -> Optional[concurrent.futures.Future]: + self._raise_if_not_initialized("call_user_record_routing_stats") + + if self._user_record_routing_stats is not None: + return self._call_user_record_routing_stats() + + return None + + @_run_user_code + async def _call_user_health_check(self): + await self._call_func_or_gen(self._user_health_check) + + @_run_user_code + async def _call_user_record_routing_stats(self) -> Dict[str, Any]: + result, _ = await self._call_func_or_gen(self._user_record_routing_stats) + return result + + @_run_user_code + async def call_reconfigure(self, user_config: Any): + self._raise_if_not_initialized("call_reconfigure") + + # NOTE(edoakes): there is the possibility of a race condition in user code if + # they don't have any form of concurrency control between `reconfigure` and + # other methods. See https://github.com/ray-project/ray/pull/42159. + if user_config is not None: + if self._is_function: + raise ValueError("deployment_def must be a class to use user_config") + elif not hasattr(self._callable, RECONFIGURE_METHOD): + raise RayServeException( + "user_config specified but deployment " + + self._deployment_id + + " missing " + + RECONFIGURE_METHOD + + " method" + ) + await self._call_func_or_gen( + getattr(self._callable, RECONFIGURE_METHOD), + args=(user_config,), + ) + + async def _handle_user_method_result( + self, + result: Any, + user_method_info: UserMethodInfo, + *, + is_streaming: bool, + is_http_request: bool, + sync_gen_consumed: bool, + generator_result_callback: Optional[Callable], + asgi_args: Optional[ASGIArgs], + ) -> Any: + """Postprocess the result of a user method. + + User methods can be regular unary functions or return a sync or async generator. + This method will raise an exception if the result is not of the expected type + (e.g., non-generator for streaming requests or generator for unary requests). + + Generator outputs will be written to the `generator_result_callback`. + + Note that HTTP requests are an exception: they are *always* streaming requests, + but for ASGI apps (like FastAPI), the actual method will be a regular function + implementing the ASGI `__call__` protocol. + """ + result_is_gen = inspect.isgenerator(result) + result_is_async_gen = inspect.isasyncgen(result) + if is_streaming: + if result_is_gen: + for r in result: + generator_result_callback(r) + elif result_is_async_gen: + async for r in result: + generator_result_callback(r) + elif is_http_request and not user_method_info.is_asgi_app: + # For the FastAPI codepath, the response has already been sent over + # ASGI, but for the vanilla deployment codepath we need to send it. + await self._send_user_result_over_asgi(result, asgi_args) + elif not is_http_request and not sync_gen_consumed: + # If a unary method is called with stream=True for anything EXCEPT + # an HTTP request, raise an error. + # HTTP requests are always streaming regardless of if the method + # returns a generator, because it's provided the result queue as its + # ASGI `send` interface to stream back results. + raise TypeError( + f"Called method '{user_method_info.name}' with " + "`handle.options(stream=True)` but it did not return a " + "generator." + ) + else: + assert ( + not is_http_request + ), "All HTTP requests go through the streaming codepath." + + if result_is_gen or result_is_async_gen: + raise TypeError( + f"Method '{user_method_info.name}' returned a generator. " + "You must use `handle.options(stream=True)` to call " + "generators on a deployment." + ) + + return result + + async def call_http_entrypoint( + self, + request_metadata: RequestMetadata, + status_code_callback: StatusCodeCallback, + scope: Scope, + receive: Receive, + ) -> Any: + result_queue = MessageQueue() + user_method_info = self.get_user_method_info(request_metadata.call_method) + + if self._run_user_code_in_separate_thread: + # `asyncio.Event`s are not thread safe, so `call_soon_threadsafe` must be + # used to interact with the result queue from the user callable thread. + system_event_loop = asyncio.get_running_loop() + + async def enqueue(item: Any): + system_event_loop.call_soon_threadsafe(result_queue.put_nowait, item) + + call_future = self._call_http_entrypoint( + user_method_info, scope, receive, enqueue + ) + else: + + async def enqueue(item: Any): + result_queue.put_nowait(item) + + call_future = asyncio.create_task( + self._call_http_entrypoint(user_method_info, scope, receive, enqueue) + ) + + first_message_peeked = False + async for messages in result_queue.fetch_messages_from_queue(call_future): + # HTTP (ASGI) messages are only consumed by the proxy so batch them + # and use vanilla pickle (we know it's safe because these messages + # only contain primitive Python types). + # Peek the first ASGI message to determine the status code. + if not first_message_peeked: + msg = messages[0] + first_message_peeked = True + if msg["type"] == "http.response.start": + # HTTP responses begin with exactly one + # "http.response.start" message containing the "status" + # field. Other response types like WebSockets may not. + status_code_callback(str(msg["status"])) + + yield messages + + @_run_user_code + async def _call_http_entrypoint( + self, + user_method_info: UserMethodInfo, + scope: Scope, + receive: Receive, + send: Send, + ) -> Any: + """Call an HTTP entrypoint. + + `send` is used to communicate the results of streaming responses. + + Raises any exception raised by the user code so it can be propagated as a + `RayTaskError`. + """ + self._raise_if_not_initialized("_call_http_entrypoint") + + if self._is_enabled_for_debug: + logger.debug( + f"Started executing request to method '{user_method_info.name}'.", + extra={"log_to_stderr": False, "serve_access_log": True}, + ) + + if user_method_info.is_asgi_app: + request_args = (scope, receive, send) + elif not user_method_info.takes_any_args: + # Edge case to support empty HTTP handlers: don't pass the Request + # argument if the callable has no parameters. + request_args = tuple() + else: + # Non-FastAPI HTTP handlers take only the starlette `Request`. + request_args = (starlette.requests.Request(scope, receive, send),) + + receive_task = None + try: + if hasattr(receive, "fetch_until_disconnect"): + receive_task = asyncio.create_task(receive.fetch_until_disconnect()) + + result, sync_gen_consumed = await self._call_func_or_gen( + user_method_info.callable, + args=request_args, + kwargs={}, + is_streaming=True, + generator_result_callback=send, + ) + final_result = await self._handle_user_method_result( + result, + user_method_info, + is_streaming=True, + is_http_request=True, + sync_gen_consumed=sync_gen_consumed, + generator_result_callback=send, + asgi_args=ASGIArgs(scope, receive, send), + ) + + if receive_task is not None and not receive_task.done(): + receive_task.cancel() + + return final_result + except Exception as e: + if not user_method_info.is_asgi_app: + response = self.handle_exception(e) + await self._send_user_result_over_asgi( + response, ASGIArgs(scope, receive, send) + ) + + if receive_task is not None and not receive_task.done(): + receive_task.cancel() + + raise + except asyncio.CancelledError: + if receive_task is not None and not receive_task.done(): + # Do NOT cancel the receive task if the request has been + # cancelled, but the call is a batched call. This is + # because we cannot guarantee cancelling the batched + # call, so in the case that the call continues executing + # we should continue fetching data from the client. + if not hasattr(user_method_info.callable, "set_max_batch_size"): + receive_task.cancel() + + raise + + async def call_user_generator( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + ) -> AsyncGenerator[Any, None]: + """Calls a user method for a streaming call and yields its results. + + The user method is called in an asyncio `Task` and places its results on a + `result_queue`. This method pulls and yields from the `result_queue`. + """ + if not self._run_user_code_in_separate_thread: + gen = await self._call_user_generator( + request_metadata, request_args, request_kwargs + ) + async for result in gen: + yield result + else: + result_queue = MessageQueue() + + # `asyncio.Event`s are not thread safe, so `call_soon_threadsafe` must be + # used to interact with the result queue from the user callable thread. + system_event_loop = asyncio.get_running_loop() + + def _enqueue_thread_safe(item: Any): + system_event_loop.call_soon_threadsafe(result_queue.put_nowait, item) + + call_future = self._call_user_generator( + request_metadata, + request_args, + request_kwargs, + enqueue=_enqueue_thread_safe, + ) + + async for messages in result_queue.fetch_messages_from_queue(call_future): + for msg in messages: + yield msg + + @_run_user_code + async def _call_user_generator( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + *, + enqueue: Optional[Callable] = None, + ) -> Optional[AsyncGenerator[Any, None]]: + """Call a user generator. + + The `generator_result_callback` is used to communicate the results of generator + methods. + + Raises any exception raised by the user code so it can be propagated as a + `RayTaskError`. + """ + self._raise_if_not_initialized("_call_user_generator") + + request_args = request_args if request_args is not None else tuple() + request_kwargs = request_kwargs if request_kwargs is not None else dict() + + user_method_info = self.get_user_method_info(request_metadata.call_method) + callable = user_method_info.callable + is_sync_method = ( + inspect.isfunction(callable) or inspect.ismethod(callable) + ) and not ( + inspect.iscoroutinefunction(callable) + or inspect.isasyncgenfunction(callable) + ) + + if self._is_enabled_for_debug: + logger.debug( + f"Started executing request to method '{user_method_info.name}'.", + extra={"log_to_stderr": False, "serve_access_log": True}, + ) + + async def _call_generator_async() -> AsyncGenerator[Any, None]: + gen = callable(*request_args, **request_kwargs) + if inspect.iscoroutine(gen): + gen = await gen + + if inspect.isgenerator(gen): + for result in gen: + yield result + elif inspect.isasyncgen(gen): + async for result in gen: + yield result + else: + raise TypeError( + f"Called method '{user_method_info.name}' with " + "`handle.options(stream=True)` but it did not return a generator." + ) + + def _call_generator_sync(): + gen = callable(*request_args, **request_kwargs) + if inspect.isgenerator(gen): + for result in gen: + enqueue(result) + else: + raise TypeError( + f"Called method '{user_method_info.name}' with " + "`handle.options(stream=True)` but it did not return a generator." + ) + + if enqueue and is_sync_method and self._run_sync_methods_in_threadpool: + await to_thread.run_sync(_call_generator_sync) + elif enqueue: + + async def gen_coro_wrapper(): + async for result in _call_generator_async(): + enqueue(result) + + await gen_coro_wrapper() + else: + return _call_generator_async() + + @_run_user_code + async def call_user_method( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + ) -> Any: + """Call a (unary) user method. + + Raises any exception raised by the user code so it can be propagated as a + `RayTaskError`. + """ + self._raise_if_not_initialized("call_user_method") + + if self._is_enabled_for_debug: + logger.debug( + f"Started executing request to method '{request_metadata.call_method}'.", + extra={"log_to_stderr": False, "serve_access_log": True}, + ) + + user_method_info = self.get_user_method_info(request_metadata.call_method) + result, _ = await self._call_func_or_gen( + user_method_info.callable, + args=request_args, + kwargs=request_kwargs, + is_streaming=False, + ) + if inspect.isgenerator(result) or inspect.isasyncgen(result): + raise TypeError( + f"Method '{user_method_info.name}' returned a generator. " + "You must use `handle.options(stream=True)` to call " + "generators on a deployment." + ) + return result + + def handle_exception(self, exc: Exception): + if isinstance(exc, self.service_unavailable_exceptions): + return starlette.responses.Response(exc.message, status_code=503) + else: + return starlette.responses.Response( + "Internal Server Error", status_code=500 + ) + + @_run_user_code + async def call_destructor(self): + """Explicitly call the `__del__` method of the user callable. + + Calling this multiple times has no effect; only the first call will + actually call the destructor. + """ + if self._callable is None: + logger.debug( + "This replica has not yet started running user code. " + "Skipping __del__." + ) + return + + # Only run the destructor once. This is safe because there is no `await` between + # checking the flag here and flipping it to `True` below. + if self._destructor_called: + return + + self._destructor_called = True + try: + if hasattr(self._callable, "__del__"): + # Make sure to accept `async def __del__(self)` as well. + await self._call_func_or_gen( + self._callable.__del__, + # Always run the destructor on the main user callable thread. + run_sync_methods_in_threadpool_override=False, + ) + + if hasattr(self._callable, "__serve_multiplex_wrapper"): + await getattr(self._callable, "__serve_multiplex_wrapper").shutdown() + + except Exception as e: + logger.exception(f"Exception during graceful shutdown of replica: {e}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/replica_result.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/replica_result.py new file mode 100644 index 0000000000000000000000000000000000000000..9deaf00ef7743f5cab20debbc906b1a4e8e3a1f3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/replica_result.py @@ -0,0 +1,248 @@ +import asyncio +import inspect +import logging +import pickle +import threading +import time +from abc import ABC, abstractmethod +from functools import wraps +from typing import Callable, Coroutine, Optional, Union + +import ray +from ray.exceptions import TaskCancelledError +from ray.serve._private.common import ReplicaQueueLengthInfo, RequestMetadata +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.utils import calculate_remaining_timeout, generate_request_id +from ray.serve.exceptions import RequestCancelledError + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class ReplicaResult(ABC): + @abstractmethod + async def get_rejection_response(self) -> Optional[ReplicaQueueLengthInfo]: + raise NotImplementedError + + @abstractmethod + def get(self, timeout_s: Optional[float]): + raise NotImplementedError + + @abstractmethod + async def get_async(self): + raise NotImplementedError + + @abstractmethod + def __next__(self): + raise NotImplementedError + + @abstractmethod + async def __anext__(self): + raise NotImplementedError + + @abstractmethod + def add_done_callback(self, callback: Callable): + raise NotImplementedError + + @abstractmethod + def cancel(self): + raise NotImplementedError + + @abstractmethod + def to_object_ref(self, timeout_s: Optional[float]) -> ray.ObjectRef: + raise NotImplementedError + + @abstractmethod + async def to_object_ref_async(self) -> ray.ObjectRef: + raise NotImplementedError + + @abstractmethod + def to_object_ref_gen(self) -> ray.ObjectRefGenerator: + # NOTE(edoakes): there is only a sync version of this method because it + # does not block like `to_object_ref` (so there's also no timeout argument). + raise NotImplementedError + + +class ActorReplicaResult(ReplicaResult): + def __init__( + self, + obj_ref_or_gen: Union[ray.ObjectRef, ray.ObjectRefGenerator], + metadata: RequestMetadata, + *, + with_rejection: bool = False, + ): + self._obj_ref: Optional[ray.ObjectRef] = None + self._obj_ref_gen: Optional[ray.ObjectRefGenerator] = None + self._is_streaming: bool = metadata.is_streaming + self._request_id: str = metadata.request_id + self._object_ref_or_gen_sync_lock = threading.Lock() + self._lazy_object_ref_or_gen_asyncio_lock = None + self._with_rejection = with_rejection + self._rejection_response = None + + if isinstance(obj_ref_or_gen, ray.ObjectRefGenerator): + self._obj_ref_gen = obj_ref_or_gen + else: + self._obj_ref = obj_ref_or_gen + + if self._is_streaming: + assert ( + self._obj_ref_gen is not None + ), "An ObjectRefGenerator must be passed for streaming requests." + + request_context = ray.serve.context._get_serve_request_context() + if request_context.cancel_on_parent_request_cancel: + # Keep track of in-flight requests. + self._response_id = generate_request_id() + ray.serve.context._add_in_flight_request( + request_context._internal_request_id, self._response_id, self + ) + self.add_done_callback( + lambda _: ray.serve.context._remove_in_flight_request( + request_context._internal_request_id, self._response_id + ) + ) + + @property + def _object_ref_or_gen_asyncio_lock(self) -> asyncio.Lock: + """Lazy `asyncio.Lock` object.""" + if self._lazy_object_ref_or_gen_asyncio_lock is None: + self._lazy_object_ref_or_gen_asyncio_lock = asyncio.Lock() + + return self._lazy_object_ref_or_gen_asyncio_lock + + def _process_response(f: Union[Callable, Coroutine]): + @wraps(f) + def wrapper(self, *args, **kwargs): + try: + return f(self, *args, **kwargs) + except ray.exceptions.TaskCancelledError: + raise RequestCancelledError(self._request_id) + + @wraps(f) + async def async_wrapper(self, *args, **kwargs): + try: + return await f(self, *args, **kwargs) + except ray.exceptions.TaskCancelledError: + raise asyncio.CancelledError() + + if inspect.iscoroutinefunction(f): + return async_wrapper + else: + return wrapper + + @_process_response + async def get_rejection_response(self) -> Optional[ReplicaQueueLengthInfo]: + """Get the queue length info from the replica to handle rejection.""" + assert ( + self._with_rejection and self._obj_ref_gen is not None + ), "get_rejection_response() can only be called when request rejection is enabled." + + try: + if self._rejection_response is None: + response = await (await self._obj_ref_gen.__anext__()) + self._rejection_response = pickle.loads(response) + + return self._rejection_response + except asyncio.CancelledError as e: + # HTTP client disconnected or request was explicitly canceled. + logger.info( + "Cancelling request that has already been assigned to a replica." + ) + self.cancel() + raise e from None + except TaskCancelledError: + raise asyncio.CancelledError() + + @_process_response + def get(self, timeout_s: Optional[float]): + assert ( + not self._is_streaming + ), "get() can only be called on a unary ActorReplicaResult." + + start_time_s = time.time() + object_ref = self.to_object_ref(timeout_s=timeout_s) + remaining_timeout_s = calculate_remaining_timeout( + timeout_s=timeout_s, + start_time_s=start_time_s, + curr_time_s=time.time(), + ) + return ray.get(object_ref, timeout=remaining_timeout_s) + + @_process_response + async def get_async(self): + assert ( + not self._is_streaming + ), "get_async() can only be called on a unary ActorReplicaResult." + + return await (await self.to_object_ref_async()) + + @_process_response + def __next__(self): + assert ( + self._is_streaming + ), "next() can only be called on a streaming ActorReplicaResult." + + next_obj_ref = self._obj_ref_gen.__next__() + return ray.get(next_obj_ref) + + @_process_response + async def __anext__(self): + assert ( + self._is_streaming + ), "__anext__() can only be called on a streaming ActorReplicaResult." + + next_obj_ref = await self._obj_ref_gen.__anext__() + return await next_obj_ref + + def add_done_callback(self, callback: Callable): + if self._obj_ref_gen is not None: + self._obj_ref_gen.completed()._on_completed(callback) + else: + self._obj_ref._on_completed(callback) + + def cancel(self): + if self._obj_ref_gen is not None: + ray.cancel(self._obj_ref_gen) + else: + ray.cancel(self._obj_ref) + + def to_object_ref(self, *, timeout_s: Optional[float] = None) -> ray.ObjectRef: + assert ( + not self._is_streaming + ), "to_object_ref can only be called on a unary ReplicaActorResult." + + # NOTE(edoakes): this section needs to be guarded with a lock and the resulting + # object ref cached in order to avoid calling `__next__()` to + # resolve to the underlying object ref more than once. + # See: https://github.com/ray-project/ray/issues/43879. + with self._object_ref_or_gen_sync_lock: + if self._obj_ref is None: + obj_ref = self._obj_ref_gen._next_sync(timeout_s=timeout_s) + if obj_ref.is_nil(): + raise TimeoutError("Timed out resolving to ObjectRef.") + + self._obj_ref = obj_ref + + return self._obj_ref + + async def to_object_ref_async(self) -> ray.ObjectRef: + assert ( + not self._is_streaming + ), "to_object_ref_async can only be called on a unary ReplicaActorResult." + + # NOTE(edoakes): this section needs to be guarded with a lock and the resulting + # object ref cached in order to avoid calling `__anext__()` to + # resolve to the underlying object ref more than once. + # See: https://github.com/ray-project/ray/issues/43879. + async with self._object_ref_or_gen_asyncio_lock: + if self._obj_ref is None: + self._obj_ref = await self._obj_ref_gen.__anext__() + + return self._obj_ref + + def to_object_ref_gen(self) -> ray.ObjectRefGenerator: + assert ( + self._is_streaming + ), "to_object_ref_gen can only be called on a streaming ReplicaActorResult." + + return self._obj_ref_gen diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4b7616810775a7b1857bc1247a3dc7126990572 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__init__.py @@ -0,0 +1,10 @@ +from ray.serve._private.request_router.common import PendingRequest # noqa: F401 +from ray.serve._private.request_router.pow_2_router import ( # noqa: F401 + PowerOfTwoChoicesRequestRouter, +) +from ray.serve._private.request_router.replica_wrapper import ( # noqa: F401 + RunningReplica, +) +from ray.serve._private.request_router.request_router import ( # noqa: F401 + RequestRouter, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e0387299e81056d7e7a64e99fb0d62520090d4a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7bc4e8c085cf11e22fbbe25fb5bc3bae968aa5d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/pow_2_router.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/pow_2_router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eb1cec0269985cc4b8b9dc6f3b066aa483acd21 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/pow_2_router.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/replica_wrapper.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/replica_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4615b58524c156f50552134a518d39af49848079 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/replica_wrapper.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/request_router.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/request_router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..779bad395989dbda1c1ab1cca1110d98939a5daa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/__pycache__/request_router.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/common.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/common.py new file mode 100644 index 0000000000000000000000000000000000000000..4653daca2185b454e8f834ef660567e5b379121c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/common.py @@ -0,0 +1,107 @@ +import asyncio +import logging +import time +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Optional, Set + +from ray.serve._private.common import ReplicaID, RequestMetadata +from ray.serve._private.constants import ( + RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S, + SERVE_LOGGER_NAME, +) +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@dataclass() +class RequestRoutingContext: + multiplexed_start_matching_time: Optional[float] = None + tried_fewest_multiplexed_models: bool = False + tried_first_multiplexed_models: bool = False + tried_same_node: bool = False + tried_same_az: bool = False + should_backoff: bool = False + + +@PublicAPI(stability="alpha") +@dataclass +class PendingRequest: + """A request that is pending execution by a replica.""" + + args: List[Any] + """Positional arguments for the request.""" + + kwargs: Dict[Any, Any] + """Keyword arguments for the request.""" + + metadata: RequestMetadata + """Metadata for the request, including request ID and whether it's streaming.""" + + created_at: float = field(default_factory=time.time) + """Timestamp when the request was created.""" + + future: asyncio.Future = field(default_factory=lambda: asyncio.Future()) + """An asyncio Future that will be set when the request is routed.""" + + routing_context: RequestRoutingContext = field( + default_factory=RequestRoutingContext + ) + """Context for request routing, used to track routing attempts and backoff.""" + + resolved: bool = False + """Whether the arguments have been resolved.""" + + def reset_future(self): + """Reset the `asyncio.Future`, must be called if this request is re-used.""" + self.future = asyncio.Future() + + +@dataclass(frozen=True) +class ReplicaQueueLengthCacheEntry: + queue_len: int + timestamp: float + + +class ReplicaQueueLengthCache: + def __init__( + self, + *, + staleness_timeout_s: float = RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S, + get_curr_time_s: Optional[Callable[[], float]] = None, + ): + self._cache: Dict[ReplicaID, ReplicaQueueLengthCacheEntry] = {} + self._staleness_timeout_s = staleness_timeout_s + self._get_curr_time_s = ( + get_curr_time_s if get_curr_time_s is not None else time.time + ) + + def _is_timed_out(self, timestamp_s: int) -> bool: + return self._get_curr_time_s() - timestamp_s > self._staleness_timeout_s + + def get(self, replica_id: ReplicaID) -> Optional[int]: + """Get the queue length for a replica. + + Returns `None` if the replica ID is not present or the entry is timed out. + """ + entry = self._cache.get(replica_id) + if entry is None or self._is_timed_out(entry.timestamp): + return None + + return entry.queue_len + + def update(self, replica_id: ReplicaID, queue_len: int): + """Set (or update) the queue length for a replica ID.""" + self._cache[replica_id] = ReplicaQueueLengthCacheEntry( + queue_len, self._get_curr_time_s() + ) + + def invalidate_key(self, replica_id: ReplicaID): + self._cache.pop(replica_id, None) + + def remove_inactive_replicas(self, *, active_replica_ids: Set[ReplicaID]): + """Removes entries for all replica IDs not in the provided active set.""" + # NOTE: the size of the cache dictionary changes during this loop. + for replica_id in list(self._cache.keys()): + if replica_id not in active_replica_ids: + self._cache.pop(replica_id) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/pow_2_router.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/pow_2_router.py new file mode 100644 index 0000000000000000000000000000000000000000..c929e3204a345455fe76509146a89e97ac7da456 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/pow_2_router.py @@ -0,0 +1,89 @@ +import logging +import random +from typing import ( + List, + Optional, +) + +from ray.serve._private.constants import ( + SERVE_LOGGER_NAME, +) +from ray.serve._private.request_router.common import ( + PendingRequest, +) +from ray.serve._private.request_router.replica_wrapper import ( + RunningReplica, +) +from ray.serve._private.request_router.request_router import ( + FIFOMixin, + LocalityMixin, + MultiplexMixin, + RequestRouter, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class PowerOfTwoChoicesRequestRouter( + FIFOMixin, LocalityMixin, MultiplexMixin, RequestRouter +): + """Chooses a replica for each request using the "power of two choices" procedure. + + Requests are routed in FIFO order. + + When a request comes in, two candidate replicas are chosen randomly. Each replica + is sent a control message to fetch its queue length. + + The replica responds with two items: (queue_len, accepted). Only replicas that + accept the request are considered; between those, the one with the lower queue + length is chosen. + + In the case when neither replica accepts the request (e.g., their queues are full), + the procedure is repeated with backoff. This backoff repeats indefinitely until a + replica is chosen, so the caller should use timeouts and cancellation to avoid + hangs. + + Each request being routed may spawn an independent task that runs the routing + procedure concurrently. This task will not necessarily satisfy the request that + started it (in order to maintain the FIFO order). The total number of tasks is + capped at (2 * num_replicas). + """ + + async def choose_replicas( + self, + candidate_replicas: List[RunningReplica], + pending_request: Optional[PendingRequest] = None, + ) -> List[List[RunningReplica]]: + """One iteration of the power of two choices procedure that chooses + (at most) two random available replicas. + + For multiplexing, this will first attempt to choose replicas that have the + requested model ID for a configured timeout. If no replicas with the matching + model ID are available after that timeout, it will fall back to the regular + procedure. + """ + if ( + pending_request is not None + and pending_request.metadata.multiplexed_model_id + ): + # Get candidates for multiplexed model ID. + candidate_replica_ids = self.apply_multiplex_routing( + pending_request=pending_request, + ) + else: + # Get candidates for locality preference. + candidate_replica_ids = self.apply_locality_routing( + pending_request=pending_request, + ) + + if not candidate_replica_ids: + return [] + + chosen_ids = random.sample( + list(candidate_replica_ids), + k=min(2, len(candidate_replica_ids)), + ) + replica_id_to_replica_map = { + replica.replica_id: replica for replica in candidate_replicas + } + return [[replica_id_to_replica_map[chosen_id] for chosen_id in chosen_ids]] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/replica_wrapper.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/replica_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..d42266c312cf115365b1e0b6a1f5ead13a238a9b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/replica_wrapper.py @@ -0,0 +1,182 @@ +import asyncio +import pickle +from abc import ABC, abstractmethod +from typing import Any, Dict, Optional, Set + +import ray +from ray.actor import ActorHandle +from ray.serve._private.common import ( + ReplicaID, + RunningReplicaInfo, +) +from ray.serve._private.replica_result import ActorReplicaResult, ReplicaResult +from ray.serve._private.request_router.common import PendingRequest +from ray.serve._private.utils import JavaActorHandleProxy +from ray.serve.generated.serve_pb2 import RequestMetadata as RequestMetadataProto +from ray.util.annotations import PublicAPI + + +class ReplicaWrapper(ABC): + """This is used to abstract away details of the transport layer + when communicating with the replica. + """ + + @abstractmethod + def send_request_java(self, pr: PendingRequest) -> ReplicaResult: + """Send request to Java replica.""" + pass + + @abstractmethod + def send_request_python( + self, pr: PendingRequest, *, with_rejection: bool + ) -> ReplicaResult: + """Send request to Python replica. + + If sending request with rejection, the replica will yield a + system message (ReplicaQueueLengthInfo) before executing the + actual request. This can cause it to reject the request. The + result will *always* be a generator, so for non-streaming + requests it's up to the caller to resolve it to its first (and + only) ObjectRef. + """ + pass + + +class ActorReplicaWrapper(ReplicaWrapper): + def __init__(self, actor_handle): + self._actor_handle = actor_handle + + def send_request_java(self, pr: PendingRequest) -> ActorReplicaResult: + """Send the request to a Java replica. + Does not currently support streaming. + """ + if pr.metadata.is_streaming: + raise RuntimeError("Streaming not supported for Java.") + + if len(pr.args) != 1: + raise ValueError("Java handle calls only support a single argument.") + + return ActorReplicaResult( + self._actor_handle.handle_request.remote( + RequestMetadataProto( + request_id=pr.metadata.request_id, + # Default call method in java is "call," not "__call__" like Python. + call_method="call" + if pr.metadata.call_method == "__call__" + else pr.metadata.call_method, + ).SerializeToString(), + pr.args, + ), + pr.metadata, + ) + + def send_request_python( + self, pr: PendingRequest, *, with_rejection: bool + ) -> ActorReplicaResult: + """Send the request to a Python replica.""" + if with_rejection: + # Call a separate handler that may reject the request. + # This handler is *always* a streaming call and the first message will + # be a system message that accepts or rejects. + method = self._actor_handle.handle_request_with_rejection.options( + num_returns="streaming" + ) + elif pr.metadata.is_streaming: + method = self._actor_handle.handle_request_streaming.options( + num_returns="streaming" + ) + else: + method = self._actor_handle.handle_request + + obj_ref_gen = method.remote(pickle.dumps(pr.metadata), *pr.args, **pr.kwargs) + return ActorReplicaResult( + obj_ref_gen, pr.metadata, with_rejection=with_rejection + ) + + +@PublicAPI(stability="alpha") +class RunningReplica: + """Contains info on a running replica. + Also defines the interface for a request router to talk to a replica. + """ + + def __init__(self, replica_info: RunningReplicaInfo): + self._replica_info = replica_info + self._multiplexed_model_ids = set(replica_info.multiplexed_model_ids) + + if replica_info.is_cross_language: + self._actor_handle = JavaActorHandleProxy(replica_info.actor_handle) + else: + self._actor_handle = replica_info.actor_handle + + @property + def replica_id(self) -> ReplicaID: + """ID of this replica.""" + return self._replica_info.replica_id + + @property + def actor_id(self) -> ray.ActorID: + """Actor ID of this replica.""" + return self._actor_handle._actor_id + + @property + def node_id(self) -> str: + """Node ID of the node this replica is running on.""" + return self._replica_info.node_id + + @property + def availability_zone(self) -> Optional[str]: + """Availability zone of the node this replica is running on.""" + return self._replica_info.availability_zone + + @property + def multiplexed_model_ids(self) -> Set[str]: + """Set of model IDs on this replica.""" + return self._multiplexed_model_ids + + @property + def routing_stats(self) -> Dict[str, Any]: + """Dictionary of routing stats.""" + return self._replica_info.routing_stats + + @property + def max_ongoing_requests(self) -> int: + """Max concurrent requests that can be sent to this replica.""" + return self._replica_info.max_ongoing_requests + + @property + def is_cross_language(self) -> bool: + """Whether this replica is cross-language (Java).""" + return self._replica_info.is_cross_language + + def _get_replica_wrapper(self, pr: PendingRequest) -> ReplicaWrapper: + return ActorReplicaWrapper(self._actor_handle) + + def push_proxy_handle(self, handle: ActorHandle): + """When on proxy, push proxy's self handle to replica""" + self._actor_handle.push_proxy_handle.remote(handle) + + async def get_queue_len(self, *, deadline_s: float) -> int: + """Returns current queue len for the replica. + `deadline_s` is passed to verify backoff for testing. + """ + # NOTE(edoakes): the `get_num_ongoing_requests` method name is shared by + # the Python and Java replica implementations. If you change it, you need to + # change both (or introduce a branch here). + obj_ref = self._actor_handle.get_num_ongoing_requests.remote() + try: + return await obj_ref + except asyncio.CancelledError: + ray.cancel(obj_ref) + raise + + def try_send_request( + self, pr: PendingRequest, with_rejection: bool + ) -> ReplicaResult: + """Try to send the request to this replica. It may be rejected.""" + wrapper = self._get_replica_wrapper(pr) + if self._replica_info.is_cross_language: + assert not with_rejection, "Request rejection not supported for Java." + return wrapper.send_request_java(pr) + + return wrapper.send_request_python(pr, with_rejection=with_rejection) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/request_router.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/request_router.py new file mode 100644 index 0000000000000000000000000000000000000000..2d95689d5b41bf5808312f7568bb31584c677758 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/request_router/request_router.py @@ -0,0 +1,1153 @@ +import asyncio +import enum +import logging +import math +import random +import time +from abc import ABC, abstractmethod +from collections import defaultdict, deque +from typing import ( + AsyncGenerator, + Callable, + DefaultDict, + Deque, + Dict, + List, + Optional, + Set, + Tuple, +) + +from ray.actor import ActorHandle +from ray.exceptions import ActorDiedError, ActorUnavailableError +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + ReplicaID, + ReplicaQueueLengthInfo, + RequestMetadata, + RunningReplicaInfo, +) +from ray.serve._private.constants import ( + RAY_SERVE_MAX_QUEUE_LENGTH_RESPONSE_DEADLINE_S, + RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S, + RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S, + RAY_SERVE_ROUTER_RETRY_BACKOFF_MULTIPLIER, + RAY_SERVE_ROUTER_RETRY_INITIAL_BACKOFF_S, + RAY_SERVE_ROUTER_RETRY_MAX_BACKOFF_S, + SERVE_LOGGER_NAME, +) +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.request_router.common import ( + PendingRequest, + ReplicaQueueLengthCache, +) +from ray.serve._private.request_router.replica_wrapper import RunningReplica +from ray.util import metrics +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class LocalityScope(str, enum.Enum): + NODE = "NODE" + AVAILABILITY_ZONE = "AVAILABILITY_ZONE" + + +@PublicAPI(stability="alpha") +class LocalityMixin: + """Mixin for locality routing. + + This mixin is used to route requests to replicas that are colocated + with the handle. It adds necessary attributes and methods to keep track of + locality scopes and offer the helpers to apply locality routing and + rank replicas based on locality. + """ + + def __init__( + self, + self_node_id: Optional[str] = None, + prefer_local_node_routing: bool = False, + prefer_local_az_routing: bool = False, + self_availability_zone: Optional[str] = None, + *args, + **kwargs, + ): + super().__init__(*args, **kwargs) + self._self_node_id = self_node_id + self._prefer_local_node_routing = prefer_local_node_routing + self._prefer_local_az_routing = prefer_local_az_routing + self._self_availability_zone = self_availability_zone + + # Colocated replicas (e.g. wrt node, AZ) + self._colocated_replica_ids: DefaultDict[ + LocalityScope, Set[ReplicaID] + ] = defaultdict(set) + self._replica_id_set: Set[ReplicaID] = set() + + def _discard_colocated_replica_ids_on_replica_actor_died( + self, replica_id: ReplicaID + ): + """Remove the replica ID from the colocated replica IDs. + This is called when a replica actor dies. + """ + for id_set in self._colocated_replica_ids.values(): + id_set.discard(replica_id) + + def _update_colocated_replica_ids_with_replicas( + self, replicas: List[RunningReplica] + ): + """Update the colocated replica IDs based on the replicas. + This is called when the replicas are updated. + """ + new_colocated_replica_ids = defaultdict(set) + + for r in replicas: + if self._self_node_id is not None and r.node_id == self._self_node_id: + new_colocated_replica_ids[LocalityScope.NODE].add(r.replica_id) + if ( + self._self_availability_zone is not None + and r.availability_zone == self._self_availability_zone + ): + new_colocated_replica_ids[LocalityScope.AVAILABILITY_ZONE].add( + r.replica_id + ) + + self._colocated_replica_ids = new_colocated_replica_ids + + def apply_locality_routing( + self, + pending_request: Optional[PendingRequest] = None, + ) -> Set[ReplicaID]: + """Apply locality routing to the pending request. + + When the reqeust is None, return all replicas. Each call will try to + route the request to replicas in the priority of first on the + same node, then in the same availability zone, and finally all + replicas. + + Args: + pending_request: The pending request to be routed. + Returns: + A set of replica IDs that are candidates based on + the locality policy. + """ + + if not pending_request: + return self._replica_id_set + + if ( + self._prefer_local_node_routing + and not pending_request.routing_context.tried_same_node + and len(self._colocated_replica_ids[LocalityScope.NODE]) > 0 + ): + # Attempt to route requests to replicas on the + # same node at most once + candidate_replica_ids = self._colocated_replica_ids[LocalityScope.NODE] + pending_request.routing_context.tried_same_node = True + pending_request.routing_context.should_backoff = False + elif ( + self._prefer_local_az_routing + and not pending_request.routing_context.tried_same_az + and len(self._colocated_replica_ids[LocalityScope.AVAILABILITY_ZONE]) > 0 + ): + # Attempt to route requests to replicas in the same + # AZ at most once + candidate_replica_ids = self._colocated_replica_ids[ + LocalityScope.AVAILABILITY_ZONE + ] + pending_request.routing_context.tried_same_az = True + pending_request.routing_context.should_backoff = False + else: + # On subsequent iterations or when there are no replicas on the same + # node or AZ, consider all available replicas. + candidate_replica_ids = self._replica_id_set + pending_request.routing_context.should_backoff = True + return candidate_replica_ids + + def rank_replicas_via_locality( + self, + replicas: List[RunningReplica], + ) -> List[List[RunningReplica]]: + """Rank the replicas based on the locality preference. + Rank 0 is the list of replicas that are on the same node. + Rank 1 is the list of replicas that are on the same availability zone. + Rank 2 is the list of all other replicas. + """ + ranked_replicas = [[] for _ in range(3)] + for replica in replicas: + if replica.replica_id in self._colocated_replica_ids[LocalityScope.NODE]: + ranked_replicas[0].append(replica) + elif ( + replica.replica_id + in self._colocated_replica_ids[LocalityScope.AVAILABILITY_ZONE] + ): + ranked_replicas[1].append(replica) + else: + ranked_replicas[2].append(replica) + return ranked_replicas + + +@PublicAPI(stability="alpha") +class MultiplexMixin: + """Mixin for multiplex routing. + + This mixin is used to route requests to replicas that are multiplexed. + It adds necessary attributes and methods to keep track of multiplexed + model IDs and offer the helpers to apply multiplex routing and rank + replicas based on multiplexed model IDs. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._multiplexed_model_id_to_replica_ids: DefaultDict[ + str, Set[ReplicaID] + ] = defaultdict(set) + + # When there is no match for a multiplexed model id, we will try to fall back + # to all replicas immediately. This set is used to make sure we only fall back + # once for concurrent requests for the same model id. + # Whenever there is a match, we will remove the model id from this set. + self._multiplexed_model_id_fallback_match: Set[str] = set() + self._replica_id_set: Set[ReplicaID] = set() + self._replicas: Dict[ReplicaID, RunningReplica] = {} + + def _get_pending_request_matching_multiplexed_model_id( + self, + request_metadata: Optional[RequestMetadata] = None, + ) -> Optional[PendingRequest]: + """Matching pending request based on the request metadata.""" + if request_metadata is None or not request_metadata.multiplexed_model_id: + return None + + for pr in self._pending_requests_to_fulfill: + if ( + not pr.future.done() + and pr.metadata.multiplexed_model_id + == request_metadata.multiplexed_model_id + ): + return pr + + def _update_multiplexed_model_ids_with_replicas( + self, replicas: List[RunningReplica] + ): + """Update the multiplexed model IDs based on the replicas. + + This should be called when the replicas are updated. + """ + new_multiplexed_model_id_to_replica_ids = defaultdict(set) + + for r in replicas: + for model_id in r.multiplexed_model_ids: + new_multiplexed_model_id_to_replica_ids[model_id].add(r.replica_id) + + self._multiplexed_model_id_to_replica_ids = ( + new_multiplexed_model_id_to_replica_ids + ) + + def _get_replica_ids_with_fewest_multiplexed_models(self) -> Set[str]: + """Get the set of replicas that have the fewest multiplexed models loaded.""" + candidates = set() + sorted_replicas = sorted( + self._replicas.values(), key=lambda x: len(x.multiplexed_model_ids) + ) + least_num_multiplexed_model_ids = math.inf + for replica in sorted_replicas: + if len(replica.multiplexed_model_ids) <= least_num_multiplexed_model_ids: + candidates.add(replica.replica_id) + least_num_multiplexed_model_ids = len(replica.multiplexed_model_ids) + else: + break + + return candidates + + @property + def _multiplexed_matching_timeout(self) -> float: + return random.uniform( + RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S, + RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S * 2, + ) + + def apply_multiplex_routing( + self, + pending_request: Optional[PendingRequest] = None, + ) -> Set[ReplicaID]: + """Apply multiplex routing to the pending request. + + When the request is None, return all replicas. Each call will try to + route the request to the replicas that have the multiplexed model ID + to the hierarchy of first the replicas with the multiplexed model ID, + then the replicas with the fewest multiplexed models, and finally all + replicas. + + Args: + pending_request: The pending request to be routed based on + multiplexed model policy. + + Returns: + A set of replica IDs that are candidates for the existing + routing call. + """ + if not pending_request: + return self._replica_id_set + + if not pending_request.routing_context.multiplexed_start_matching_time: + pending_request.routing_context.multiplexed_start_matching_time = ( + time.time() + ) + + multiplexed_start_matching_time = ( + pending_request.routing_context.multiplexed_start_matching_time + ) + multiplexed_model_id = pending_request.metadata.multiplexed_model_id + if ( + time.time() - multiplexed_start_matching_time + < self._multiplexed_matching_timeout + ): + candidate_replica_ids = self._multiplexed_model_id_to_replica_ids.get( + multiplexed_model_id, None + ) + if ( + not candidate_replica_ids + and multiplexed_model_id + not in self._multiplexed_model_id_fallback_match + ) or pending_request.routing_context.tried_first_multiplexed_models: + # When there is no match for a multiplexed model id + # or when the replica(s) with the matching model id is busy, + # first try to fall back to replicas with the fewest models. + candidate_replica_ids = ( + self._get_replica_ids_with_fewest_multiplexed_models() + ) + self._multiplexed_model_id_fallback_match.add(multiplexed_model_id) + elif candidate_replica_ids: + self._multiplexed_model_id_fallback_match.discard(multiplexed_model_id) + pending_request.routing_context.tried_first_multiplexed_models = True + elif not pending_request.routing_context.tried_fewest_multiplexed_models: + # After the `_multiplexed_matching_timeout` is up, first try + # routing to replicas that have the fewest models loaded. + # We only try this once to avoid deterministically retrying on + # the same replicas repeatedly. + candidate_replica_ids = ( + self._get_replica_ids_with_fewest_multiplexed_models() + ) + pending_request.routing_context.tried_fewest_multiplexed_models = True + else: + # If the timeout is up, and we've already tried the candidates + # with the fewest models loaded, fall back to all replicas. + candidate_replica_ids = self._replica_id_set + + pending_request.routing_context.should_backoff = True + return candidate_replica_ids + + def rank_replicas_via_multiplex( + self, + replicas: List[RunningReplica], + multiplexed_model_id: str, + ) -> List[List[RunningReplica]]: + """Rank the replicas based on the multiplexed model ID. + Rank 0 is the list of replicas that have the multiplexed model ID. + Rank 1 is the list of replicas that have the fewest multiplexed models. + Rank 2 is the list of all other replicas. + """ + replica_ids_with_multiplexed_model = ( + self._multiplexed_model_id_to_replica_ids.get(multiplexed_model_id, set()) + ) + replica_ids_with_fewest_multiplexed_models = ( + self._get_replica_ids_with_fewest_multiplexed_models() + ) + + ranked_replicas = [[] for _ in range(3)] + for replica in replicas: + if replica.replica_id in replica_ids_with_multiplexed_model: + ranked_replicas[0].append(replica) + elif replica.replica_id in replica_ids_with_fewest_multiplexed_models: + ranked_replicas[1].append(replica) + else: + ranked_replicas[2].append(replica) + return ranked_replicas + + +@PublicAPI(stability="alpha") +class FIFOMixin: + """Mixin for FIFO routing. + + This mixin is used to route requests in FIFO order, optionally prioritizing + requests with matching metadata. RequestRouter's default behavior is + out-of-order routing and match exactly the internal request id of + the request. This mixin doesn't provide any helper methods. By including it + in your custom implementation of RequestRouter, it will override the + reqeust matching algorithm to match based on the request metadata + multiplexed model id, if available, and then fall back to the first pending + request in the queue. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def _get_pending_request_matching_metadata( + self, + request_metadata: Optional[RequestMetadata] = None, + ) -> Optional[PendingRequest]: + """Matching pending request based on the request metadata. + + If multiplex mixin is used, this will be using the multiplexed model + id for the matching. Else, it will return none as no matching pending request. + """ + if hasattr(self, "_get_pending_request_matching_multiplexed_model_id"): + return self._get_pending_request_matching_multiplexed_model_id( + request_metadata + ) + + return None + + def _fulfill_next_pending_request( + self, + replica: RunningReplica, + request_metadata: Optional[RequestMetadata] = None, + ): + """Assign the replica to the next pending request in FIFO order. + + If a pending request has been cancelled, it will be popped from the queue + and not assigned. + """ + # First try to match a pending request based on the request metadata. + matched_pending_request = self._get_pending_request_matching_metadata( + request_metadata + ) + if matched_pending_request is not None: + matched_pending_request.future.set_result(replica) + self._pending_requests_to_fulfill.remove(matched_pending_request) + return + + # If no pending request matches the request metadata, fulfill the next in the + # queue in FIFO order, passing over futures that have been cancelled. + while len(self._pending_requests_to_fulfill) > 0: + pr = self._pending_requests_to_fulfill.popleft() + if not pr.future.done(): + pr.future.set_result(replica) + break + + +@PublicAPI(stability="alpha") +class RequestRouter(ABC): + """Abstract interface for a request router (how the router calls it).""" + + """Backoff parameters for request router.""" + initial_backoff_s = RAY_SERVE_ROUTER_RETRY_INITIAL_BACKOFF_S + backoff_multiplier = RAY_SERVE_ROUTER_RETRY_BACKOFF_MULTIPLIER + max_backoff_s = RAY_SERVE_ROUTER_RETRY_MAX_BACKOFF_S + + # Deadline for replicas to respond with their queue length. If the response isn't + # received within this deadline, the replica will not be considered. + # If this deadline is repeatedly missed, it will be exponentially increased up to + # the maximum configured here. + queue_len_response_deadline_s = RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S + """Deadline for receiving queue length info from replicas.""" + + max_queue_len_response_deadline_s = RAY_SERVE_MAX_QUEUE_LENGTH_RESPONSE_DEADLINE_S + """Maximum deadline for receiving queue length info from replicas.""" + + max_num_routing_tasks_cap = 50 + """ + Hard limit on the maximum number of routing tasks to run. Having too many of + these tasks can cause stability issue due to too much load on the local process + and many too requests in flight to fetch replicas' queue lengths. + """ + + def __init__( + self, + deployment_id: DeploymentID, + handle_source: DeploymentHandleSource, + self_actor_id: Optional[str] = None, + self_actor_handle: Optional[ActorHandle] = None, + use_replica_queue_len_cache: bool = False, + get_curr_time_s: Optional[Callable[[], float]] = None, + create_replica_wrapper_func: Optional[ + Callable[[RunningReplicaInfo], RunningReplica] + ] = None, + *args, + **kwargs, + ): + self._deployment_id = deployment_id + self._handle_source = handle_source + self._self_actor_handle = self_actor_handle + self._use_replica_queue_len_cache = use_replica_queue_len_cache + self._create_replica_wrapper_func = create_replica_wrapper_func + + # Current replicas available to be routed. + # Updated via `update_replicas`. + self._replica_id_set: Set[ReplicaID] = set() + self._replicas: Dict[ReplicaID, RunningReplica] = {} + self._replica_queue_len_cache = ReplicaQueueLengthCache( + get_curr_time_s=get_curr_time_s, + ) + + # NOTE(edoakes): Python 3.10 removed the `loop` parameter to `asyncio.Event`. + # Now, the `asyncio.Event` will call `get_running_loop` in its constructor to + # determine the loop to attach to. This class can be constructed for the handle + # from a different loop than it uses for routing, so we need to construct it + # lazily to avoid an error due to the event being attached to the wrong loop. + self._lazily_constructed_replicas_updated_event: Optional[asyncio.Event] = None + self._lazily_fetched_loop: Optional[asyncio.AbstractEventLoop] = None + + # Tasks running the routing loop. The size of this set may vary over time + # as new tasks will be routed when a request comes in or new replicas are + # added, but it will not exceed self.max_num_routing_tasks. + self._routing_tasks: Set[asyncio.Task] = set() + + # We keep two separate queues of pending requests: + # - self._pending_requests_to_fulfill is a queue that will be used to fulfill + # requests (potentially out of order) by routing tasks once they've acquired a replica. + # - self.routing is a queue that is used for tasks to + # best-effort grab the metadata of requests waiting to be fulfilled. This is + # currently used for routing tasks to know which multiplexed model IDs they + # should be trying to get replicas for. + self._pending_requests_to_fulfill: Deque[PendingRequest] = deque() + self._pending_requests_to_route: Deque[PendingRequest] = deque() + + # Prepare request router metrics. + self.num_routing_tasks_gauge = metrics.Gauge( + "serve_num_scheduling_tasks", + description="The number of request routing tasks in the router.", + tag_keys=("app", "deployment", "actor_id"), + ).set_default_tags( + { + "app": self._deployment_id.app_name, + "deployment": self._deployment_id.name, + "actor_id": self_actor_id if self_actor_id else "", + } + ) + self.num_routing_tasks_gauge.set(0) + + self.num_routing_tasks_in_backoff = 0 + self.num_routing_tasks_in_backoff_gauge = metrics.Gauge( + "serve_num_scheduling_tasks_in_backoff", + description=( + "The number of request routing tasks in the router " + "that are undergoing backoff." + ), + tag_keys=("app", "deployment", "actor_id"), + ).set_default_tags( + { + "app": self._deployment_id.app_name, + "deployment": self._deployment_id.name, + "actor_id": self_actor_id if self_actor_id else "", + } + ) + self.num_routing_tasks_in_backoff_gauge.set(self.num_routing_tasks_in_backoff) + + def initialize_state(self, **kwargs): + """ + Initialize the state of the request router. Called by the Ray Serve framework with the + contents of `RequestRouter.request_router_kwargs`. + """ + pass + + @property + def _event_loop(self) -> asyncio.AbstractEventLoop: + if self._lazily_fetched_loop is None: + self._lazily_fetched_loop = asyncio.get_running_loop() + + return self._lazily_fetched_loop + + @property + def _replicas_updated_event(self) -> asyncio.Event: + """Lazily construct `asyncio.Event`. + + See comment for self._lazily_constructed_replicas_updated_event. + """ + if self._lazily_constructed_replicas_updated_event is None: + self._lazily_constructed_replicas_updated_event = asyncio.Event() + + return self._lazily_constructed_replicas_updated_event + + @property + def num_pending_requests(self) -> int: + """Current number of requests pending assignment.""" + return len(self._pending_requests_to_fulfill) + + @property + def curr_num_routing_tasks(self) -> int: + """Current number of routing tasks running.""" + return len(self._routing_tasks) + + @property + def max_num_routing_tasks(self) -> int: + """Max number of routing tasks to run at any time.""" + return min(self.max_num_routing_tasks_cap, 2 * len(self._replicas)) + + @property + def target_num_routing_tasks(self) -> int: + """Target number of routing tasks to be running based on pending requests. + + This will never exceed `self.max_num_routing_tasks`. + """ + return min(self.num_pending_requests, self.max_num_routing_tasks) + + @property + def curr_replicas(self) -> Dict[ReplicaID, RunningReplica]: + """Current replicas available to be routed.""" + return self._replicas + + @property + def app_name(self) -> str: + """Name of the app this router is serving.""" + return self._deployment_id.app_name + + @property + def replica_queue_len_cache(self) -> ReplicaQueueLengthCache: + """Get the replica queue length cache.""" + return self._replica_queue_len_cache + + def create_replica_wrapper( + self, replica_info: RunningReplicaInfo + ) -> RunningReplica: + return self._create_replica_wrapper_func(replica_info) + + def on_replica_actor_died(self, replica_id: ReplicaID): + """Drop replica from replica set so it's not considered for future requests.""" + self._replicas.pop(replica_id, None) + self._replica_id_set.discard(replica_id) + if hasattr(self, "_discard_colocated_replica_ids_on_replica_actor_died"): + self._discard_colocated_replica_ids_on_replica_actor_died(replica_id) + + def on_replica_actor_unavailable(self, replica_id: ReplicaID): + """Invalidate cache entry so active probing is required for the next request.""" + self._replica_queue_len_cache.invalidate_key(replica_id) + + def on_new_queue_len_info( + self, replica_id: ReplicaID, queue_len_info: ReplicaQueueLengthInfo + ): + """Update queue length cache with new info received from replica.""" + if self._use_replica_queue_len_cache: + self._replica_queue_len_cache.update( + replica_id, queue_len_info.num_ongoing_requests + ) + + def on_send_request(self, replica_id: ReplicaID): + """Increment queue length cache when a request is sent to a replica.""" + if self._use_replica_queue_len_cache: + num_ongoing_requests = self._replica_queue_len_cache.get(replica_id) or 0 + self._replica_queue_len_cache.update(replica_id, num_ongoing_requests + 1) + + def update_replicas(self, replicas: List[RunningReplica]): + """Update the set of available replicas to be considered for routing. + + When the set of replicas changes, we may spawn additional routing tasks + if there are pending requests. + """ + new_replicas = {} + new_replica_id_set = set() + if hasattr(self, "_update_colocated_replica_ids_with_replicas"): + self._update_colocated_replica_ids_with_replicas(replicas) + if hasattr(self, "_update_multiplexed_model_ids_with_replicas"): + self._update_multiplexed_model_ids_with_replicas(replicas) + + for r in replicas: + # If on the proxy, replica needs to call back into the proxy with + # `receive_asgi_messages` which can be blocked when GCS is down. + # To prevent that from happening, push proxy handle eagerly + if ( + self._handle_source == DeploymentHandleSource.PROXY + and r.replica_id not in self._replicas + ): + r.push_proxy_handle(self._self_actor_handle) + + new_replicas[r.replica_id] = r + new_replica_id_set.add(r.replica_id) + + if self._replica_id_set != new_replica_id_set: + replica_id_set_strs = {r.unique_id for r in new_replica_id_set} + logger.info( + f"Got updated replicas for {self._deployment_id}: " + f"{replica_id_set_strs}.", + extra={"log_to_stderr": False}, + ) + + # Get list of new replicas + new_ids = new_replica_id_set - self._replica_id_set + replicas_to_ping = [new_replicas.get(id) for id in new_ids] + + self._replicas = new_replicas + self._replica_id_set = new_replica_id_set + self._replica_queue_len_cache.remove_inactive_replicas( + active_replica_ids=new_replica_id_set + ) + # Populate cache for new replicas + self._event_loop.create_task(self._probe_queue_lens(replicas_to_ping, 0)) + self._replicas_updated_event.set() + self._maybe_start_routing_tasks() + + async def _probe_queue_lens( + self, + replicas: List[RunningReplica], + backoff_index: int, + ) -> List[Tuple[RunningReplica, Optional[int]]]: + """Actively probe the queue length from each of the replicas. + + Sends an RPC to each replica to fetch its queue length, with a response deadline + that increases exponentially in backoff. + + Returns a list of queue lengths in the same order as the replicas passed in. + Replicas whose RPCs fail or don't respond within the deadline will have a queue + length of `None`. Replicas that return a `RayActorError` will be removed from + future consideration for requests. + + This method also updates the local cache of replica queue lengths according to + the responses. + """ + result: List[Tuple[RunningReplica, Optional[int]]] = [] + if len(replicas) == 0: + return result + + # Ensure the max deadline is always >= the initial deadline. + max_queue_len_response_deadline_s = max( + self.queue_len_response_deadline_s, + self.max_queue_len_response_deadline_s, + ) + + try: + queue_len_response_deadline_s = min( + self.queue_len_response_deadline_s * (2**backoff_index), + max_queue_len_response_deadline_s, + ) + except OverflowError: + # self.queue_len_response_deadline_s * (2**backoff_index) + # can overflow if backoff_index gets sufficiently large (e.g. + # 1024 when queue_len_response_deadline_s is 0.1). + queue_len_response_deadline_s = max_queue_len_response_deadline_s + + get_queue_len_tasks = [] + for r in replicas: + t = self._event_loop.create_task( + r.get_queue_len(deadline_s=queue_len_response_deadline_s) + ) + t.replica = r + get_queue_len_tasks.append(t) + + done, pending = await asyncio.wait( + get_queue_len_tasks, + timeout=queue_len_response_deadline_s, + return_when=asyncio.ALL_COMPLETED, + ) + for t in pending: + replica = t.replica + result.append((replica, None)) + t.cancel() + logger.warning( + f"Failed to get queue length from {replica.replica_id} " + f"within {queue_len_response_deadline_s}s. If this happens repeatedly " + "it's likely caused by high network latency in the cluster. You can " + "configure the deadline using the " + "`RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S` environment variable." + ) + + for t in done: + replica = t.replica + if t.exception() is not None: + result.append((replica, None)) + msg = ( + "Failed to fetch queue length for " + f"{replica.replica_id}: '{t.exception()}'" + ) + # If we get an ActorDiedError, the replica actor has died. This + # is not recoverable (the controller will start a new replica in its + # place), so we should no longer consider it for requests. + # We do not catch RayActorError here because that error can be + # raised even when a replica is temporarily unavailable. + # See https://github.com/ray-project/ray/issues/44185 for details. + if isinstance(t.exception(), ActorDiedError): + self.on_replica_actor_died(replica.replica_id) + msg += " This replica will no longer be considered for requests." + # Replica is temporarily unavailable because of network issues, or + # replica has died but GCS is down so ActorUnavailableError will + # be raised until the GCS recovers. For the time being, invalidate + # the cache entry so that we don't try to send requests to this + # replica without actively probing. + elif isinstance(t.exception(), ActorUnavailableError): + self.on_replica_actor_unavailable(replica.replica_id) + msg = ( + "Failed to fetch queue length for " + f"{replica.replica_id}. Replica is temporarily " + "unavailable." + ) + + logger.warning(msg) + else: + queue_len = t.result() + result.append((replica, queue_len)) + self._replica_queue_len_cache.update(replica.replica_id, queue_len) + + assert len(result) == len(replicas) + return result + + async def _select_from_candidate_replicas( + self, + candidates: List[RunningReplica], + backoff_index: int, + ) -> Optional[RunningReplica]: + """Chooses the best replica from the list of candidates. + + If none of the replicas can be routed, returns `None`. + + The queue length for each replica is first looked up in the local cache. If not + present in the cache, the replica will be actively probed and the cache updated. + + Among replicas that respond within the deadline and don't have full queues, the + one with the lowest queue length is chosen. + """ + lowest_queue_len = math.inf + chosen_replica_id: Optional[str] = None + not_in_cache: List[RunningReplica] = [] + if self._use_replica_queue_len_cache: + # Populate available queue lens from the cache. + for r in candidates: + queue_len = self._replica_queue_len_cache.get(r.replica_id) + # Include replicas whose queues are full as not in the cache so we will + # actively probe them. Otherwise we may end up in "deadlock" until their + # cache entries expire. + if queue_len is None or queue_len >= r.max_ongoing_requests: + not_in_cache.append(r) + elif queue_len < lowest_queue_len: + lowest_queue_len = queue_len + chosen_replica_id = r.replica_id + else: + not_in_cache = candidates + + # If there is a valid replica to route based on the information in the + # cache, route it. Else fall back to actively probing. + if chosen_replica_id is None: + for r, queue_len in await self._probe_queue_lens( + not_in_cache, + backoff_index, + ): + if queue_len is None: + # None is returned if we failed to get the queue len. + continue + + if queue_len < r.max_ongoing_requests and queue_len < lowest_queue_len: + lowest_queue_len = queue_len + chosen_replica_id = r.replica_id + elif len(not_in_cache) > 0: + # If there are replicas without a valid cache entry, probe them in the + # background to populate the cache. + self._event_loop.create_task( + self._probe_queue_lens(not_in_cache, backoff_index) + ) + + # `self._replicas` may have been updated since the candidates were chosen. + # In that case, return `None` so a new one is selected. + return self._replicas.get(chosen_replica_id, None) + + def _get_pending_request_matching_internal_request_id( + self, + request_metadata: Optional[RequestMetadata] = None, + ) -> Optional[PendingRequest]: + """Get the pending request that matches on the internal request id. + + If no request metadata is provided or no request is found that matches + the internal request ID, return None. + """ + if request_metadata is None: + return None + + for pr in self._pending_requests_to_fulfill: + if ( + not pr.future.done() + and pr.metadata.internal_request_id + == request_metadata.internal_request_id + ): + return pr + + return None + + def _fulfill_next_pending_request( + self, + replica: RunningReplica, + request_metadata: Optional[RequestMetadata] = None, + ): + """Assign the replica to the next pending request, potentially not in + order of when the request arrived. + + If a pending request has been cancelled, it will be popped from the queue + and not assigned. + """ + # Find the pending request that matches exactly. + matched_pending_request = ( + self._get_pending_request_matching_internal_request_id(request_metadata) + ) + if matched_pending_request is not None: + matched_pending_request.future.set_result(replica) + self._pending_requests_to_fulfill.remove(matched_pending_request) + return + + def _get_next_pending_request_to_route( + self, + ) -> Optional[PendingRequest]: + while len(self._pending_requests_to_route) > 0: + pr = self._pending_requests_to_route.popleft() + if not pr.future.done(): + return pr + + return None + + async def _choose_replicas_with_backoff( + self, + pending_request: Optional[PendingRequest] = None, + ) -> AsyncGenerator[List[RunningReplica], None]: + """Generator that repeatedly chooses available replicas. + In the first iteration, only replicas colocated on the same node as this router + will be considered. If those are occupied, the full set of replicas will be + considered on subsequent iterations. + After each iteration, there will be an increasing backoff sleep time (dictated + by `initial_backoff_s` and `backoff_multiplier`). The caller should exit the + generator to reset the backoff sleep time. + """ + entered_backoff = False + try: + attempt = 0 + + while True: + # If no replicas are available, wait until `update_replicas` is called. + while len(self._replicas) == 0: + logger.info( + "No replicas are currently available for " + f"{self._deployment_id}.", + extra={"log_to_stderr": False}, + ) + self._replicas_updated_event.clear() + await self._replicas_updated_event.wait() + logger.info( + f"New replicas are available for {self._deployment_id}, " + "attempting to route queued requests.", + extra={"log_to_stderr": False}, + ) + + replica_ranks = list(self._replicas.values()) + chosen_replicas: List[ + List[RunningReplica] + ] = await self.choose_replicas( + candidate_replicas=replica_ranks, + pending_request=pending_request, + ) + for replicas in chosen_replicas: + if replicas: + yield replicas + + # We have a slight unintended behavior when enabled locality routing + # for both node and AZ. The intention is to try same node first, + # then try same AZ if node fails, then try everything else until a + # replica is found. These sequence should only help to reduce the + # latency of the request. No backoff and sleep should be applied, until + # we have fall into the case trying on all available replicas. + if not pending_request.routing_context.should_backoff: + continue + + if not entered_backoff: + entered_backoff = True + self.num_routing_tasks_in_backoff += 1 + self.num_routing_tasks_in_backoff_gauge.set( + self.num_routing_tasks_in_backoff + ) + else: + # Only backoff after the first retry. + backoff_s = min( + self.initial_backoff_s * self.backoff_multiplier**attempt, + self.max_backoff_s, + ) + await asyncio.sleep(backoff_s) + attempt += 1 + finally: + if entered_backoff: + self.num_routing_tasks_in_backoff -= 1 + self.num_routing_tasks_in_backoff_gauge.set( + self.num_routing_tasks_in_backoff + ) + + async def _fulfill_pending_requests(self): + """Repeatedly tries to fulfill a pending request with an available replica. + + This is expected to be run inside a task in self._routing_tasks. + + When a replica is found, this method will exit if the number of routing tasks + has exceeded the target number. Else it will loop again to route another + replica. + """ + try: + while len(self._routing_tasks) <= self.target_num_routing_tasks: + start_time = time.time() + backoff_index = 0 + pending_request = self._get_next_pending_request_to_route() + request_metadata = pending_request.metadata if pending_request else None + async for candidates in self._choose_replicas_with_backoff( + pending_request + ): + # Clear out pending requests at the front of the + # queue that have been cancelled, then reevaluate + # if we need to continue this routing task. + while ( + len(self._pending_requests_to_fulfill) > 0 + and self._pending_requests_to_fulfill[0].future.done() + ): + self._pending_requests_to_fulfill.popleft() + + if len(self._routing_tasks) > self.target_num_routing_tasks: + break + + replica = await self._select_from_candidate_replicas( + candidates, backoff_index + ) + if replica is not None: + self._fulfill_next_pending_request(replica, request_metadata) + break + + backoff_index += 1 + if backoff_index >= 50 and backoff_index % 50 == 0: + routing_time_elapsed = time.time() - start_time + warning_log = ( + "Failed to route request after " + f"{backoff_index} attempts over " + f"{routing_time_elapsed:.2f}s. Retrying." + ) + if request_metadata is not None: + warning_log += ( + f" Request ID: {request_metadata.request_id}." + ) + if request_metadata.multiplexed_model_id: + warning_log += ( + " Multiplexed model ID: " + f"{request_metadata.multiplexed_model_id}." + ) + logger.warning(warning_log) + + except Exception: + logger.exception("Unexpected error in _fulfill_pending_requests.") + finally: + self._routing_tasks.remove(asyncio.current_task(loop=self._event_loop)) + self.num_routing_tasks_gauge.set(self.curr_num_routing_tasks) + + def _maybe_start_routing_tasks(self): + """Start routing tasks to fulfill pending requests if necessary. + + Starts tasks so that there is at least one task per pending request + (respecting the max number of routing tasks). + + In the common case, this will start a single task when a new request comes + in for routing. However, in cases where the number of available replicas + is updated or a task exits unexpectedly, we may need to start multiple. + """ + tasks_to_start = self.target_num_routing_tasks - self.curr_num_routing_tasks + for _ in range(tasks_to_start): + self._routing_tasks.add( + self._event_loop.create_task(self._fulfill_pending_requests()) + ) + if tasks_to_start > 0: + self.num_routing_tasks_gauge.set(self.curr_num_routing_tasks) + + async def _choose_replica_for_request( + self, pending_request: PendingRequest, *, is_retry: bool = False + ) -> RunningReplica: + """Chooses a replica to send the provided request to. + + Upon cancellation (by the caller), the future is cancelled and will be passed + over when a replica becomes available. + """ + try: + if not is_retry: + self._pending_requests_to_fulfill.append(pending_request) + self._pending_requests_to_route.append(pending_request) + else: + pending_request.reset_future() + index = 0 + for pr in self._pending_requests_to_fulfill: + if pending_request.created_at < pr.created_at: + break + + index += 1 + + self._pending_requests_to_fulfill.insert(index, pending_request) + + index = 0 + for pr in self._pending_requests_to_route: + if pending_request.created_at < pr.created_at: + break + + index += 1 + + self._pending_requests_to_route.insert(index, pending_request) + + self._maybe_start_routing_tasks() + replica = await pending_request.future + except asyncio.CancelledError as e: + pending_request.future.cancel() + + raise e from None + + return replica + + def _update_running_replicas(self, running_replicas: List[RunningReplicaInfo]): + """Compatibility shim for RunningReplicaInfo datatype.""" + return self.update_replicas( + [self.create_replica_wrapper(r) for r in running_replicas] + ) + + def select_available_replicas( + self, candidates: Optional[List[RunningReplica]] = None + ) -> List[RunningReplica]: + """Select available replicas from the list of candidates. + + This method is used to select replicas that are available to take more + requests based on the queue length cache. If the queue length is not + available in the cache, the replica is considered available. It does + not actively probe the replicas for their queue length. + + If input candidates is `None`, all replicas are considered. + """ + if candidates is None: + candidates = list(self._replicas.values()) + + available_replicas = [] + for r in candidates: + queue_len = self._replica_queue_len_cache.get(r.replica_id) + if queue_len is None or queue_len < r.max_ongoing_requests: + available_replicas.append(r) + + return available_replicas + + @abstractmethod + async def choose_replicas( + self, + candidate_replicas: List[RunningReplica], + pending_request: Optional[PendingRequest] = None, + ) -> List[List[RunningReplica]]: + """Chooses a subset of candidate replicas from available replicas. + + This is the main function each request router should implement to + decide which replica to send the request to. This is one iteration of + replica selection. + + Args: + candidate_replicas: A list of candidate replicas to be considered in the + policy. + pending_request: The request to be routed. This is used to + determine which replicas are eligible for routing. + + Returns: + A list of lists of replicas, where each inner list represents a + rank of replicas. The first rank is the most preferred and the last + rank is the least preferred. + """ + pass + + def on_request_routed( + self, + pending_request: PendingRequest, + replica_id: ReplicaID, + result: ReplicaResult, + ): + """Called when a request is routed to a replica. + + This is used as a callback to update the state of the request router + after a response is generated. + """ + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/router.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/router.py new file mode 100644 index 0000000000000000000000000000000000000000..82f90674184b4e0f8b559fe15b6c7a791044df82 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/router.py @@ -0,0 +1,1038 @@ +import asyncio +import concurrent.futures +import logging +import threading +import time +import weakref +from abc import ABC, abstractmethod +from asyncio import AbstractEventLoop +from collections import defaultdict +from collections.abc import MutableMapping +from contextlib import contextmanager +from functools import lru_cache, partial +from typing import ( + Any, + Callable, + Coroutine, + DefaultDict, + Dict, + List, + Optional, + Union, +) + +import ray +from ray.actor import ActorHandle +from ray.exceptions import ActorDiedError, ActorUnavailableError, RayError +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + DeploymentTargetInfo, + ReplicaID, + RequestMetadata, + RunningReplicaInfo, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE, + RAY_SERVE_HANDLE_AUTOSCALING_METRIC_PUSH_INTERVAL_S, + RAY_SERVE_HANDLE_AUTOSCALING_METRIC_RECORD_INTERVAL_S, + RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING, + SERVE_LOGGER_NAME, +) +from ray.serve._private.long_poll import LongPollClient, LongPollNamespace +from ray.serve._private.metrics_utils import InMemoryMetricsStore, MetricsPusher +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.request_router import PendingRequest, RequestRouter +from ray.serve._private.request_router.pow_2_router import ( + PowerOfTwoChoicesRequestRouter, +) +from ray.serve._private.request_router.replica_wrapper import RunningReplica +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + generate_request_id, + resolve_deployment_response, + run_coroutine_or_future_threadsafe, +) +from ray.serve.config import AutoscalingConfig +from ray.serve.exceptions import BackPressureError, DeploymentUnavailableError +from ray.util import metrics + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +QUEUED_REQUESTS_KEY = "queued" + + +class RouterMetricsManager: + """Manages metrics for the router.""" + + PUSH_METRICS_TO_CONTROLLER_TASK_NAME = "push_metrics_to_controller" + RECORD_METRICS_TASK_NAME = "record_metrics" + + def __init__( + self, + deployment_id: DeploymentID, + handle_id: str, + self_actor_id: str, + handle_source: DeploymentHandleSource, + controller_handle: ActorHandle, + router_requests_counter: metrics.Counter, + queued_requests_gauge: metrics.Gauge, + running_requests_gauge: metrics.Gauge, + ): + self._handle_id = handle_id + self._deployment_id = deployment_id + self._self_actor_id = self_actor_id + self._handle_source = handle_source + self._controller_handle = controller_handle + + # Exported metrics + self.num_router_requests = router_requests_counter + self.num_router_requests.set_default_tags( + { + "deployment": deployment_id.name, + "application": deployment_id.app_name, + "handle": self._handle_id, + "actor_id": self._self_actor_id, + } + ) + + self.num_queued_requests = 0 + self.num_queued_requests_gauge = queued_requests_gauge + self.num_queued_requests_gauge.set_default_tags( + { + "deployment": deployment_id.name, + "application": deployment_id.app_name, + "handle": self._handle_id, + "actor_id": self._self_actor_id, + } + ) + self.num_queued_requests_gauge.set(0) + + # Track queries sent to replicas for the autoscaling algorithm. + self.num_requests_sent_to_replicas: DefaultDict[ReplicaID, int] = defaultdict( + int + ) + self.num_running_requests_gauge = running_requests_gauge + self.num_running_requests_gauge.set_default_tags( + { + "deployment": deployment_id.name, + "application": deployment_id.app_name, + "handle": self._handle_id, + "actor_id": self._self_actor_id, + } + ) + # We use Ray object ref callbacks to update state when tracking + # number of requests running on replicas. The callbacks will be + # called from a C++ thread into the router's async event loop, + # so non-atomic read and write operations need to be guarded by + # this thread-safe lock. + self._queries_lock = threading.Lock() + # Regularly aggregate and push autoscaling metrics to controller + self.metrics_pusher = MetricsPusher() + self.metrics_store = InMemoryMetricsStore() + # The config for the deployment this router sends requests to will be broadcast + # by the controller. That means it is not available until we get the first + # update. This includes an optional autoscaling config. + self._deployment_config: Optional[DeploymentConfig] = None + # Track whether the metrics manager has been shutdown + self._shutdown: bool = False + + @contextmanager + def wrap_request_assignment(self, request_meta: RequestMetadata): + max_queued_requests = ( + self._deployment_config.max_queued_requests + if self._deployment_config is not None + else -1 + ) + if ( + max_queued_requests != -1 + and self.num_queued_requests >= max_queued_requests + ): + # Due to the async nature of request handling, we may reject more requests + # than strictly necessary. This is more likely to happen during + # high concurrency. Here's why: + # + # When multiple requests arrive simultaneously with max_queued_requests=1: + # 1. First request increments num_queued_requests to 1 + # 2. Before that request gets assigned to a replica and decrements the counter, + # we yield to the event loop + # 3. Other requests see num_queued_requests=1 and get rejected, even though + # the first request will soon free up the queue slot + # + # For example, with max_queued_requests=1 and 4 simultaneous requests: + # - Request 1 gets queued (num_queued_requests=1) + # - Requests 2,3,4 get rejected since queue appears full + # - Request 1 gets assigned and frees queue slot (num_queued_requests=0) + # - But we already rejected Request 2 which could have been queued + e = BackPressureError( + num_queued_requests=self.num_queued_requests, + max_queued_requests=max_queued_requests, + ) + logger.warning(e.message) + raise e + + self.inc_num_total_requests(request_meta.route) + yield + + @contextmanager + def wrap_queued_request(self, is_retry: bool, num_curr_replicas: int): + """Increment queued requests gauge and maybe push autoscaling metrics to controller.""" + try: + self.inc_num_queued_requests() + # Optimization: if there are currently zero replicas for a deployment, + # push handle metric to controller to allow for fast cold start time. + # Only do this on the first attempt to route the request. + if not is_retry and self.should_send_scaled_to_zero_optimized_push( + curr_num_replicas=num_curr_replicas + ): + self.push_autoscaling_metrics_to_controller() + + yield + finally: + # If the request is disconnected before assignment, this coroutine + # gets cancelled by the caller and an asyncio.CancelledError is + # raised. The finally block ensures that num_queued_requests + # is correctly decremented in this case. + self.dec_num_queued_requests() + + def _update_running_replicas(self, running_replicas: List[RunningReplicaInfo]): + """Prune list of replica ids in self.num_queries_sent_to_replicas. + + We want to avoid self.num_queries_sent_to_replicas from growing + in memory as the deployment upscales and downscales over time. + """ + + running_replica_set = {replica.replica_id for replica in running_replicas} + with self._queries_lock: + self.num_requests_sent_to_replicas = defaultdict( + int, + { + id: self.num_requests_sent_to_replicas[id] + for id, num_queries in self.num_requests_sent_to_replicas.items() + if num_queries or id in running_replica_set + }, + ) + + @property + def autoscaling_config(self) -> Optional[AutoscalingConfig]: + if self._deployment_config is None: + return None + + return self._deployment_config.autoscaling_config + + def update_deployment_config( + self, deployment_config: DeploymentConfig, curr_num_replicas: int + ): + """Update the config for the deployment this router sends requests to.""" + + if self._shutdown: + return + + self._deployment_config = deployment_config + + # Start the metrics pusher if autoscaling is enabled. + autoscaling_config = self.autoscaling_config + if autoscaling_config: + self.metrics_pusher.start() + # Optimization for autoscaling cold start time. If there are + # currently 0 replicas for the deployment, and there is at + # least one queued request on this router, then immediately + # push handle metric to the controller. + if self.should_send_scaled_to_zero_optimized_push(curr_num_replicas): + self.push_autoscaling_metrics_to_controller() + + if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: + # Record number of queued + ongoing requests at regular + # intervals into the in-memory metrics store + self.metrics_pusher.register_or_update_task( + self.RECORD_METRICS_TASK_NAME, + self._add_autoscaling_metrics_point, + min( + RAY_SERVE_HANDLE_AUTOSCALING_METRIC_RECORD_INTERVAL_S, + autoscaling_config.metrics_interval_s, + ), + ) + # Push metrics to the controller periodically. + self.metrics_pusher.register_or_update_task( + self.PUSH_METRICS_TO_CONTROLLER_TASK_NAME, + self.push_autoscaling_metrics_to_controller, + autoscaling_config.metrics_interval_s, + ) + else: + self.metrics_pusher.register_or_update_task( + self.PUSH_METRICS_TO_CONTROLLER_TASK_NAME, + self.push_autoscaling_metrics_to_controller, + RAY_SERVE_HANDLE_AUTOSCALING_METRIC_PUSH_INTERVAL_S, + ) + + else: + if self.metrics_pusher: + self.metrics_pusher.stop_tasks() + + def inc_num_total_requests(self, route: str): + self.num_router_requests.inc(tags={"route": route}) + + def inc_num_queued_requests(self): + self.num_queued_requests += 1 + self.num_queued_requests_gauge.set(self.num_queued_requests) + + def dec_num_queued_requests(self): + self.num_queued_requests -= 1 + self.num_queued_requests_gauge.set(self.num_queued_requests) + + def inc_num_running_requests_for_replica(self, replica_id: ReplicaID): + with self._queries_lock: + self.num_requests_sent_to_replicas[replica_id] += 1 + self.num_running_requests_gauge.set( + sum(self.num_requests_sent_to_replicas.values()) + ) + + def dec_num_running_requests_for_replica(self, replica_id: ReplicaID): + with self._queries_lock: + self.num_requests_sent_to_replicas[replica_id] -= 1 + self.num_running_requests_gauge.set( + sum(self.num_requests_sent_to_replicas.values()) + ) + + def should_send_scaled_to_zero_optimized_push(self, curr_num_replicas: int) -> bool: + return ( + self.autoscaling_config is not None + and curr_num_replicas == 0 + and self.num_queued_requests > 0 + ) + + def push_autoscaling_metrics_to_controller(self): + """Pushes queued and running request metrics to the controller. + + These metrics are used by the controller for autoscaling. + """ + + self._controller_handle.record_handle_metrics.remote( + send_timestamp=time.time(), + deployment_id=self._deployment_id, + handle_id=self._handle_id, + actor_id=self._self_actor_id, + handle_source=self._handle_source, + **self._get_aggregated_requests(), + ) + + def _add_autoscaling_metrics_point(self): + """Adds metrics point for queued and running requests at replicas. + + Also prunes keys in the in memory metrics store with outdated datapoints. + """ + + timestamp = time.time() + self.metrics_store.add_metrics_point( + {QUEUED_REQUESTS_KEY: self.num_queued_requests}, timestamp + ) + if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: + self.metrics_store.add_metrics_point( + self.num_requests_sent_to_replicas, timestamp + ) + + # Prevent in memory metrics store memory from growing + start_timestamp = time.time() - self.autoscaling_config.look_back_period_s + self.metrics_store.prune_keys_and_compact_data(start_timestamp) + + def _get_aggregated_requests(self): + running_requests = dict() + if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE and self.autoscaling_config: + look_back_period = self.autoscaling_config.look_back_period_s + running_requests = { + replica_id: self.metrics_store.window_average( + replica_id, time.time() - look_back_period + ) + # If data hasn't been recorded yet, return current + # number of queued and ongoing requests. + or num_requests + for replica_id, num_requests in self.num_requests_sent_to_replicas.items() # noqa: E501 + } + + return { + "queued_requests": self.num_queued_requests, + "running_requests": running_requests, + } + + async def shutdown(self): + """Shutdown metrics manager gracefully.""" + + if self.metrics_pusher: + await self.metrics_pusher.graceful_shutdown() + + self._shutdown = True + + +class Router(ABC): + @abstractmethod + def running_replicas_populated(self) -> bool: + pass + + @abstractmethod + def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> concurrent.futures.Future[ReplicaResult]: + pass + + @abstractmethod + def shutdown(self) -> concurrent.futures.Future: + pass + + +async def create_event() -> asyncio.Event: + """Helper to create an asyncio event in the current event loop.""" + return asyncio.Event() + + +class AsyncioRouter: + def __init__( + self, + controller_handle: ActorHandle, + deployment_id: DeploymentID, + handle_id: str, + self_actor_id: str, + handle_source: DeploymentHandleSource, + event_loop: asyncio.BaseEventLoop, + enable_strict_max_ongoing_requests: bool, + node_id: str, + availability_zone: Optional[str], + prefer_local_node_routing: bool, + resolve_request_arg_func: Coroutine = resolve_deployment_response, + request_router_class: Optional[Callable] = None, + request_router_kwargs: Optional[Dict[str, Any]] = None, + request_router: Optional[RequestRouter] = None, + _request_router_initialized_event: Optional[asyncio.Event] = None, + ): + """Used to assign requests to downstream replicas for a deployment. + + The routing behavior is delegated to a RequestRouter; this is a thin + wrapper that adds metrics and logging. + """ + self._controller_handle = controller_handle + self.deployment_id = deployment_id + self._self_actor_id = self_actor_id + self._handle_source = handle_source + self._event_loop = event_loop + self._request_router_class = request_router_class + self._request_router_kwargs = ( + request_router_kwargs if request_router_kwargs else {} + ) + self._enable_strict_max_ongoing_requests = enable_strict_max_ongoing_requests + self._node_id = node_id + self._availability_zone = availability_zone + self._prefer_local_node_routing = prefer_local_node_routing + # By default, deployment is available unless we receive news + # otherwise through a long poll broadcast from the controller. + self._deployment_available = True + + # The request router will be lazy loaded to decouple form the initialization. + self._request_router: Optional[RequestRouter] = request_router + + if _request_router_initialized_event: + self._request_router_initialized = _request_router_initialized_event + else: + future = asyncio.run_coroutine_threadsafe(create_event(), self._event_loop) + self._request_router_initialized = future.result() + + if self._request_router: + self._request_router_initialized.set() + self._resolve_request_arg_func = resolve_request_arg_func + self._running_replicas: Optional[List[RunningReplicaInfo]] = None + + # Flipped to `True` once the router has received a non-empty + # replica set at least once. + self._running_replicas_populated: bool = False + + # Initializing `self._metrics_manager` before `self.long_poll_client` is + # necessary to avoid race condition where `self.update_deployment_config()` + # might be called before `self._metrics_manager` instance is created. + self._metrics_manager = RouterMetricsManager( + deployment_id, + handle_id, + self_actor_id, + handle_source, + controller_handle, + metrics.Counter( + "serve_num_router_requests", + description="The number of requests processed by the router.", + tag_keys=("deployment", "route", "application", "handle", "actor_id"), + ), + metrics.Gauge( + "serve_deployment_queued_queries", + description=( + "The current number of queries to this deployment waiting" + " to be assigned to a replica." + ), + tag_keys=("deployment", "application", "handle", "actor_id"), + ), + metrics.Gauge( + "serve_num_ongoing_requests_at_replicas", + description=( + "The current number of requests to this deployment that " + "have been submitted to a replica." + ), + tag_keys=("deployment", "application", "handle", "actor_id"), + ), + ) + + # The Router needs to stay informed about changes to the target deployment's + # running replicas and deployment config. We do this via the long poll system. + # However, for efficiency, we don't want to create a LongPollClient for every + # DeploymentHandle, so we use a shared LongPollClient that all Routers + # register themselves with. But first, the router needs to get a fast initial + # update so that it can start serving requests, which we do with a dedicated + # LongPollClient that stops running once the shared client takes over. + + self.long_poll_client = LongPollClient( + controller_handle, + { + ( + LongPollNamespace.DEPLOYMENT_TARGETS, + deployment_id, + ): self.update_deployment_targets, + ( + LongPollNamespace.DEPLOYMENT_CONFIG, + deployment_id, + ): self.update_deployment_config, + }, + call_in_event_loop=self._event_loop, + ) + + shared = SharedRouterLongPollClient.get_or_create( + controller_handle, self._event_loop + ) + shared.register(self) + + @property + def request_router(self) -> Optional[RequestRouter]: + """Get and lazy loading request router. + + If the request_router_class not provided, and the request router is not + yet initialized, then it will return None. Otherwise, if request router + is not yet initialized, it will be initialized and returned. Also, + setting `self._request_router_initialized` to signal that the request + router is initialized. + """ + if not self._request_router and self._request_router_class: + request_router = self._request_router_class( + deployment_id=self.deployment_id, + handle_source=self._handle_source, + self_node_id=self._node_id, + self_actor_id=self._self_actor_id, + self_actor_handle=ray.get_runtime_context().current_actor + if ray.get_runtime_context().get_actor_id() + else None, + # Streaming ObjectRefGenerators are not supported in Ray Client + use_replica_queue_len_cache=self._enable_strict_max_ongoing_requests, + create_replica_wrapper_func=lambda r: RunningReplica(r), + prefer_local_node_routing=self._prefer_local_node_routing, + prefer_local_az_routing=RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING, + self_availability_zone=self._availability_zone, + ) + request_router.initialize_state(**(self._request_router_kwargs)) + + # Populate the running replicas if they are already available. + if self._running_replicas is not None: + request_router._update_running_replicas(self._running_replicas) + + self._request_router = request_router + self._request_router_initialized.set() + + # Log usage telemetry to indicate that custom request router + # feature is being used in this cluster. + if self._request_router_class is not PowerOfTwoChoicesRequestRouter: + ServeUsageTag.CUSTOM_REQUEST_ROUTER_USED.record("1") + return self._request_router + + def running_replicas_populated(self) -> bool: + return self._running_replicas_populated + + def update_deployment_targets(self, deployment_target_info: DeploymentTargetInfo): + self._deployment_available = deployment_target_info.is_available + + running_replicas = deployment_target_info.running_replicas + if self.request_router: + self.request_router._update_running_replicas(running_replicas) + else: + # In this case, the request router hasn't been initialized yet. + # Store the running replicas so that we can update the request + # router once it is initialized. + self._running_replicas = running_replicas + self._metrics_manager._update_running_replicas(running_replicas) + + if running_replicas: + self._running_replicas_populated = True + + def update_deployment_config(self, deployment_config: DeploymentConfig): + self._request_router_class = ( + deployment_config.request_router_config.get_request_router_class() + ) + self._request_router_kwargs = ( + deployment_config.request_router_config.request_router_kwargs + ) + self._metrics_manager.update_deployment_config( + deployment_config, + curr_num_replicas=len(self.request_router.curr_replicas), + ) + + async def _resolve_request_arguments( + self, + pr: PendingRequest, + ) -> None: + """Asynchronously resolve and replace top-level request args and kwargs.""" + if pr.resolved: + return + + new_args = list(pr.args) + new_kwargs = pr.kwargs.copy() + + # Map from index -> task for resolving positional arg + resolve_arg_tasks = {} + for i, obj in enumerate(pr.args): + task = await self._resolve_request_arg_func(obj, pr.metadata) + if task is not None: + resolve_arg_tasks[i] = task + + # Map from key -> task for resolving key-word arg + resolve_kwarg_tasks = {} + for k, obj in pr.kwargs.items(): + task = await self._resolve_request_arg_func(obj, pr.metadata) + if task is not None: + resolve_kwarg_tasks[k] = task + + # Gather all argument resolution tasks concurrently. + if resolve_arg_tasks or resolve_kwarg_tasks: + all_tasks = list(resolve_arg_tasks.values()) + list( + resolve_kwarg_tasks.values() + ) + await asyncio.wait(all_tasks) + + # Update new args and new kwargs with resolved arguments + for index, task in resolve_arg_tasks.items(): + new_args[index] = task.result() + for key, task in resolve_kwarg_tasks.items(): + new_kwargs[key] = task.result() + + pr.args = new_args + pr.kwargs = new_kwargs + pr.resolved = True + + def _process_finished_request( + self, + replica_id: ReplicaID, + parent_request_id: str, + response_id: str, + result: Union[Any, RayError], + ): + self._metrics_manager.dec_num_running_requests_for_replica(replica_id) + if isinstance(result, ActorDiedError): + # Replica has died but controller hasn't notified the router yet. + # Don't consider this replica for requests in the future, and retry + # routing request. + if self.request_router: + self.request_router.on_replica_actor_died(replica_id) + logger.warning( + f"{replica_id} will not be considered for future " + "requests because it has died." + ) + elif isinstance(result, ActorUnavailableError): + # There are network issues, or replica has died but GCS is down so + # ActorUnavailableError will be raised until GCS recovers. For the + # time being, invalidate the cache entry so that we don't try to + # send requests to this replica without actively probing, and retry + # routing request. + if self.request_router: + self.request_router.on_replica_actor_unavailable(replica_id) + logger.warning( + f"Request failed because {replica_id} is temporarily unavailable." + ) + + async def _route_and_send_request_once( + self, + pr: PendingRequest, + response_id: str, + is_retry: bool, + ) -> Optional[ReplicaResult]: + result: Optional[ReplicaResult] = None + replica: Optional[RunningReplica] = None + try: + num_curr_replicas = len(self.request_router.curr_replicas) + with self._metrics_manager.wrap_queued_request(is_retry, num_curr_replicas): + # If the pending request is uninitialized, we do so by resolving the + # request arguments. This should only be done once per request, and + # should happen after incrementing `num_queued_requests`, so that Serve + # can upscale the downstream deployment while arguments are resolving. + if not pr.resolved: + await self._resolve_request_arguments(pr) + + replica = await self.request_router._choose_replica_for_request( + pr, is_retry=is_retry + ) + + # If the queue len cache is disabled or we're sending a request to Java, + # then directly send the query and hand the response back. The replica will + # never reject requests in this code path. + with_rejection = ( + self._enable_strict_max_ongoing_requests + and not replica.is_cross_language + ) + result = replica.try_send_request(pr, with_rejection=with_rejection) + + # Proactively update the queue length cache. + self.request_router.on_send_request(replica.replica_id) + + # Keep track of requests that have been sent out to replicas + if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: + _request_context = ray.serve.context._get_serve_request_context() + request_id: str = _request_context.request_id + self._metrics_manager.inc_num_running_requests_for_replica( + replica.replica_id + ) + callback = partial( + self._process_finished_request, + replica.replica_id, + request_id, + response_id, + ) + result.add_done_callback(callback) + + if not with_rejection: + return result + + queue_info = await result.get_rejection_response() + self.request_router.on_new_queue_len_info(replica.replica_id, queue_info) + if queue_info.accepted: + self.request_router.on_request_routed(pr, replica.replica_id, result) + return result + + except asyncio.CancelledError: + # NOTE(edoakes): this is not strictly necessary because there are + # currently no `await` statements between getting the ref and returning, + # but I'm adding it defensively. + if result is not None: + result.cancel() + + raise + except ActorDiedError: + # Replica has died but controller hasn't notified the router yet. + # Don't consider this replica for requests in the future, and retry + # routing request. + if replica is not None: + self.request_router.on_replica_actor_died(replica.replica_id) + logger.warning( + f"{replica.replica_id} will not be considered for future " + "requests because it has died." + ) + except ActorUnavailableError: + # There are network issues, or replica has died but GCS is down so + # ActorUnavailableError will be raised until GCS recovers. For the + # time being, invalidate the cache entry so that we don't try to + # send requests to this replica without actively probing, and retry + # routing request. + if replica is not None: + self.request_router.on_replica_actor_unavailable(replica.replica_id) + logger.warning(f"{replica.replica_id} is temporarily unavailable.") + + return None + + async def route_and_send_request( + self, + pr: PendingRequest, + response_id: str, + ) -> ReplicaResult: + """Choose a replica for the request and send it. + + This will block indefinitely if no replicas are available to handle the + request, so it's up to the caller to time out or cancel the request. + """ + # Wait for the router to be initialized before sending the request. + await self._request_router_initialized.wait() + + is_retry = False + while True: + result = await self._route_and_send_request_once( + pr, + response_id, + is_retry, + ) + if result is not None: + return result + + # If the replica rejects the request, retry the routing process. The + # request will be placed on the front of the queue to avoid tail latencies. + # TODO(edoakes): this retry procedure is not perfect because it'll reset the + # process of choosing candidates replicas (i.e., for locality-awareness). + is_retry = True + + async def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> ReplicaResult: + """Assign a request to a replica and return the resulting object_ref.""" + + if not self._deployment_available: + raise DeploymentUnavailableError(self.deployment_id) + + response_id = generate_request_id() + assign_request_task = asyncio.current_task() + ray.serve.context._add_request_pending_assignment( + request_meta.internal_request_id, response_id, assign_request_task + ) + assign_request_task.add_done_callback( + lambda _: ray.serve.context._remove_request_pending_assignment( + request_meta.internal_request_id, response_id + ) + ) + + # Wait for the router to be initialized before sending the request. + await self._request_router_initialized.wait() + + with self._metrics_manager.wrap_request_assignment(request_meta): + replica_result = None + try: + replica_result = await self.route_and_send_request( + PendingRequest( + args=list(request_args), + kwargs=request_kwargs, + metadata=request_meta, + ), + response_id, + ) + return replica_result + except asyncio.CancelledError: + # NOTE(edoakes): this is not strictly necessary because + # there are currently no `await` statements between + # getting the ref and returning, but I'm adding it defensively. + if replica_result is not None: + replica_result.cancel() + + raise + + async def shutdown(self): + await self._metrics_manager.shutdown() + + +class SingletonThreadRouter(Router): + """Wrapper class that runs an AsyncioRouter on a separate thread. + + The motivation for this is to avoid user code blocking the event loop and + preventing the router from making progress. + + Maintains a singleton event loop running in a daemon thread that is shared by + all AsyncioRouters. + """ + + _asyncio_loop: Optional[asyncio.AbstractEventLoop] = None + _asyncio_loop_creation_lock = threading.Lock() + + def __init__(self, **passthrough_kwargs): + assert ( + "event_loop" not in passthrough_kwargs + ), "SingletonThreadRouter manages the router event loop." + + self._asyncio_router = AsyncioRouter( + event_loop=self._get_singleton_asyncio_loop(), **passthrough_kwargs + ) + + @classmethod + def _get_singleton_asyncio_loop(cls) -> asyncio.AbstractEventLoop: + """Get singleton asyncio loop running in a daemon thread. + + This method is thread safe. + """ + with cls._asyncio_loop_creation_lock: + if cls._asyncio_loop is None: + cls._asyncio_loop = asyncio.new_event_loop() + thread = threading.Thread( + daemon=True, + target=cls._asyncio_loop.run_forever, + ) + thread.start() + + return cls._asyncio_loop + + def running_replicas_populated(self) -> bool: + return self._asyncio_router.running_replicas_populated() + + def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> concurrent.futures.Future[ReplicaResult]: + """Routes assign_request call on the internal asyncio loop. + + This method uses `run_coroutine_threadsafe` to execute the actual request + assignment logic (`_asyncio_router.assign_request`) on the dedicated + asyncio event loop thread. It returns a `concurrent.futures.Future` that + can be awaited or queried from the calling thread. + + Returns: + A concurrent.futures.Future resolving to the ReplicaResult representing + the assigned request. + """ + + def asyncio_future_callback( + asyncio_future: asyncio.Future, concurrent_future: concurrent.futures.Future + ): + """Callback attached to the asyncio Task running assign_request. + + This runs when the asyncio Task finishes (completes, fails, or is cancelled). + Its primary goal is to propagate cancellation initiated via the + `concurrent_future` back to the `ReplicaResult` in situations where + asyncio_future didn't see the cancellation event in time. Think of it + like a second line of defense for cancellation of replica results. + """ + # Check if the cancellation originated from the concurrent.futures.Future + if ( + concurrent_future.cancelled() + and not asyncio_future.cancelled() + and asyncio_future.exception() is None + ): + result: ReplicaResult = asyncio_future.result() + logger.info( + "Asyncio task completed despite cancellation attempt. " + "Attempting to cancel the request that was assigned to a replica." + ) + result.cancel() + + task = self._asyncio_loop.create_task( + self._asyncio_router.assign_request( + request_meta, *request_args, **request_kwargs + ) + ) + # Route the actual request assignment coroutine on the asyncio loop thread. + concurrent_future = run_coroutine_or_future_threadsafe( + task, + loop=self._asyncio_loop, + ) + task.add_done_callback(lambda _: asyncio_future_callback(_, concurrent_future)) + return concurrent_future + + def shutdown(self) -> concurrent.futures.Future: + return asyncio.run_coroutine_threadsafe( + self._asyncio_router.shutdown(), loop=self._asyncio_loop + ) + + +class SharedRouterLongPollClient: + def __init__(self, controller_handle: ActorHandle, event_loop: AbstractEventLoop): + self.controller_handler = controller_handle + self.event_loop = event_loop + + # We use a WeakSet to store the Routers so that we don't prevent them + # from being garbage-collected. + self.routers: MutableMapping[ + DeploymentID, weakref.WeakSet[AsyncioRouter] + ] = defaultdict(weakref.WeakSet) + + # Creating the LongPollClient implicitly starts it + self.long_poll_client = LongPollClient( + controller_handle, + key_listeners={}, + call_in_event_loop=self.event_loop, + ) + + @classmethod + @lru_cache(maxsize=None) + def get_or_create( + cls, controller_handle: ActorHandle, event_loop: AbstractEventLoop + ) -> "SharedRouterLongPollClient": + shared = cls(controller_handle=controller_handle, event_loop=event_loop) + logger.info(f"Started {shared}.") + return shared + + def update_deployment_targets( + self, + deployment_target_info: DeploymentTargetInfo, + deployment_id: DeploymentID, + ) -> None: + for router in self.routers[deployment_id]: + router.update_deployment_targets(deployment_target_info) + router.long_poll_client.stop() + + def update_deployment_config( + self, deployment_config: DeploymentConfig, deployment_id: DeploymentID + ) -> None: + for router in self.routers[deployment_id]: + router.update_deployment_config(deployment_config) + router.long_poll_client.stop() + + def register(self, router: AsyncioRouter) -> None: + # We need to run the underlying method in the same event loop that runs + # the long poll loop, because we need to mutate the mapping of routers, + # which are also being iterated over by the key listener callbacks. + # If those happened concurrently in different threads, + # we could get a `RuntimeError: Set changed size during iteration`. + # See https://github.com/ray-project/ray/pull/53613 for more details. + self.event_loop.call_soon_threadsafe(self._register, router) + + def _register(self, router: AsyncioRouter) -> None: + self.routers[router.deployment_id].add(router) + + # Remove the entries for any deployment ids that no longer have any routers. + # The WeakSets will automatically lose track of Routers that get GC'd, + # but the outer dict will keep the key around, so we need to clean up manually. + # Note the list(...) to avoid mutating self.routers while iterating over it. + for deployment_id, routers in list(self.routers.items()): + if not routers: + self.routers.pop(deployment_id) + + # Register the new listeners on the long poll client. + # Some of these listeners may already exist, but it's safe to add them again. + key_listeners = { + (LongPollNamespace.DEPLOYMENT_TARGETS, deployment_id): partial( + self.update_deployment_targets, deployment_id=deployment_id + ) + for deployment_id in self.routers.keys() + } | { + (LongPollNamespace.DEPLOYMENT_CONFIG, deployment_id): partial( + self.update_deployment_config, deployment_id=deployment_id + ) + for deployment_id in self.routers.keys() + } + self.long_poll_client.add_key_listeners(key_listeners) + + +class CurrentLoopRouter(Router): + """Wrapper class that runs an AsyncioRouter on the current asyncio loop. + Note that this class is NOT THREAD-SAFE, and all methods are expected to be + invoked from a single asyncio event loop. + """ + + def __init__(self, **passthrough_kwargs): + assert ( + "event_loop" not in passthrough_kwargs + ), "CurrentLoopRouter uses the current event loop." + + self._asyncio_loop = asyncio.get_running_loop() + self._asyncio_router = AsyncioRouter( + event_loop=self._asyncio_loop, + _request_router_initialized_event=asyncio.Event(), + **passthrough_kwargs, + ) + + def running_replicas_populated(self) -> bool: + return self._asyncio_router.running_replicas_populated() + + def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> asyncio.Future[ReplicaResult]: + return self._asyncio_loop.create_task( + self._asyncio_router.assign_request( + request_meta, *request_args, **request_kwargs + ), + ) + + def shutdown(self) -> asyncio.Future: + return self._asyncio_loop.create_task(self._asyncio_router.shutdown()) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8eab934d1b0896c17acf4109c9751ecebe7c1f18 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/kv_store.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/kv_store.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbc93d6eb422aa5db0688ebea74aff1dcb0863a5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/kv_store.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/kv_store_base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/kv_store_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a334bea1f20d6500e939c2f6c1b7243b9afad897 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/__pycache__/kv_store_base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/kv_store.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/kv_store.py new file mode 100644 index 0000000000000000000000000000000000000000..edca67b596af5e2ac40208143f30bcb1174cf6e1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/kv_store.py @@ -0,0 +1,109 @@ +import logging +from typing import Optional + +import ray +import ray.serve._private.constants as serve_constants +from ray._raylet import GcsClient +from ray.serve._private.storage.kv_store_base import KVStoreBase + +logger = logging.getLogger(serve_constants.SERVE_LOGGER_NAME) + +SERVE_INTERNAL_KV_NAMESPACE = b"serve" + + +def get_storage_key(namespace: str, storage_key: str) -> str: + """In case we need to access kvstore""" + return "{ns}-{key}".format(ns=namespace, key=storage_key) + + +class KVStoreError(Exception): + def __init__(self, rpc_code): + self.rpc_code = rpc_code + + +class RayInternalKVStore(KVStoreBase): + """Wraps ray's internal_kv with a namespace to avoid collisions. + + Supports string keys and bytes values, caller must handle serialization. + """ + + def __init__( + self, + namespace: Optional[str] = None, + gcs_client: Optional[GcsClient] = None, + ): + if namespace is not None and not isinstance(namespace, str): + raise TypeError("namespace must a string, got: {}.".format(type(namespace))) + if gcs_client is not None: + self.gcs_client = gcs_client + else: + self.gcs_client = GcsClient(address=ray.get_runtime_context().gcs_address) + self.timeout = serve_constants.RAY_SERVE_KV_TIMEOUT_S + self.namespace = namespace or "" + + def get_storage_key(self, key: str) -> str: + return "{ns}-{key}".format(ns=self.namespace, key=key) + + def put(self, key: str, val: bytes) -> bool: + """Put the key-value pair into the store. + + Args: + key: The key to store. + val: The value to store. + """ + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + if not isinstance(val, bytes): + raise TypeError("val must be bytes, got: {}.".format(type(val))) + + try: + return self.gcs_client.internal_kv_put( + self.get_storage_key(key).encode(), + val, + overwrite=True, + namespace=SERVE_INTERNAL_KV_NAMESPACE, + timeout=self.timeout, + ) + except ray.exceptions.RpcError as e: + raise KVStoreError(e.rpc_code) + + def get(self, key: str) -> Optional[bytes]: + """Get the value associated with the given key from the store. + + Args: + key: The key to retrieve. + + Returns: + Optional[bytes]: The bytes value. If the key wasn't found, returns None. + """ + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + + try: + return self.gcs_client.internal_kv_get( + self.get_storage_key(key).encode(), + namespace=SERVE_INTERNAL_KV_NAMESPACE, + timeout=self.timeout, + ) + except ray.exceptions.RpcError as e: + raise KVStoreError(e.rpc_code) + + def delete(self, key: str): + """Delete the value associated with the given key from the store. + + Args: + key: The key to delete. + """ + + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + + try: + return self.gcs_client.internal_kv_del( + self.get_storage_key(key).encode(), + False, + namespace=SERVE_INTERNAL_KV_NAMESPACE, + timeout=self.timeout, + ) + except ray.exceptions.RpcError as e: + raise KVStoreError(e.rpc_code) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/kv_store_base.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/kv_store_base.py new file mode 100644 index 0000000000000000000000000000000000000000..68216e6547d169963f424c726fd2494a774c0039 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/storage/kv_store_base.py @@ -0,0 +1,56 @@ +import abc +from abc import abstractmethod +from typing import Optional + +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class KVStoreBase(metaclass=abc.ABCMeta): + """Abstract class for KVStore defining APIs needed for ray serve + use cases, currently (8/6/2021) controller state checkpointing. + """ + + @abstractmethod + def get_storage_key(self, key: str) -> str: + """Get internal key for storage. + + Args: + key: User provided key + + Returns: + storage_key: Formatted key for storage, usually by + prepending namespace. + """ + raise NotImplementedError("get_storage_key() has to be implemented") + + @abstractmethod + def put(self, key: str, val: bytes) -> bool: + """Put object into kv store, bytes only. + + Args: + key: Key for object to be stored. + val: Byte value of object. + """ + raise NotImplementedError("put() has to be implemented") + + @abstractmethod + def get(self, key: str) -> Optional[bytes]: + """Get object from storage. + + Args: + key: Key for object to be retrieved. + + Returns: + val: Byte value of object from storage. + """ + raise NotImplementedError("get() has to be implemented") + + @abstractmethod + def delete(self, key: str) -> None: + """Delete an object. + + Args: + key: Key for object to be deleted. + """ + raise NotImplementedError("delete() has to be implemented") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/test_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d742b1c8a2b042a1d72d9bbe4966a1c77078cb86 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/test_utils.py @@ -0,0 +1,815 @@ +import asyncio +import datetime +import os +import random +import threading +import time +from contextlib import asynccontextmanager +from copy import copy, deepcopy +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import grpc +import requests +from starlette.requests import Request + +import ray +import ray.util.state as state_api +from ray import serve +from ray._common.network_utils import build_address +from ray.actor import ActorHandle +from ray.serve._private.client import ServeControllerClient +from ray.serve._private.common import ( + CreatePlacementGroupRequest, + DeploymentID, + DeploymentStatus, + RequestProtocol, +) +from ray.serve._private.constants import ( + SERVE_DEFAULT_APP_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.deployment_state import ALL_REPLICA_STATES, ReplicaState +from ray.serve._private.proxy import DRAINING_MESSAGE +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import TimerBase +from ray.serve.context import _get_global_client +from ray.serve.generated import serve_pb2, serve_pb2_grpc +from ray.serve.schema import ApplicationStatus, TargetGroup + +TELEMETRY_ROUTE_PREFIX = "/telemetry" +STORAGE_ACTOR_NAME = "storage" + + +class MockTimer(TimerBase): + def __init__(self, start_time: Optional[float] = None): + self._lock = threading.Lock() + self.reset(start_time=start_time) + + def reset(self, start_time: Optional[float] = None): + if start_time is None: + start_time = time.time() + self._curr = start_time + + def time(self) -> float: + return self._curr + + def advance(self, by: float): + with self._lock: + self._curr += by + + def realistic_sleep(self, amt: float): + with self._lock: + self._curr += amt + 0.001 + + +class MockAsyncTimer: + def __init__(self, start_time: Optional[float] = 0): + self.reset(start_time=start_time) + self._num_sleepers = 0 + + def reset(self, start_time: 0): + self._curr = start_time + + def time(self) -> float: + return self._curr + + async def sleep(self, amt: float): + self._num_sleepers += 1 + end = self._curr + amt + + # Give up the event loop + while self._curr < end: + await asyncio.sleep(0) + + self._num_sleepers -= 1 + + def advance(self, amt: float): + self._curr += amt + + def num_sleepers(self): + return self._num_sleepers + + +class MockKVStore: + def __init__(self): + self.store = dict() + + def put(self, key: str, val: Any) -> bool: + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + self.store[key] = val + return True + + def get(self, key: str) -> Any: + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + return self.store.get(key, None) + + def delete(self, key: str) -> bool: + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + + if key in self.store: + del self.store[key] + return True + + return False + + +class MockClusterNodeInfoCache: + def __init__(self): + self.alive_node_ids = set() + self.total_resources_per_node = dict() + self.available_resources_per_node = dict() + self.draining_nodes = dict() + self.node_labels = dict() + + def get_alive_node_ids(self): + return self.alive_node_ids + + def get_draining_nodes(self): + return self.draining_nodes + + def get_active_node_ids(self): + return self.alive_node_ids - set(self.draining_nodes) + + def get_node_az(self, node_id): + return None + + def get_available_resources_per_node(self): + return self.available_resources_per_node + + def get_total_resources_per_node(self): + return self.total_resources_per_node + + def add_node(self, node_id: str, resources: Dict = None, labels: Dict = None): + self.alive_node_ids.add(node_id) + self.total_resources_per_node[node_id] = deepcopy(resources) or {} + self.available_resources_per_node[node_id] = deepcopy(resources) or {} + self.node_labels[node_id] = labels or {} + + def set_available_resources_per_node(self, node_id: str, resources: Dict): + self.available_resources_per_node[node_id] = deepcopy(resources) + + +class FakeRemoteFunction: + def remote(self): + pass + + +class MockActorHandle: + def __init__(self, **kwargs): + self._options = kwargs + self._actor_id = "fake_id" + self.initialize_and_get_metadata_called = False + self.is_allocated_called = False + + @property + def initialize_and_get_metadata(self): + self.initialize_and_get_metadata_called = True + # return a mock object so that we can call `remote()` on it. + return FakeRemoteFunction() + + @property + def is_allocated(self): + self.is_allocated_called = True + return FakeRemoteFunction() + + +class MockActorClass: + def __init__(self): + self._init_args = () + self._options = dict() + + def options(self, **kwargs): + res = copy(self) + + for k, v in kwargs.items(): + res._options[k] = v + + return res + + def remote(self, *args) -> MockActorHandle: + return MockActorHandle(init_args=args, **self._options) + + +class MockPlacementGroup: + def __init__(self, request: CreatePlacementGroupRequest): + self._bundles = request.bundles + self._strategy = request.strategy + self._soft_target_node_id = request.target_node_id + self._name = request.name + self._lifetime = "detached" + + +class MockDeploymentHandle: + def __init__(self, deployment_name: str, app_name: str = SERVE_DEFAULT_APP_NAME): + self._deployment_name = deployment_name + self._app_name = app_name + self._protocol = RequestProtocol.UNDEFINED + self._running_replicas_populated = False + self._initialized = False + + def is_initialized(self): + return self._initialized + + def _init(self): + if self._initialized: + raise RuntimeError("already initialized") + + self._initialized = True + + def options(self, *args, **kwargs): + return self + + def __eq__(self, dep: Tuple[str]): + other_deployment_name, other_app_name = dep + return ( + self._deployment_name == other_deployment_name + and self._app_name == other_app_name + ) + + def _set_request_protocol(self, protocol: RequestProtocol): + self._protocol = protocol + + def _get_or_create_router(self): + pass + + def running_replicas_populated(self) -> bool: + return self._running_replicas_populated + + def set_running_replicas_populated(self, val: bool): + self._running_replicas_populated = val + + +@serve.deployment +class GetPID: + def __call__(self): + return os.getpid() + + +get_pid_entrypoint = GetPID.bind() + + +def check_ray_stopped(): + try: + requests.get("http://localhost:8265/api/ray/version") + return False + except Exception: + return True + + +def check_ray_started(): + return requests.get("http://localhost:8265/api/ray/version").status_code == 200 + + +def check_deployment_status( + name: str, expected_status: DeploymentStatus, app_name=SERVE_DEFAULT_APP_NAME +) -> bool: + app_status = serve.status().applications[app_name] + assert app_status.deployments[name].status == expected_status + return True + + +def get_num_alive_replicas( + deployment_name: str, app_name: str = SERVE_DEFAULT_APP_NAME +) -> int: + """Get the replicas currently running for the given deployment.""" + + dep_id = DeploymentID(name=deployment_name, app_name=app_name) + actors = state_api.list_actors( + filters=[ + ("class_name", "=", dep_id.to_replica_actor_class_name()), + ("state", "=", "ALIVE"), + ] + ) + return len(actors) + + +def check_num_replicas_gte( + name: str, target: int, app_name: str = SERVE_DEFAULT_APP_NAME +) -> int: + """Check if num replicas is >= target.""" + + assert get_num_alive_replicas(name, app_name) >= target + return True + + +def check_num_replicas_eq( + name: str, + target: int, + app_name: str = SERVE_DEFAULT_APP_NAME, + use_controller: bool = False, +) -> int: + """Check if num replicas is == target.""" + + if use_controller: + dep = serve.status().applications[app_name].deployments[name] + num_running_replicas = dep.replica_states.get(ReplicaState.RUNNING, 0) + assert num_running_replicas == target + else: + assert get_num_alive_replicas(name, app_name) == target + + return True + + +def check_num_replicas_lte( + name: str, target: int, app_name: str = SERVE_DEFAULT_APP_NAME +) -> int: + """Check if num replicas is <= target.""" + + assert get_num_alive_replicas(name, app_name) <= target + return True + + +def check_apps_running(apps: List): + status = serve.status() + + for app_name in apps: + assert status.applications[app_name].status == ApplicationStatus.RUNNING + + return True + + +def check_replica_counts( + controller: ActorHandle, + deployment_id: DeploymentID, + total: Optional[int] = None, + by_state: Optional[List[Tuple[ReplicaState, int, Callable]]] = None, +): + """Uses _dump_replica_states_for_testing to check replica counts. + + Args: + controller: A handle to the Serve controller. + deployment_id: The deployment to check replica counts for. + total: The total number of expected replicas for the deployment. + by_state: A list of tuples of the form + (replica state, number of replicas, filter function). + Used for more fine grained checks. + """ + replicas = ray.get( + controller._dump_replica_states_for_testing.remote(deployment_id) + ) + + if total is not None: + replica_counts = { + state: len(replicas.get([state])) + for state in ALL_REPLICA_STATES + if replicas.get([state]) + } + assert replicas.count() == total, replica_counts + + if by_state is not None: + for state, count, check in by_state: + assert isinstance(state, ReplicaState) + assert isinstance(count, int) and count >= 0 + if check: + filtered = {r for r in replicas.get(states=[state]) if check(r)} + curr_count = len(filtered) + else: + curr_count = replicas.count(states=[state]) + msg = f"Expected {count} for state {state} but got {curr_count}." + assert curr_count == count, msg + + return True + + +@ray.remote(name=STORAGE_ACTOR_NAME, namespace=SERVE_NAMESPACE, num_cpus=0) +class TelemetryStorage: + def __init__(self): + self.reports_received = 0 + self.current_report = dict() + + def store_report(self, report: Dict) -> None: + self.reports_received += 1 + self.current_report = report + + def get_report(self) -> Dict: + return self.current_report + + def get_reports_received(self) -> int: + return self.reports_received + + +@serve.deployment(ray_actor_options={"num_cpus": 0}) +class TelemetryReceiver: + def __init__(self): + self.storage = ray.get_actor(name=STORAGE_ACTOR_NAME, namespace=SERVE_NAMESPACE) + + async def __call__(self, request: Request) -> bool: + report = await request.json() + ray.get(self.storage.store_report.remote(report)) + return True + + +receiver_app = TelemetryReceiver.bind() + + +def start_telemetry_app(): + """Start a telemetry Serve app. + + Ray should be initialized before calling this method. + + NOTE: If you're running the TelemetryReceiver Serve app to check telemetry, + remember that the receiver itself is counted in the telemetry. E.g. if you + deploy a Serve app other than the receiver, the number of apps in the + cluster is 2- not 1– since the receiver is also running. + + Returns a handle to a TelemetryStorage actor. You can use this actor + to access the latest telemetry reports. + """ + + storage = TelemetryStorage.remote() + serve.run(receiver_app, name="telemetry", route_prefix=TELEMETRY_ROUTE_PREFIX) + return storage + + +def check_telemetry( + tag: ServeUsageTag, expected: Any, storage_actor_name: str = STORAGE_ACTOR_NAME +): + storage_handle = ray.get_actor(storage_actor_name, namespace=SERVE_NAMESPACE) + report = ray.get(storage_handle.get_report.remote()) + print(report["extra_usage_tags"]) + assert tag.get_value_from_report(report) == expected + return True + + +def ping_grpc_list_applications(channel, app_names, test_draining=False): + import pytest + + stub = serve_pb2_grpc.RayServeAPIServiceStub(channel) + request = serve_pb2.ListApplicationsRequest() + if test_draining: + with pytest.raises(grpc.RpcError) as exception_info: + _, _ = stub.ListApplications.with_call(request=request) + rpc_error = exception_info.value + assert rpc_error.code() == grpc.StatusCode.UNAVAILABLE + assert rpc_error.details() == DRAINING_MESSAGE + else: + response, call = stub.ListApplications.with_call(request=request) + assert call.code() == grpc.StatusCode.OK + assert response.application_names == app_names + return True + + +def ping_grpc_healthz(channel, test_draining=False): + import pytest + + stub = serve_pb2_grpc.RayServeAPIServiceStub(channel) + request = serve_pb2.HealthzRequest() + if test_draining: + with pytest.raises(grpc.RpcError) as exception_info: + _, _ = stub.Healthz.with_call(request=request) + rpc_error = exception_info.value + assert rpc_error.code() == grpc.StatusCode.UNAVAILABLE + assert rpc_error.details() == DRAINING_MESSAGE + else: + response, call = stub.Healthz.with_call(request=request) + assert call.code() == grpc.StatusCode.OK + assert response.message == "success" + + +def ping_grpc_call_method(channel, app_name, test_not_found=False): + import pytest + + stub = serve_pb2_grpc.UserDefinedServiceStub(channel) + request = serve_pb2.UserDefinedMessage(name="foo", num=30, foo="bar") + metadata = (("application", app_name),) + if test_not_found: + with pytest.raises(grpc.RpcError) as exception_info: + _, _ = stub.__call__.with_call(request=request, metadata=metadata) + rpc_error = exception_info.value + assert rpc_error.code() == grpc.StatusCode.NOT_FOUND, rpc_error.code() + assert f"Application '{app_name}' not found." in rpc_error.details() + else: + response, call = stub.__call__.with_call(request=request, metadata=metadata) + assert call.code() == grpc.StatusCode.OK, call.code() + assert response.greeting == "Hello foo from bar", response.greeting + + +def ping_grpc_another_method(channel, app_name): + stub = serve_pb2_grpc.UserDefinedServiceStub(channel) + request = serve_pb2.UserDefinedMessage(name="foo", num=30, foo="bar") + metadata = (("application", app_name),) + response = stub.Method1(request=request, metadata=metadata) + assert response.greeting == "Hello foo from method1" + + +def ping_grpc_model_multiplexing(channel, app_name): + stub = serve_pb2_grpc.UserDefinedServiceStub(channel) + request = serve_pb2.UserDefinedMessage(name="foo", num=30, foo="bar") + multiplexed_model_id = "999" + metadata = ( + ("application", app_name), + ("multiplexed_model_id", multiplexed_model_id), + ) + response = stub.Method2(request=request, metadata=metadata) + assert ( + response.greeting + == f"Method2 called model, loading model: {multiplexed_model_id}" + ) + + +def ping_grpc_streaming(channel, app_name): + stub = serve_pb2_grpc.UserDefinedServiceStub(channel) + request = serve_pb2.UserDefinedMessage(name="foo", num=30, foo="bar") + metadata = (("application", app_name),) + responses = stub.Streaming(request=request, metadata=metadata) + for idx, response in enumerate(responses): + assert response.greeting == f"{idx}: Hello foo from bar" + + +def ping_fruit_stand(channel, app_name): + stub = serve_pb2_grpc.FruitServiceStub(channel) + request = serve_pb2.FruitAmounts(orange=4, apple=8) + metadata = (("application", app_name),) + response = stub.FruitStand(request=request, metadata=metadata) + assert response.costs == 32 + + +@asynccontextmanager +async def send_signal_on_cancellation(signal_actor: ActorHandle): + cancelled = False + try: + yield + await asyncio.sleep(100) + except asyncio.CancelledError: + cancelled = True + # Clear the context var to avoid Ray recursively cancelling this method call. + ray._raylet.async_task_id.set(None) + await signal_actor.send.remote() + + if not cancelled: + raise RuntimeError( + "CancelledError wasn't raised during `send_signal_on_cancellation` block" + ) + + +class FakeGrpcContext: + def __init__(self): + self._auth_context = {"key": "value"} + self._invocation_metadata = [("key", "value")] + self._peer = "peer" + self._peer_identities = b"peer_identities" + self._peer_identity_key = "peer_identity_key" + self._code = None + self._details = None + self._trailing_metadata = [] + self._invocation_metadata = [] + + def auth_context(self): + return self._auth_context + + def code(self): + return self._code + + def details(self): + return self._details + + def peer(self): + return self._peer + + def peer_identities(self): + return self._peer_identities + + def peer_identity_key(self): + return self._peer_identity_key + + def trailing_metadata(self): + return self._trailing_metadata + + def set_code(self, code): + self._code = code + + def set_details(self, details): + self._details = details + + def set_trailing_metadata(self, trailing_metadata): + self._trailing_metadata = trailing_metadata + + def invocation_metadata(self): + return self._invocation_metadata + + +class FakeGauge: + def __init__(self, name: str = None, tag_keys: Tuple[str] = None): + self.name = name + self.values = dict() + + self.tags = tag_keys or () + self.default_tags = dict() + + def set_default_tags(self, tags: Dict[str, str]): + for key, tag in tags.items(): + assert key in self.tags + self.default_tags[key] = tag + + def set(self, value: Union[int, float], tags: Dict[str, str] = None): + merged_tags = self.default_tags.copy() + merged_tags.update(tags or {}) + assert set(merged_tags.keys()) == set(self.tags) + + d = self.values + for tag in self.tags[:-1]: + tag_value = merged_tags[tag] + if tag_value not in d: + d[tag_value] = dict() + d = d[tag_value] + + d[merged_tags[self.tags[-1]]] = value + + def get_value(self, tags: Dict[str, str]): + value = self.values + for tag in self.tags: + tag_value = tags[tag] + value = value.get(tag_value) + if value is None: + return + + return value + + +class FakeCounter: + def __init__(self, name: str = None, tag_keys: Tuple[str] = None): + self.name = name + self.counts = dict() + + self.tags = tag_keys or () + self.default_tags = dict() + + def set_default_tags(self, tags: Dict[str, str]): + for key, tag in tags.items(): + assert key in self.tags + self.default_tags[key] = tag + + def inc(self, value: Union[int, float] = 1.0, tags: Dict[str, str] = None): + merged_tags = self.default_tags.copy() + merged_tags.update(tags or {}) + assert set(merged_tags.keys()) == set(self.tags) + + d = self.counts + for tag in self.tags[:-1]: + tag_value = merged_tags[tag] + if tag_value not in d: + d[tag_value] = dict() + d = d[tag_value] + + key = merged_tags[self.tags[-1]] + d[key] = d.get(key, 0) + value + + def get_count(self, tags: Dict[str, str]) -> int: + value = self.counts + for tag in self.tags: + tag_value = tags[tag] + value = value.get(tag_value) + if value is None: + return + + return value + + def get_tags(self): + return self.tags + + +@ray.remote +def get_node_id(): + return ray.get_runtime_context().get_node_id() + + +def check_num_alive_nodes(target: int): + alive_nodes = [node for node in ray.nodes() if node["Alive"]] + assert len(alive_nodes) == target + return True + + +def get_deployment_details( + deployment_name: str, + app_name: str = SERVE_DEFAULT_APP_NAME, + _client: ServeControllerClient = None, +): + client = _client or _get_global_client() + details = client.get_serve_details() + return details["applications"][app_name]["deployments"][deployment_name] + + +@ray.remote +class Counter: + def __init__(self, target: int): + self.count = 0 + self.target = target + self.ready_event = asyncio.Event() + + def inc(self): + self.count += 1 + if self.count == self.target: + self.ready_event.set() + + async def wait(self): + await self.ready_event.wait() + + +def tlog(s: str, level: str = "INFO"): + """Convenient logging method for testing.""" + + now = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3] + print(f"[{level}] {now} {s}") + + +def get_application_urls( + protocol: Union[str, RequestProtocol] = RequestProtocol.HTTP, + app_name: str = SERVE_DEFAULT_APP_NAME, + use_localhost: bool = True, + is_websocket: bool = False, + exclude_route_prefix: bool = False, +) -> List[str]: + """Get the URL of the application. + + Args: + protocol: The protocol to use for the application. + app_name: The name of the application. + use_localhost: Whether to use localhost instead of the IP address. + Set to True if Serve deployments are not exposed publicly or + for low latency benchmarking. + is_websocket: Whether the url should be served as a websocket. + exclude_route_prefix: The route prefix to exclude from the application. + Returns: + The URLs of the application. + """ + client = _get_global_client(_health_check_controller=True) + serve_details = client.get_serve_details() + assert ( + app_name in serve_details["applications"] + ), f"App {app_name} not found in serve details. Use this method only when the app is known to be running." + route_prefix = serve_details["applications"][app_name]["route_prefix"] + # route_prefix is set to None when route_prefix value is specifically set to None + # in the config used to deploy the app. + if exclude_route_prefix or route_prefix is None: + route_prefix = "" + if isinstance(protocol, str): + protocol = RequestProtocol(protocol) + target_groups: List[TargetGroup] = ray.get( + client._controller.get_target_groups.remote(app_name) + ) + target_groups = [ + target_group + for target_group in target_groups + if target_group.protocol == protocol + ] + if len(target_groups) == 0: + raise ValueError( + f"No target group found for app {app_name} with protocol {protocol} and route prefix {route_prefix}" + ) + urls = [] + for target_group in target_groups: + for target in target_group.targets: + ip = "localhost" if use_localhost else target.ip + if protocol == RequestProtocol.HTTP: + scheme = "ws" if is_websocket else "http" + url = f"{scheme}://{build_address(ip, target.port)}{route_prefix}" + elif protocol == RequestProtocol.GRPC: + if is_websocket: + raise ValueError( + "is_websocket=True is not supported with gRPC protocol." + ) + url = build_address(ip, target.port) + else: + raise ValueError(f"Unsupported protocol: {protocol}") + url = url.rstrip("/") + urls.append(url) + return urls + + +def get_application_url( + protocol: Union[str, RequestProtocol] = RequestProtocol.HTTP, + app_name: str = SERVE_DEFAULT_APP_NAME, + use_localhost: bool = True, + is_websocket: bool = False, + exclude_route_prefix: bool = False, +) -> str: + """Get the URL of the application. + + Args: + protocol: The protocol to use for the application. + app_name: The name of the application. + use_localhost: Whether to use localhost instead of the IP address. + Set to True if Serve deployments are not exposed publicly or + for low latency benchmarking. + is_websocket: Whether the url should be served as a websocket. + exclude_route_prefix: The route prefix to exclude from the application. + Returns: + The URL of the application. If there are multiple URLs, a random one is returned. + """ + return random.choice( + get_application_urls( + protocol, + app_name, + use_localhost, + is_websocket, + exclude_route_prefix, + ) + ) + + +def check_running(app_name: str = SERVE_DEFAULT_APP_NAME): + assert serve.status().applications[app_name].status == ApplicationStatus.RUNNING + return True diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eeeee1e6b10ce1db2e152c73d84659e50d690d5c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/__pycache__/get_asgi_route_name.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/__pycache__/get_asgi_route_name.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61c8ed8b8a5987d9e12fce9c971552908d060e3d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/__pycache__/get_asgi_route_name.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/get_asgi_route_name.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/get_asgi_route_name.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb2466b78b18b8b9d5744b957bfb3390548389b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/thirdparty/get_asgi_route_name.py @@ -0,0 +1,91 @@ +# This code is adapted from: +# https://github.com/elastic/apm-agent-python/blob/f570e8c2b68a8714628acac815aebcc3518b44c7/elasticapm/contrib/starlette/__init__.py +# +# BSD 3-Clause License +# +# Copyright (c) 2012, the Sentry Team, see AUTHORS for more details +# Copyright (c) 2019, Elasticsearch BV +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + +from typing import List, Optional + +from starlette.routing import Match, Mount, Route +from starlette.types import ASGIApp, Scope + + +def _get_route_name( + scope: Scope, routes: List[Route], *, route_name: Optional[str] = None +) -> Optional[str]: + for route in routes: + match, child_scope = route.matches(scope) + if match == Match.FULL: + route_name = route.path + child_scope = {**scope, **child_scope} + if isinstance(route, Mount) and route.routes: + child_route_name = _get_route_name( + child_scope, route.routes, route_name=route_name + ) + if child_route_name is None: + route_name = None + else: + route_name += child_route_name + return route_name + elif match == Match.PARTIAL and route_name is None: + route_name = route.path + + return None + + +def get_asgi_route_name(app: ASGIApp, scope: Scope) -> Optional[str]: + """Gets route name for given request taking mounts into account.""" + + routes = app.routes + route_name = _get_route_name(scope, routes) + + # Starlette magically redirects requests if the path matches a route name + # with a trailing slash appended or removed. To not spam the transaction + # names list, we do the same here and put these redirects all in the + # same "redirect trailing slashes" transaction name. + if not route_name and app.router.redirect_slashes and scope["path"] != "/": + redirect_scope = dict(scope) + if scope["path"].endswith("/"): + redirect_scope["path"] = scope["path"][:-1] + trim = True + else: + redirect_scope["path"] = scope["path"] + "/" + trim = False + + route_name = _get_route_name(redirect_scope, routes) + if route_name is not None: + route_name = route_name + "/" if trim else route_name[:-1] + + if route_name: + root_path = scope.get("root_path", "") + if root_path: + route_name = root_path.rstrip("/") + "/" + route_name.lstrip("/") + + return route_name diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/usage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/usage.py new file mode 100644 index 0000000000000000000000000000000000000000..39db128c5abe3e351534a472f5948a9c882eaae1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/usage.py @@ -0,0 +1,50 @@ +from enum import Enum +from typing import Dict, Optional + +from ray._common.usage.usage_lib import TagKey, record_extra_usage_tag + + +class ServeUsageTag(Enum): + API_VERSION = TagKey.SERVE_API_VERSION + NUM_DEPLOYMENTS = TagKey.SERVE_NUM_DEPLOYMENTS + GCS_STORAGE = TagKey.GCS_STORAGE + NUM_GPU_DEPLOYMENTS = TagKey.SERVE_NUM_GPU_DEPLOYMENTS + FASTAPI_USED = TagKey.SERVE_FASTAPI_USED + DAG_DRIVER_USED = TagKey.SERVE_DAG_DRIVER_USED + HTTP_ADAPTER_USED = TagKey.SERVE_HTTP_ADAPTER_USED + GRPC_INGRESS_USED = TagKey.SERVE_GRPC_INGRESS_USED + REST_API_VERSION = TagKey.SERVE_REST_API_VERSION + NUM_APPS = TagKey.SERVE_NUM_APPS + NUM_REPLICAS_LIGHTWEIGHT_UPDATED = TagKey.SERVE_NUM_REPLICAS_LIGHTWEIGHT_UPDATED + USER_CONFIG_LIGHTWEIGHT_UPDATED = TagKey.SERVE_USER_CONFIG_LIGHTWEIGHT_UPDATED + AUTOSCALING_CONFIG_LIGHTWEIGHT_UPDATED = ( + TagKey.SERVE_AUTOSCALING_CONFIG_LIGHTWEIGHT_UPDATED + ) + DEPLOYMENT_HANDLE_API_USED = TagKey.SERVE_DEPLOYMENT_HANDLE_API_USED + DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED = ( + TagKey.SERVE_DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED + ) + MULTIPLEXED_API_USED = TagKey.SERVE_MULTIPLEXED_API_USED + HTTP_PROXY_USED = TagKey.SERVE_HTTP_PROXY_USED + GRPC_PROXY_USED = TagKey.SERVE_GRPC_PROXY_USED + SERVE_STATUS_API_USED = TagKey.SERVE_STATUS_API_USED + SERVE_GET_APP_HANDLE_API_USED = TagKey.SERVE_GET_APP_HANDLE_API_USED + SERVE_GET_DEPLOYMENT_HANDLE_API_USED = TagKey.SERVE_GET_DEPLOYMENT_HANDLE_API_USED + APP_CONTAINER_RUNTIME_ENV_USED = TagKey.SERVE_APP_CONTAINER_RUNTIME_ENV_USED + DEPLOYMENT_CONTAINER_RUNTIME_ENV_USED = ( + TagKey.SERVE_DEPLOYMENT_CONTAINER_RUNTIME_ENV_USED + ) + NUM_NODE_COMPACTIONS = TagKey.SERVE_NUM_NODE_COMPACTIONS + AUTO_NUM_REPLICAS_USED = TagKey.SERVE_AUTO_NUM_REPLICAS_USED + CUSTOM_REQUEST_ROUTER_USED = TagKey.SERVE_CUSTOM_REQUEST_ROUTER_USED + + def record(self, value: str): + """Record telemetry value.""" + record_extra_usage_tag(self.value, value) + + def get_value_from_report(self, report: Dict) -> Optional[str]: + """Returns `None` if the tag isn't in the report.""" + if "extra_usage_tags" not in report: + return None + + return report["extra_usage_tags"].get(TagKey.Name(self.value).lower(), None) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3cfad95ff0cdbf39377885ccad30347da00e5159 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/utils.py @@ -0,0 +1,739 @@ +import asyncio +import collections +import concurrent.futures +import copy +import importlib +import inspect +import logging +import random +import re +import time +import uuid +from abc import ABC, abstractmethod +from asyncio import coroutines, ensure_future, futures +from decimal import ROUND_HALF_UP, Decimal +from enum import Enum +from functools import wraps +from typing import Any, Callable, Dict, List, Optional, TypeVar, Union + +import requests + +import ray +import ray.util.serialization_addons +from ray._common.constants import HEAD_NODE_RESOURCE_NAME +from ray._common.utils import get_random_alphanumeric_string, import_attr +from ray._private.worker import LOCAL_MODE, SCRIPT_MODE +from ray._raylet import MessagePackSerializer +from ray.actor import ActorHandle +from ray.serve._private.common import RequestMetadata, ServeComponentType +from ray.serve._private.constants import HTTP_PROXY_TIMEOUT, SERVE_LOGGER_NAME +from ray.serve.config import gRPCOptions +from ray.types import ObjectRef +from ray.util.serialization import StandaloneSerializationContext + +try: + import pandas as pd +except ImportError: + pd = None + +try: + import numpy as np +except ImportError: + np = None + +FILE_NAME_REGEX = r"[^\x20-\x7E]|[<>:\"/\\|?*]" + +MESSAGE_PACK_OFFSET = 9 +GENERATOR_COMPOSITION_NOT_SUPPORTED_ERROR = RuntimeError( + "Streaming deployment handle results cannot be passed to " + "downstream handle calls. If you have a use case requiring " + "this feature, please file a feature request on GitHub." +) + + +# Use a global singleton enum to emulate default options. We cannot use None +# for those option because None is a valid new value. +class DEFAULT(Enum): + VALUE = 1 + + +class DeploymentOptionUpdateType(str, Enum): + # Nothing needs to be done other than setting the target state. + LightWeight = "LightWeight" + # Each DeploymentReplica instance (tracked in DeploymentState) uses certain options + # from the deployment config. These values need to be updated in DeploymentReplica. + NeedsReconfigure = "NeedsReconfigure" + # Options that are sent to the replica actor. If changed, reconfigure() on the actor + # needs to be called to update these values. + NeedsActorReconfigure = "NeedsActorReconfigure" + # If changed, restart all replicas. + HeavyWeight = "HeavyWeight" + + +# Type alias: objects that can be DEFAULT.VALUE have type Default[T] +T = TypeVar("T") +Default = Union[DEFAULT, T] + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +# Format for component files +FILE_FMT = "{component_name}_{component_id}{suffix}" + + +class _ServeCustomEncoders: + """Group of custom encoders for common types that's not handled by FastAPI.""" + + @staticmethod + def encode_np_array(obj): + assert isinstance(obj, np.ndarray) + if obj.dtype.kind == "f": # floats + obj = obj.astype(float) + if obj.dtype.kind in {"i", "u"}: # signed and unsigned integers. + obj = obj.astype(int) + return obj.tolist() + + @staticmethod + def encode_np_scaler(obj): + assert isinstance(obj, np.generic) + return obj.item() + + @staticmethod + def encode_exception(obj): + assert isinstance(obj, Exception) + return str(obj) + + @staticmethod + def encode_pandas_dataframe(obj): + assert isinstance(obj, pd.DataFrame) + return obj.to_dict(orient="records") + + +serve_encoders = {Exception: _ServeCustomEncoders.encode_exception} + +if np is not None: + serve_encoders[np.ndarray] = _ServeCustomEncoders.encode_np_array + serve_encoders[np.generic] = _ServeCustomEncoders.encode_np_scaler + +if pd is not None: + serve_encoders[pd.DataFrame] = _ServeCustomEncoders.encode_pandas_dataframe + + +@ray.remote(num_cpus=0) +def block_until_http_ready( + http_endpoint, + backoff_time_s=1, + check_ready=None, + timeout=HTTP_PROXY_TIMEOUT, +): + http_is_ready = False + start_time = time.time() + + while not http_is_ready: + try: + resp = requests.get(http_endpoint) + assert resp.status_code == 200 + if check_ready is None: + http_is_ready = True + else: + http_is_ready = check_ready(resp) + except Exception: + pass + + if 0 < timeout < time.time() - start_time: + raise TimeoutError("HTTP proxy not ready after {} seconds.".format(timeout)) + + time.sleep(backoff_time_s) + + +def get_random_string(length: int = 8): + return get_random_alphanumeric_string(length) + + +def format_actor_name(actor_name, *modifiers): + name = actor_name + for modifier in modifiers: + name += "-{}".format(modifier) + + return name + + +def ensure_serialization_context(): + """Ensure the serialization addons on registered, even when Ray has not + been started.""" + ctx = StandaloneSerializationContext() + ray.util.serialization_addons.apply(ctx) + + +def msgpack_serialize(obj): + ctx = ray._private.worker.global_worker.get_serialization_context() + buffer = ctx.serialize(obj) + serialized = buffer.to_bytes() + return serialized + + +def msgpack_deserialize(data): + # todo: Ray does not provide a msgpack deserialization api. + try: + obj = MessagePackSerializer.loads(data[MESSAGE_PACK_OFFSET:], None) + except Exception: + raise + return obj + + +def merge_dict(dict1, dict2): + if dict1 is None and dict2 is None: + return None + if dict1 is None: + dict1 = dict() + if dict2 is None: + dict2 = dict() + result = dict() + for key in dict1.keys() | dict2.keys(): + result[key] = sum([e.get(key, 0) for e in (dict1, dict2)]) + return result + + +def parse_import_path(import_path: str): + """ + Takes in an import_path of form: + + [subdirectory 1].[subdir 2]...[subdir n].[file name].[attribute name] + + Parses this path and returns the module name (everything before the last + dot) and attribute name (everything after the last dot), such that the + attribute can be imported using "from module_name import attr_name". + """ + + nodes = import_path.split(".") + if len(nodes) < 2: + raise ValueError( + f"Got {import_path} as import path. The import path " + f"should at least specify the file name and " + f"attribute name connected by a dot." + ) + + return ".".join(nodes[:-1]), nodes[-1] + + +def override_runtime_envs_except_env_vars(parent_env: Dict, child_env: Dict) -> Dict: + """Creates a runtime_env dict by merging a parent and child environment. + + This method is not destructive. It leaves the parent and child envs + the same. + + The merge is a shallow update where the child environment inherits the + parent environment's settings. If the child environment specifies any + env settings, those settings take precdence over the parent. + - Note: env_vars are a special case. The child's env_vars are combined + with the parent. + + Args: + parent_env: The environment to inherit settings from. + child_env: The environment with override settings. + + Returns: A new dictionary containing the merged runtime_env settings. + + Raises: + TypeError: If a dictionary is not passed in for parent_env or child_env. + """ + + if not isinstance(parent_env, Dict): + raise TypeError( + f'Got unexpected type "{type(parent_env)}" for parent_env. ' + "parent_env must be a dictionary." + ) + if not isinstance(child_env, Dict): + raise TypeError( + f'Got unexpected type "{type(child_env)}" for child_env. ' + "child_env must be a dictionary." + ) + + defaults = copy.deepcopy(parent_env) + overrides = copy.deepcopy(child_env) + + default_env_vars = defaults.get("env_vars", {}) + override_env_vars = overrides.get("env_vars", {}) + + defaults.update(overrides) + default_env_vars.update(override_env_vars) + + defaults["env_vars"] = default_env_vars + + return defaults + + +class JavaActorHandleProxy: + """Wraps actor handle and translate snake_case to camelCase.""" + + def __init__(self, handle: ActorHandle): + self.handle = handle + self._available_attrs = set(dir(self.handle)) + + def __getattr__(self, key: str): + if key in self._available_attrs: + camel_case_key = key + else: + components = key.split("_") + camel_case_key = components[0] + "".join(x.title() for x in components[1:]) + return getattr(self.handle, camel_case_key) + + +def require_packages(packages: List[str]): + """Decorator making sure function run in specified environments + + Examples: + >>> from ray.serve._private.utils import require_packages + >>> @require_packages(["numpy", "package_a"]) # doctest: +SKIP + ... def func(): # doctest: +SKIP + ... import numpy as np # doctest: +SKIP + ... ... # doctest: +SKIP + >>> func() # doctest: +SKIP + ImportError: func requires ["numpy", "package_a"] but + ["package_a"] are not available, please pip install them. + """ + + def decorator(func): + def check_import_once(): + if not hasattr(func, "_require_packages_checked"): + missing_packages = [] + for package in packages: + try: + importlib.import_module(package) + except ModuleNotFoundError: + missing_packages.append(package) + if len(missing_packages) > 0: + raise ImportError( + f"{func} requires packages {packages} to run but " + f"{missing_packages} are missing. Please " + "`pip install` them or add them to " + "`runtime_env`." + ) + func._require_packages_checked = True + + if inspect.iscoroutinefunction(func): + + @wraps(func) + async def wrapped(*args, **kwargs): + check_import_once() + return await func(*args, **kwargs) + + elif inspect.isroutine(func): + + @wraps(func) + def wrapped(*args, **kwargs): + check_import_once() + return func(*args, **kwargs) + + else: + raise ValueError("Decorator expect callable functions.") + + return wrapped + + return decorator + + +def in_interactive_shell(): + # Taken from: + # https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook + import __main__ as main + + return not hasattr(main, "__file__") + + +def snake_to_camel_case(snake_str: str) -> str: + """Convert a snake case string to camel case.""" + + words = snake_str.strip("_").split("_") + return words[0] + "".join(word[:1].upper() + word[1:] for word in words[1:]) + + +def check_obj_ref_ready_nowait(obj_ref: ObjectRef) -> bool: + """Check if ray object reference is ready without waiting for it.""" + finished, _ = ray.wait([obj_ref], timeout=0) + return len(finished) == 1 + + +def extract_self_if_method_call(args: List[Any], func: Callable) -> Optional[object]: + """Check if this is a method rather than a function. + + Does this by checking to see if `func` is the attribute of the first + (`self`) argument under `func.__name__`. Unfortunately, this is the most + robust solution to this I was able to find. It would also be preferable + to do this check when the decorator runs, rather than when the method is. + + Returns the `self` object if it's a method call, else None. + + Arguments: + args: arguments to the function/method call. + func: the unbound function that was called. + """ + if len(args) > 0: + method = getattr(args[0], func.__name__, False) + if method: + wrapped = getattr(method, "__wrapped__", False) + if wrapped and wrapped == func: + return args[0] + + return None + + +def call_function_from_import_path(import_path: str) -> Any: + """Call the function given import path. + + Args: + import_path: The import path of the function to call. + Raises: + ValueError: If the import path is invalid. + TypeError: If the import path is not callable. + RuntimeError: if the function raise exeception during execution. + Returns: + The result of the function call. + """ + try: + callback_func = import_attr(import_path) + except Exception as e: + raise ValueError(f"The import path {import_path} cannot be imported: {e}") + + if not callable(callback_func): + raise TypeError(f"The import path {import_path} is not callable.") + + try: + return callback_func() + except Exception as e: + raise RuntimeError(f"The function {import_path} raised an exception: {e}") + + +def get_head_node_id() -> str: + """Get the head node id. + + Iterate through all nodes in the ray cluster and return the node id of the first + alive node with head node resource. + """ + head_node_id = None + for node in ray.nodes(): + if HEAD_NODE_RESOURCE_NAME in node["Resources"] and node["Alive"]: + head_node_id = node["NodeID"] + break + assert head_node_id is not None, "Cannot find alive head node." + + return head_node_id + + +def calculate_remaining_timeout( + *, + timeout_s: Optional[float], + start_time_s: float, + curr_time_s: float, +) -> Optional[float]: + """Get the timeout remaining given an overall timeout, start time, and curr time. + + If the timeout passed in was `None` or negative, will always return that timeout + directly. + + If the timeout is >= 0, the returned remaining timeout always be >= 0. + """ + if timeout_s is None or timeout_s < 0: + return timeout_s + + time_since_start_s = curr_time_s - start_time_s + return max(0, timeout_s - time_since_start_s) + + +def get_all_live_placement_group_names() -> List[str]: + """Fetch and parse the Ray placement group table for live placement group names. + + Placement groups are filtered based on their `scheduling_state`; any placement + group not in the "REMOVED" state is considered live. + """ + placement_group_table = ray.util.placement_group_table() + + live_pg_names = [] + for entry in placement_group_table.values(): + pg_name = entry.get("name", "") + if ( + pg_name + and entry.get("stats", {}).get("scheduling_state", "UNKNOWN") != "REMOVED" + ): + live_pg_names.append(pg_name) + + return live_pg_names + + +def get_current_actor_id() -> str: + """Gets the ID of the calling actor. + + If this is called in a driver, returns "DRIVER." + + If otherwise called outside of an actor, returns an empty string. + + This function hangs when GCS is down due to the `ray.get_runtime_context()` + call. + """ + + worker_mode = ray.get_runtime_context().worker.mode + if worker_mode in {SCRIPT_MODE, LOCAL_MODE}: + return "DRIVER" + else: + try: + actor_id = ray.get_runtime_context().get_actor_id() + if actor_id is None: + return "" + else: + return actor_id + except Exception: + return "" + + +def is_running_in_asyncio_loop() -> bool: + try: + asyncio.get_running_loop() + return True + except RuntimeError: + return False + + +class TimerBase(ABC): + @abstractmethod + def time(self) -> float: + """Return the current time.""" + raise NotImplementedError + + +class Timer(TimerBase): + def time(self) -> float: + return time.time() + + +def get_capacity_adjusted_num_replicas( + num_replicas: int, target_capacity: Optional[float] +) -> int: + """Return the `num_replicas` adjusted by the `target_capacity`. + + The output will only ever be 0 if `target_capacity` is 0 or `num_replicas` is + 0 (to support autoscaling deployments using scale-to-zero). + + Rather than using the default `round` behavior in Python, which rounds half to + even, uses the `decimal` module to round half up (standard rounding behavior). + """ + if target_capacity is None or target_capacity == 100: + return num_replicas + + if target_capacity == 0 or num_replicas == 0: + return 0 + + adjusted_num_replicas = Decimal(num_replicas * target_capacity) / Decimal(100.0) + rounded_adjusted_num_replicas = adjusted_num_replicas.to_integral_value( + rounding=ROUND_HALF_UP + ) + return max(1, int(rounded_adjusted_num_replicas)) + + +def generate_request_id() -> str: + # NOTE(edoakes): we use random.getrandbits because it reduces CPU overhead + # significantly. This is less cryptographically secure but should be ok for + # request ID generation. + # See https://bugs.python.org/issue45556 for discussion. + return str(uuid.UUID(int=random.getrandbits(128), version=4)) + + +def inside_ray_client_context() -> bool: + return ray.util.client.ray.is_connected() + + +def get_component_file_name( + component_name: str, + component_id: str, + component_type: Optional[ServeComponentType], + suffix: str = "", +) -> str: + """Get the component's file name. Replaces special characters with underscores.""" + component_name = re.sub(FILE_NAME_REGEX, "_", component_name) + + # For DEPLOYMENT component type, we want to log the deployment name + # instead of adding the component type to the component name. + component_log_file_name = component_name + if component_type is not None: + component_log_file_name = f"{component_type.value}_{component_name}" + if component_type != ServeComponentType.REPLICA: + component_name = f"{component_type}_{component_name}" + file_name = FILE_FMT.format( + component_name=component_log_file_name, + component_id=component_id, + suffix=suffix, + ) + return file_name + + +def validate_route_prefix(route_prefix: Union[DEFAULT, None, str]): + if route_prefix is DEFAULT.VALUE or route_prefix is None: + return + + if not route_prefix.startswith("/"): + raise ValueError( + f"Invalid route_prefix '{route_prefix}', " + "must start with a forward slash ('/')." + ) + + if route_prefix != "/" and route_prefix.endswith("/"): + raise ValueError( + f"Invalid route_prefix '{route_prefix}', " + "may not end with a trailing '/'." + ) + + if "{" in route_prefix or "}" in route_prefix: + raise ValueError( + f"Invalid route_prefix '{route_prefix}', may not contain wildcards." + ) + + +async def resolve_deployment_response(obj: Any, request_metadata: RequestMetadata): + """Resolve `DeploymentResponse` objects to underlying object references. + + This enables composition without explicitly calling `_to_object_ref`. + """ + from ray.serve.handle import DeploymentResponse, DeploymentResponseGenerator + + if isinstance(obj, DeploymentResponseGenerator): + raise GENERATOR_COMPOSITION_NOT_SUPPORTED_ERROR + elif isinstance(obj, DeploymentResponse): + # Launch async task to convert DeploymentResponse to an object ref + return asyncio.create_task(obj._to_object_ref()) + + +def wait_for_interrupt() -> None: + try: + while True: + # Block, letting Ray print logs to the terminal. + time.sleep(10) + except KeyboardInterrupt: + logger.warning("Got KeyboardInterrupt, exiting...") + # We need to re-raise KeyboardInterrupt, so serve components can be shutdown + # from the main script. + raise + + +def is_grpc_enabled(grpc_config: gRPCOptions) -> bool: + return grpc_config.port > 0 and len(grpc_config.grpc_servicer_functions) > 0 + + +def run_coroutine_or_future_threadsafe(coro_or_future, loop): + """Submit a coroutine object or future to a given event loop. + + Ref: https://github.com/python/cpython/blob/eef49c359505eaf109d519d39e53dfd3c78d066a/Lib/asyncio/tasks.py#L991 + + Return a concurrent.futures.Future to access the result. + """ + if not coroutines.iscoroutine(coro_or_future) and not futures.isfuture( + coro_or_future + ): + raise TypeError("A coroutine object or future is required") + + if futures.isfuture(coro_or_future): + assert loop == coro_or_future.get_loop() + + future = concurrent.futures.Future() + + def callback(): + try: + futures._chain_future(ensure_future(coro_or_future, loop=loop), future) + except (SystemExit, KeyboardInterrupt): + raise + except BaseException as exc: + if future.set_running_or_notify_cancel(): + future.set_exception(exc) + raise + + loop.call_soon_threadsafe(callback) + return future + + +class Semaphore: + """Based on asyncio.Semaphore. + + This is a semaphore that can be used to limit the number of concurrent requests. + Its maximum value is dynamic and is determined by the `get_value_fn` function. + """ + + def __init__(self, get_value_fn: Callable[[], int]): + self._waiters = None + self._value = 0 + self._get_value_fn = get_value_fn + + def __repr__(self): + res = super().__repr__() + extra = "locked" if self.locked() else f"unlocked, value:{self._value}" + if self._waiters: + extra = f"{extra}, waiters:{len(self._waiters)}" + return f"<{res[1:-1]} [{extra}]>" + + async def __aenter__(self): + await self.acquire() + # We have no use for the "as ..." clause in the with + # statement for locks. + return None + + async def __aexit__(self, exc_type, exc, tb): + self.release() + + def get_max_value(self): + return self._get_value_fn() + + def locked(self): + """Returns True if semaphore cannot be acquired immediately.""" + return self._value >= self.get_max_value() or ( + any(not w.cancelled() for w in (self._waiters or ())) + ) + + async def acquire(self): + """Acquire a semaphore. + If the internal counter is larger than zero on entry, + decrement it by one and return True immediately. If it is + zero on entry, block, waiting until some other coroutine has + called release() to make it larger than 0, and then return + True. + """ + if not self.locked(): + self._value += 1 + return True + + if self._waiters is None: + self._waiters = collections.deque() + fut = asyncio.Future() + self._waiters.append(fut) + + # Finally block should be called before the CancelledError + # handling as we don't want CancelledError to call + # _wake_up_first() and attempt to wake up itself. + try: + try: + await fut + finally: + self._waiters.remove(fut) + except asyncio.CancelledError: + if not fut.cancelled(): + self._value -= 1 + self._wake_up_next() + raise + + if self._value < self.get_max_value(): + self._wake_up_next() + return True + + def release(self): + """Release a semaphore, incrementing the internal counter by one. + When it was zero on entry and another coroutine is waiting for it to + become larger than zero again, wake up that coroutine. + """ + self._value -= 1 + self._wake_up_next() + + def _wake_up_next(self): + """Wake up the first waiter that isn't done.""" + if not self._waiters: + return + + for fut in self._waiters: + if not fut.done(): + self._value += 1 + fut.set_result(True) + return diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/version.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/version.py new file mode 100644 index 0000000000000000000000000000000000000000..1c064a9a9dc7ad416fc092b0c1b12dafd537c9ec --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/version.py @@ -0,0 +1,217 @@ +import json +import logging +from copy import deepcopy +from typing import Any, Dict, List, Optional +from zlib import crc32 + +from ray._common.pydantic_compat import BaseModel +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.utils import DeploymentOptionUpdateType, get_random_string +from ray.serve.config import AutoscalingConfig +from ray.serve.generated.serve_pb2 import DeploymentVersion as DeploymentVersionProto + +logger = logging.getLogger("ray.serve") + + +class DeploymentVersion: + def __init__( + self, + code_version: Optional[str], + deployment_config: DeploymentConfig, + ray_actor_options: Optional[Dict], + placement_group_bundles: Optional[List[Dict[str, float]]] = None, + placement_group_strategy: Optional[str] = None, + max_replicas_per_node: Optional[int] = None, + route_prefix: Optional[str] = None, + ): + if code_version is not None and not isinstance(code_version, str): + raise TypeError(f"code_version must be str, got {type(code_version)}.") + if code_version is None: + self.code_version = get_random_string() + else: + self.code_version = code_version + + # Options for this field may be mutated over time, so any logic that uses this + # should access this field directly. + self.deployment_config = deployment_config + self.ray_actor_options = ray_actor_options + self.placement_group_bundles = placement_group_bundles + self.placement_group_strategy = placement_group_strategy + self.max_replicas_per_node = max_replicas_per_node + self.route_prefix = route_prefix + self.compute_hashes() + + @classmethod + def from_deployment_version( + cls, deployment_version, deployment_config, route_prefix: Optional[str] = None + ): + version_copy = deepcopy(deployment_version) + version_copy.deployment_config = deployment_config + version_copy.route_prefix = route_prefix + version_copy.compute_hashes() + return version_copy + + def __hash__(self) -> int: + return self._hash + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DeploymentVersion): + return False + return self._hash == other._hash + + def requires_actor_restart(self, new_version): + """Determines whether the new version requires actors of the current version to + be restarted. + """ + return ( + self.code_version != new_version.code_version + or self.ray_actor_options_hash != new_version.ray_actor_options_hash + or self.placement_group_options_hash + != new_version.placement_group_options_hash + or self.max_replicas_per_node != new_version.max_replicas_per_node + ) + + def requires_actor_reconfigure(self, new_version): + """Determines whether the new version requires calling reconfigure() on the + replica actor. + """ + return self.reconfigure_actor_hash != new_version.reconfigure_actor_hash + + def requires_long_poll_broadcast(self, new_version): + """Determines whether lightweightly updating an existing replica to the new + version requires broadcasting through long poll that the running replicas has + changed. + """ + return ( + self.deployment_config.max_ongoing_requests + != new_version.deployment_config.max_ongoing_requests + ) + + def compute_hashes(self): + # If these change, the controller will rolling upgrade existing replicas. + serialized_ray_actor_options = _serialize(self.ray_actor_options or {}) + self.ray_actor_options_hash = crc32(serialized_ray_actor_options) + combined_placement_group_options = {} + if self.placement_group_bundles is not None: + combined_placement_group_options["bundles"] = self.placement_group_bundles + if self.placement_group_strategy is not None: + combined_placement_group_options["strategy"] = self.placement_group_strategy + serialized_placement_group_options = _serialize( + combined_placement_group_options + ) + self.placement_group_options_hash = crc32(serialized_placement_group_options) + # Include app-level route prefix in the version hashes so changing + # it triggers an in-place reconfigure of running replicas. + serialized_route_prefix = _serialize(self.route_prefix) + + # If this changes, DeploymentReplica.reconfigure() will call reconfigure on the + # actual replica actor + self.reconfigure_actor_hash = crc32( + serialized_route_prefix + + self._get_serialized_options( + [DeploymentOptionUpdateType.NeedsActorReconfigure] + ) + ) + + # Used by __eq__ in deployment state to either reconfigure the replicas or + # stop and restart them + self._hash = crc32( + self.code_version.encode("utf-8") + + serialized_ray_actor_options + + serialized_placement_group_options + + str(self.max_replicas_per_node).encode("utf-8") + + serialized_route_prefix + + self._get_serialized_options( + [ + DeploymentOptionUpdateType.NeedsReconfigure, + DeploymentOptionUpdateType.NeedsActorReconfigure, + ] + ) + ) + + def to_proto(self) -> bytes: + # TODO(simon): enable cross language user config + return DeploymentVersionProto( + code_version=self.code_version, + deployment_config=self.deployment_config.to_proto(), + ray_actor_options=json.dumps(self.ray_actor_options), + placement_group_bundles=json.dumps(self.placement_group_bundles) + if self.placement_group_bundles is not None + else "", + placement_group_strategy=self.placement_group_strategy + if self.placement_group_strategy is not None + else "", + max_replicas_per_node=self.max_replicas_per_node + if self.max_replicas_per_node is not None + else 0, + ) + + @classmethod + def from_proto(cls, proto: DeploymentVersionProto): + return DeploymentVersion( + proto.code_version, + DeploymentConfig.from_proto(proto.deployment_config), + json.loads(proto.ray_actor_options), + placement_group_bundles=( + json.loads(proto.placement_group_bundles) + if proto.placement_group_bundles + else None + ), + placement_group_version=( + proto.placement_group_version if proto.placement_group_version else None + ), + max_replicas_per_node=( + proto.max_replicas_per_node if proto.max_replicas_per_node else None + ), + ) + + def _get_serialized_options( + self, update_types: List[DeploymentOptionUpdateType] + ) -> bytes: + """Returns a serialized dictionary containing fields of a deployment config that + should prompt a deployment version update. + """ + reconfigure_dict = {} + # TODO(aguo): Once we only support pydantic 2, we can remove this if check. + # In pydantic 2.0, `__fields__` has been renamed to `model_fields`. + fields = ( + self.deployment_config.model_fields + if hasattr(self.deployment_config, "model_fields") + else self.deployment_config.__fields__ + ) + for option_name, field in fields.items(): + option_weight = field.field_info.extra.get("update_type") + if option_weight in update_types: + reconfigure_dict[option_name] = getattr( + self.deployment_config, option_name + ) + # If autoscaling config was changed, only broadcast to + # replicas if metrics_interval_s or look_back_period_s + # was changed, because the rest of the fields are only + # used in deployment state manager + if isinstance(reconfigure_dict[option_name], AutoscalingConfig): + reconfigure_dict[option_name] = reconfigure_dict[option_name].dict( + include={"metrics_interval_s", "look_back_period_s"} + ) + elif isinstance(reconfigure_dict[option_name], BaseModel): + reconfigure_dict[option_name] = reconfigure_dict[option_name].dict() + + # Can't serialize bytes. The request router class is already + # included in the serialized config as request_router_class. + if "request_router_config" in reconfigure_dict: + reconfigure_dict["request_router_config"].pop( + "_serialized_request_router_cls", None + ) + + if ( + isinstance(self.deployment_config.user_config, bytes) + and "user_config" in reconfigure_dict + ): + del reconfigure_dict["user_config"] + return self.deployment_config.user_config + _serialize(reconfigure_dict) + + return _serialize(reconfigure_dict) + + +def _serialize(json_object): + return str.encode(json.dumps(json_object, sort_keys=True)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/__pycache__/serve_pb2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/__pycache__/serve_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bf1409129326376316b53058ff55eecf3028170 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/__pycache__/serve_pb2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/__pycache__/serve_pb2_grpc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/__pycache__/serve_pb2_grpc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24f10bc197f744fe2d46f3a455bc88634647a701 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/__pycache__/serve_pb2_grpc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/serve_pb2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/serve_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..1c20e4194393924e7c2e4a509683d4b1792074fe --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/serve_pb2.py @@ -0,0 +1,526 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: src/ray/protobuf/serve.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1csrc/ray/protobuf/serve.proto\x12\tray.serve\"\'\n\x11\x41utoscalingPolicy\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\"\xea\x06\n\x11\x41utoscalingConfig\x12!\n\x0cmin_replicas\x18\x01 \x01(\rR\x0bminReplicas\x12!\n\x0cmax_replicas\x18\x02 \x01(\rR\x0bmaxReplicas\x12,\n\x12metrics_interval_s\x18\x03 \x01(\x01R\x10metricsIntervalS\x12+\n\x12look_back_period_s\x18\x04 \x01(\x01R\x0flookBackPeriodS\x12)\n\x10smoothing_factor\x18\x05 \x01(\x01R\x0fsmoothingFactor\x12*\n\x11\x64ownscale_delay_s\x18\x06 \x01(\x01R\x0f\x64ownscaleDelayS\x12&\n\x0fupscale_delay_s\x18\x07 \x01(\x01R\rupscaleDelayS\x12.\n\x10initial_replicas\x18\x08 \x01(\rH\x00R\x0finitialReplicas\x88\x01\x01\x12=\n\x18upscale_smoothing_factor\x18\t \x01(\x01H\x01R\x16upscaleSmoothingFactor\x88\x01\x01\x12\x41\n\x1a\x64ownscale_smoothing_factor\x18\n \x01(\x01H\x02R\x18\x64ownscaleSmoothingFactor\x88\x01\x01\x12\x33\n\x16_serialized_policy_def\x18\x0b \x01(\x0cR\x13SerializedPolicyDef\x12\x35\n\x07_policy\x18\x0c \x01(\x0b\x32\x1c.ray.serve.AutoscalingPolicyR\x06Policy\x12\x36\n\x17target_ongoing_requests\x18\r \x01(\x01R\x15targetOngoingRequests\x12.\n\x10upscaling_factor\x18\x0e \x01(\x01H\x03R\x0fupscalingFactor\x88\x01\x01\x12\x32\n\x12\x64ownscaling_factor\x18\x0f \x01(\x01H\x04R\x11\x64ownscalingFactor\x88\x01\x01\x42\x13\n\x11_initial_replicasB\x1b\n\x19_upscale_smoothing_factorB\x1d\n\x1b_downscale_smoothing_factorB\x13\n\x11_upscaling_factorB\x15\n\x13_downscaling_factor\"\xeb\x01\n\rLoggingConfig\x12\x33\n\x08\x65ncoding\x18\x01 \x01(\x0e\x32\x17.ray.serve.EncodingTypeR\x08\x65ncoding\x12\x1b\n\tlog_level\x18\x02 \x01(\tR\x08logLevel\x12\x19\n\x08logs_dir\x18\x03 \x01(\tR\x07logsDir\x12*\n\x11\x65nable_access_log\x18\x04 \x01(\x08R\x0f\x65nableAccessLog\x12\x41\n\x1d\x61\x64\x64itional_log_standard_attrs\x18\x05 \x03(\tR\x1a\x61\x64\x64itionalLogStandardAttrs\"\xc9\x02\n\x13RequestRouterConfig\x12\x42\n\x1e_serialized_request_router_cls\x18\x01 \x01(\x0cR\x1aSerializedRequestRouterCls\x12\x30\n\x14request_router_class\x18\x02 \x01(\tR\x12requestRouterClass\x12\x42\n\x1erequest_routing_stats_period_s\x18\x03 \x01(\x01R\x1arequestRoutingStatsPeriodS\x12\x44\n\x1frequest_routing_stats_timeout_s\x18\x04 \x01(\x01R\x1brequestRoutingStatsTimeoutS\x12\x32\n\x15request_router_kwargs\x18\x05 \x01(\x0cR\x13requestRouterKwargs\"\xda\x06\n\x10\x44\x65ploymentConfig\x12!\n\x0cnum_replicas\x18\x01 \x01(\x05R\x0bnumReplicas\x12\x30\n\x14max_ongoing_requests\x18\x02 \x01(\x05R\x12maxOngoingRequests\x12.\n\x13max_queued_requests\x18\x03 \x01(\x05R\x11maxQueuedRequests\x12\x1f\n\x0buser_config\x18\x04 \x01(\x0cR\nuserConfig\x12@\n\x1dgraceful_shutdown_wait_loop_s\x18\x05 \x01(\x01R\x19gracefulShutdownWaitLoopS\x12=\n\x1bgraceful_shutdown_timeout_s\x18\x06 \x01(\x01R\x18gracefulShutdownTimeoutS\x12\x31\n\x15health_check_period_s\x18\x07 \x01(\x01R\x12healthCheckPeriodS\x12\x33\n\x16health_check_timeout_s\x18\x08 \x01(\x01R\x13healthCheckTimeoutS\x12*\n\x11is_cross_language\x18\t \x01(\x08R\x0fisCrossLanguage\x12N\n\x13\x64\x65ployment_language\x18\n \x01(\x0e\x32\x1d.ray.serve.DeploymentLanguageR\x12\x64\x65ploymentLanguage\x12K\n\x12\x61utoscaling_config\x18\x0b \x01(\x0b\x32\x1c.ray.serve.AutoscalingConfigR\x11\x61utoscalingConfig\x12\x18\n\x07version\x18\x0c \x01(\tR\x07version\x12?\n\x1cuser_configured_option_names\x18\r \x03(\tR\x19userConfiguredOptionNames\x12?\n\x0elogging_config\x18\x0e \x01(\x0b\x32\x18.ray.serve.LoggingConfigR\rloggingConfig\x12R\n\x15request_router_config\x18\x13 \x01(\x0b\x32\x1e.ray.serve.RequestRouterConfigR\x13requestRouterConfig\"\xc8\x02\n\x0fRequestMetadata\x12\x1d\n\nrequest_id\x18\x01 \x01(\tR\trequestId\x12.\n\x13internal_request_id\x18\x02 \x01(\tR\x11internalRequestId\x12\x1f\n\x0b\x63\x61ll_method\x18\x03 \x01(\tR\ncallMethod\x12\x41\n\x07\x63ontext\x18\x04 \x03(\x0b\x32\'.ray.serve.RequestMetadata.ContextEntryR\x07\x63ontext\x12\x30\n\x14multiplexed_model_id\x18\x05 \x01(\tR\x12multiplexedModelId\x12\x14\n\x05route\x18\x06 \x01(\tR\x05route\x1a:\n\x0c\x43ontextEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\"$\n\x0eRequestWrapper\x12\x12\n\x04\x62ody\x18\x01 \x01(\x0cR\x04\x62ody\"Y\n\rUpdatedObject\x12\'\n\x0fobject_snapshot\x18\x01 \x01(\x0cR\x0eobjectSnapshot\x12\x1f\n\x0bsnapshot_id\x18\x02 \x01(\x05R\nsnapshotId\"\xbb\x01\n\x0fLongPollRequest\x12\x62\n\x14keys_to_snapshot_ids\x18\x01 \x03(\x0b\x32\x31.ray.serve.LongPollRequest.KeysToSnapshotIdsEntryR\x11keysToSnapshotIds\x1a\x44\n\x16KeysToSnapshotIdsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\x05R\x05value:\x02\x38\x01\"\xc5\x01\n\x0eLongPollResult\x12V\n\x0fupdated_objects\x18\x01 \x03(\x0b\x32-.ray.serve.LongPollResult.UpdatedObjectsEntryR\x0eupdatedObjects\x1a[\n\x13UpdatedObjectsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x18.ray.serve.UpdatedObjectR\x05value:\x02\x38\x01\"\xc1\x01\n\x0c\x45ndpointInfo\x12#\n\rendpoint_name\x18\x01 \x01(\tR\x0c\x65ndpointName\x12\x14\n\x05route\x18\x02 \x01(\tR\x05route\x12;\n\x06\x63onfig\x18\x03 \x03(\x0b\x32#.ray.serve.EndpointInfo.ConfigEntryR\x06\x63onfig\x1a\x39\n\x0b\x43onfigEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\"\xa9\x01\n\x0b\x45ndpointSet\x12\x43\n\tendpoints\x18\x01 \x03(\x0b\x32%.ray.serve.EndpointSet.EndpointsEntryR\tendpoints\x1aU\n\x0e\x45ndpointsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12-\n\x05value\x18\x02 \x01(\x0b\x32\x17.ray.serve.EndpointInfoR\x05value:\x02\x38\x01\"%\n\rActorNameList\x12\x14\n\x05names\x18\x01 \x03(\tR\x05names\"^\n\x14\x44\x65ploymentTargetInfo\x12#\n\rreplica_names\x18\x01 \x03(\tR\x0creplicaNames\x12!\n\x0cis_available\x18\x02 \x01(\x08R\x0bisAvailable\"\xd1\x02\n\x11\x44\x65ploymentVersion\x12!\n\x0c\x63ode_version\x18\x01 \x01(\tR\x0b\x63odeVersion\x12H\n\x11\x64\x65ployment_config\x18\x02 \x01(\x0b\x32\x1b.ray.serve.DeploymentConfigR\x10\x64\x65ploymentConfig\x12*\n\x11ray_actor_options\x18\x03 \x01(\tR\x0frayActorOptions\x12\x36\n\x17placement_group_bundles\x18\x04 \x01(\tR\x15placementGroupBundles\x12\x38\n\x18placement_group_strategy\x18\x05 \x01(\tR\x16placementGroupStrategy\x12\x31\n\x15max_replicas_per_node\x18\x06 \x01(\x05R\x12maxReplicasPerNode\"\xf5\x02\n\rReplicaConfig\x12.\n\x13\x64\x65ployment_def_name\x18\x01 \x01(\tR\x11\x64\x65ploymentDefName\x12%\n\x0e\x64\x65ployment_def\x18\x02 \x01(\x0cR\rdeploymentDef\x12\x1b\n\tinit_args\x18\x03 \x01(\x0cR\x08initArgs\x12\x1f\n\x0binit_kwargs\x18\x04 \x01(\x0cR\ninitKwargs\x12*\n\x11ray_actor_options\x18\x05 \x01(\tR\x0frayActorOptions\x12\x36\n\x17placement_group_bundles\x18\x06 \x01(\tR\x15placementGroupBundles\x12\x38\n\x18placement_group_strategy\x18\x07 \x01(\tR\x16placementGroupStrategy\x12\x31\n\x15max_replicas_per_node\x18\x08 \x01(\x05R\x12maxReplicasPerNode\"\xb5\x03\n\x0e\x44\x65ploymentInfo\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12H\n\x11\x64\x65ployment_config\x18\x02 \x01(\x0b\x32\x1b.ray.serve.DeploymentConfigR\x10\x64\x65ploymentConfig\x12?\n\x0ereplica_config\x18\x03 \x01(\x0b\x32\x18.ray.serve.ReplicaConfigR\rreplicaConfig\x12\"\n\rstart_time_ms\x18\x04 \x01(\x03R\x0bstartTimeMs\x12\x1d\n\nactor_name\x18\x05 \x01(\tR\tactorName\x12\x18\n\x07version\x18\x06 \x01(\tR\x07version\x12\x1e\n\x0b\x65nd_time_ms\x18\x07 \x01(\x03R\tendTimeMs\x12\'\n\x0ftarget_capacity\x18\x08 \x01(\x01R\x0etargetCapacity\x12^\n\x19target_capacity_direction\x18\t \x01(\x0e\x32\".ray.serve.TargetCapacityDirectionR\x17targetCapacityDirection\"k\n\x0f\x44\x65ploymentRoute\x12\x42\n\x0f\x64\x65ployment_info\x18\x01 \x01(\x0b\x32\x19.ray.serve.DeploymentInfoR\x0e\x64\x65ploymentInfo\x12\x14\n\x05route\x18\x02 \x01(\tR\x05route\"^\n\x13\x44\x65ploymentRouteList\x12G\n\x11\x64\x65ployment_routes\x18\x01 \x03(\x0b\x32\x1a.ray.serve.DeploymentRouteR\x10\x64\x65ploymentRoutes\"\xc4\x01\n\x14\x44\x65ploymentStatusInfo\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x33\n\x06status\x18\x02 \x01(\x0e\x32\x1b.ray.serve.DeploymentStatusR\x06status\x12\x18\n\x07message\x18\x03 \x01(\tR\x07message\x12I\n\x0estatus_trigger\x18\x04 \x01(\x0e\x32\".ray.serve.DeploymentStatusTriggerR\rstatusTrigger\"s\n\x18\x44\x65ploymentStatusInfoList\x12W\n\x17\x64\x65ployment_status_infos\x18\x01 \x03(\x0b\x32\x1f.ray.serve.DeploymentStatusInfoR\x15\x64\x65ploymentStatusInfos\"\x9a\x01\n\x15\x41pplicationStatusInfo\x12\x34\n\x06status\x18\x01 \x01(\x0e\x32\x1c.ray.serve.ApplicationStatusR\x06status\x12\x18\n\x07message\x18\x02 \x01(\tR\x07message\x12\x31\n\x14\x64\x65ployment_timestamp\x18\x03 \x01(\x01R\x13\x64\x65ploymentTimestamp\"\xbb\x01\n\x0eStatusOverview\x12?\n\napp_status\x18\x01 \x01(\x0b\x32 .ray.serve.ApplicationStatusInfoR\tappStatus\x12T\n\x13\x64\x65ployment_statuses\x18\x02 \x01(\x0b\x32#.ray.serve.DeploymentStatusInfoListR\x12\x64\x65ploymentStatuses\x12\x12\n\x04name\x18\x03 \x01(\tR\x04name\"\x19\n\x17ListApplicationsRequest\"G\n\x18ListApplicationsResponse\x12+\n\x11\x61pplication_names\x18\x01 \x03(\tR\x10\x61pplicationNames\"\x10\n\x0eHealthzRequest\"+\n\x0fHealthzResponse\x12\x18\n\x07message\x18\x01 \x01(\tR\x07message\"L\n\x12UserDefinedMessage\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n\x03\x66oo\x18\x02 \x01(\tR\x03\x66oo\x12\x10\n\x03num\x18\x03 \x01(\x03R\x03num\"H\n\x13UserDefinedResponse\x12\x1a\n\x08greeting\x18\x01 \x01(\tR\x08greeting\x12\x15\n\x06num_x2\x18\x02 \x01(\x03R\x05numX2\"\x15\n\x13UserDefinedMessage2\"2\n\x14UserDefinedResponse2\x12\x1a\n\x08greeting\x18\x01 \x01(\tR\x08greeting\"T\n\x0c\x46ruitAmounts\x12\x16\n\x06orange\x18\x01 \x01(\x03R\x06orange\x12\x14\n\x05\x61pple\x18\x02 \x01(\x03R\x05\x61pple\x12\x16\n\x06\x62\x61nana\x18\x03 \x01(\x03R\x06\x62\x61nana\"\"\n\nFruitCosts\x12\x14\n\x05\x63osts\x18\x01 \x01(\x02R\x05\x63osts\"\x1f\n\tArrayData\x12\x12\n\x04nums\x18\x01 \x03(\x02R\x04nums\" \n\nStringData\x12\x12\n\x04\x64\x61ta\x18\x01 \x01(\tR\x04\x64\x61ta\"%\n\x0bModelOutput\x12\x16\n\x06output\x18\x01 \x01(\x02R\x06output\"\xb8\x02\n\x0e\x44\x65ploymentArgs\x12\'\n\x0f\x64\x65ployment_name\x18\x01 \x01(\tR\x0e\x64\x65ploymentName\x12+\n\x11\x64\x65ployment_config\x18\x02 \x01(\x0cR\x10\x64\x65ploymentConfig\x12%\n\x0ereplica_config\x18\x03 \x01(\x0cR\rreplicaConfig\x12&\n\x0f\x64\x65ployer_job_id\x18\x04 \x01(\tR\rdeployerJobId\x12&\n\x0croute_prefix\x18\x05 \x01(\tH\x00R\x0broutePrefix\x88\x01\x01\x12\x18\n\x07ingress\x18\x06 \x01(\x08R\x07ingress\x12 \n\tdocs_path\x18\x07 \x01(\tH\x01R\x08\x64ocsPath\x88\x01\x01\x42\x0f\n\r_route_prefixB\x0c\n\n_docs_path*\"\n\x0c\x45ncodingType\x12\x08\n\x04TEXT\x10\x00\x12\x08\n\x04JSON\x10\x01**\n\x12\x44\x65ploymentLanguage\x12\n\n\x06PYTHON\x10\x00\x12\x08\n\x04JAVA\x10\x01*6\n\x17TargetCapacityDirection\x12\t\n\x05UNSET\x10\x00\x12\x06\n\x02UP\x10\x01\x12\x08\n\x04\x44OWN\x10\x02*\xdb\x01\n\x10\x44\x65ploymentStatus\x12\x1e\n\x1a\x44\x45PLOYMENT_STATUS_UPDATING\x10\x00\x12\x1d\n\x19\x44\x45PLOYMENT_STATUS_HEALTHY\x10\x01\x12\x1f\n\x1b\x44\x45PLOYMENT_STATUS_UNHEALTHY\x10\x02\x12#\n\x1f\x44\x45PLOYMENT_STATUS_DEPLOY_FAILED\x10\x03\x12\x1f\n\x1b\x44\x45PLOYMENT_STATUS_UPSCALING\x10\x04\x12!\n\x1d\x44\x45PLOYMENT_STATUS_DOWNSCALING\x10\x05*\xfe\x03\n\x17\x44\x65ploymentStatusTrigger\x12)\n%DEPLOYMENT_STATUS_TRIGGER_UNSPECIFIED\x10\x00\x12\x33\n/DEPLOYMENT_STATUS_TRIGGER_CONFIG_UPDATE_STARTED\x10\x01\x12\x35\n1DEPLOYMENT_STATUS_TRIGGER_CONFIG_UPDATE_COMPLETED\x10\x02\x12/\n+DEPLOYMENT_STATUS_TRIGGER_UPSCALE_COMPLETED\x10\x03\x12\x31\n-DEPLOYMENT_STATUS_TRIGGER_DOWNSCALE_COMPLETED\x10\x04\x12)\n%DEPLOYMENT_STATUS_TRIGGER_AUTOSCALING\x10\x05\x12\x34\n0DEPLOYMENT_STATUS_TRIGGER_REPLICA_STARTUP_FAILED\x10\x06\x12\x31\n-DEPLOYMENT_STATUS_TRIGGER_HEALTH_CHECK_FAILED\x10\x07\x12,\n(DEPLOYMENT_STATUS_TRIGGER_INTERNAL_ERROR\x10\x08\x12&\n\"DEPLOYMENT_STATUS_TRIGGER_DELETING\x10\t*\xe2\x01\n\x11\x41pplicationStatus\x12 \n\x1c\x41PPLICATION_STATUS_DEPLOYING\x10\x00\x12\x1e\n\x1a\x41PPLICATION_STATUS_RUNNING\x10\x01\x12$\n APPLICATION_STATUS_DEPLOY_FAILED\x10\x02\x12\x1f\n\x1b\x41PPLICATION_STATUS_DELETING\x10\x03\x12\"\n\x1e\x41PPLICATION_STATUS_NOT_STARTED\x10\x05\x12 \n\x1c\x41PPLICATION_STATUS_UNHEALTHY\x10\x06\x32\xb3\x01\n\x12RayServeAPIService\x12[\n\x10ListApplications\x12\".ray.serve.ListApplicationsRequest\x1a#.ray.serve.ListApplicationsResponse\x12@\n\x07Healthz\x12\x19.ray.serve.HealthzRequest\x1a\x1a.ray.serve.HealthzResponse2\xc3\x02\n\x12UserDefinedService\x12I\n\x08__call__\x12\x1d.ray.serve.UserDefinedMessage\x1a\x1e.ray.serve.UserDefinedResponse\x12H\n\x07Method1\x12\x1d.ray.serve.UserDefinedMessage\x1a\x1e.ray.serve.UserDefinedResponse\x12J\n\x07Method2\x12\x1e.ray.serve.UserDefinedMessage2\x1a\x1f.ray.serve.UserDefinedResponse2\x12L\n\tStreaming\x12\x1d.ray.serve.UserDefinedMessage\x1a\x1e.ray.serve.UserDefinedResponse0\x01\x32L\n\x0c\x46ruitService\x12<\n\nFruitStand\x12\x17.ray.serve.FruitAmounts\x1a\x15.ray.serve.FruitCosts2\x98\x01\n\x18RayServeBenchmarkService\x12\x39\n\tgrpc_call\x12\x14.ray.serve.ArrayData\x1a\x16.ray.serve.ModelOutput\x12\x41\n\x10\x63\x61ll_with_string\x12\x15.ray.serve.StringData\x1a\x16.ray.serve.ModelOutputB\'\n\x16io.ray.serve.generatedB\x0bServeProtosP\x01\x62\x06proto3') + +_ENCODINGTYPE = DESCRIPTOR.enum_types_by_name['EncodingType'] +EncodingType = enum_type_wrapper.EnumTypeWrapper(_ENCODINGTYPE) +_DEPLOYMENTLANGUAGE = DESCRIPTOR.enum_types_by_name['DeploymentLanguage'] +DeploymentLanguage = enum_type_wrapper.EnumTypeWrapper(_DEPLOYMENTLANGUAGE) +_TARGETCAPACITYDIRECTION = DESCRIPTOR.enum_types_by_name['TargetCapacityDirection'] +TargetCapacityDirection = enum_type_wrapper.EnumTypeWrapper(_TARGETCAPACITYDIRECTION) +_DEPLOYMENTSTATUS = DESCRIPTOR.enum_types_by_name['DeploymentStatus'] +DeploymentStatus = enum_type_wrapper.EnumTypeWrapper(_DEPLOYMENTSTATUS) +_DEPLOYMENTSTATUSTRIGGER = DESCRIPTOR.enum_types_by_name['DeploymentStatusTrigger'] +DeploymentStatusTrigger = enum_type_wrapper.EnumTypeWrapper(_DEPLOYMENTSTATUSTRIGGER) +_APPLICATIONSTATUS = DESCRIPTOR.enum_types_by_name['ApplicationStatus'] +ApplicationStatus = enum_type_wrapper.EnumTypeWrapper(_APPLICATIONSTATUS) +TEXT = 0 +JSON = 1 +PYTHON = 0 +JAVA = 1 +UNSET = 0 +UP = 1 +DOWN = 2 +DEPLOYMENT_STATUS_UPDATING = 0 +DEPLOYMENT_STATUS_HEALTHY = 1 +DEPLOYMENT_STATUS_UNHEALTHY = 2 +DEPLOYMENT_STATUS_DEPLOY_FAILED = 3 +DEPLOYMENT_STATUS_UPSCALING = 4 +DEPLOYMENT_STATUS_DOWNSCALING = 5 +DEPLOYMENT_STATUS_TRIGGER_UNSPECIFIED = 0 +DEPLOYMENT_STATUS_TRIGGER_CONFIG_UPDATE_STARTED = 1 +DEPLOYMENT_STATUS_TRIGGER_CONFIG_UPDATE_COMPLETED = 2 +DEPLOYMENT_STATUS_TRIGGER_UPSCALE_COMPLETED = 3 +DEPLOYMENT_STATUS_TRIGGER_DOWNSCALE_COMPLETED = 4 +DEPLOYMENT_STATUS_TRIGGER_AUTOSCALING = 5 +DEPLOYMENT_STATUS_TRIGGER_REPLICA_STARTUP_FAILED = 6 +DEPLOYMENT_STATUS_TRIGGER_HEALTH_CHECK_FAILED = 7 +DEPLOYMENT_STATUS_TRIGGER_INTERNAL_ERROR = 8 +DEPLOYMENT_STATUS_TRIGGER_DELETING = 9 +APPLICATION_STATUS_DEPLOYING = 0 +APPLICATION_STATUS_RUNNING = 1 +APPLICATION_STATUS_DEPLOY_FAILED = 2 +APPLICATION_STATUS_DELETING = 3 +APPLICATION_STATUS_NOT_STARTED = 5 +APPLICATION_STATUS_UNHEALTHY = 6 + + +_AUTOSCALINGPOLICY = DESCRIPTOR.message_types_by_name['AutoscalingPolicy'] +_AUTOSCALINGCONFIG = DESCRIPTOR.message_types_by_name['AutoscalingConfig'] +_LOGGINGCONFIG = DESCRIPTOR.message_types_by_name['LoggingConfig'] +_REQUESTROUTERCONFIG = DESCRIPTOR.message_types_by_name['RequestRouterConfig'] +_DEPLOYMENTCONFIG = DESCRIPTOR.message_types_by_name['DeploymentConfig'] +_REQUESTMETADATA = DESCRIPTOR.message_types_by_name['RequestMetadata'] +_REQUESTMETADATA_CONTEXTENTRY = _REQUESTMETADATA.nested_types_by_name['ContextEntry'] +_REQUESTWRAPPER = DESCRIPTOR.message_types_by_name['RequestWrapper'] +_UPDATEDOBJECT = DESCRIPTOR.message_types_by_name['UpdatedObject'] +_LONGPOLLREQUEST = DESCRIPTOR.message_types_by_name['LongPollRequest'] +_LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY = _LONGPOLLREQUEST.nested_types_by_name['KeysToSnapshotIdsEntry'] +_LONGPOLLRESULT = DESCRIPTOR.message_types_by_name['LongPollResult'] +_LONGPOLLRESULT_UPDATEDOBJECTSENTRY = _LONGPOLLRESULT.nested_types_by_name['UpdatedObjectsEntry'] +_ENDPOINTINFO = DESCRIPTOR.message_types_by_name['EndpointInfo'] +_ENDPOINTINFO_CONFIGENTRY = _ENDPOINTINFO.nested_types_by_name['ConfigEntry'] +_ENDPOINTSET = DESCRIPTOR.message_types_by_name['EndpointSet'] +_ENDPOINTSET_ENDPOINTSENTRY = _ENDPOINTSET.nested_types_by_name['EndpointsEntry'] +_ACTORNAMELIST = DESCRIPTOR.message_types_by_name['ActorNameList'] +_DEPLOYMENTTARGETINFO = DESCRIPTOR.message_types_by_name['DeploymentTargetInfo'] +_DEPLOYMENTVERSION = DESCRIPTOR.message_types_by_name['DeploymentVersion'] +_REPLICACONFIG = DESCRIPTOR.message_types_by_name['ReplicaConfig'] +_DEPLOYMENTINFO = DESCRIPTOR.message_types_by_name['DeploymentInfo'] +_DEPLOYMENTROUTE = DESCRIPTOR.message_types_by_name['DeploymentRoute'] +_DEPLOYMENTROUTELIST = DESCRIPTOR.message_types_by_name['DeploymentRouteList'] +_DEPLOYMENTSTATUSINFO = DESCRIPTOR.message_types_by_name['DeploymentStatusInfo'] +_DEPLOYMENTSTATUSINFOLIST = DESCRIPTOR.message_types_by_name['DeploymentStatusInfoList'] +_APPLICATIONSTATUSINFO = DESCRIPTOR.message_types_by_name['ApplicationStatusInfo'] +_STATUSOVERVIEW = DESCRIPTOR.message_types_by_name['StatusOverview'] +_LISTAPPLICATIONSREQUEST = DESCRIPTOR.message_types_by_name['ListApplicationsRequest'] +_LISTAPPLICATIONSRESPONSE = DESCRIPTOR.message_types_by_name['ListApplicationsResponse'] +_HEALTHZREQUEST = DESCRIPTOR.message_types_by_name['HealthzRequest'] +_HEALTHZRESPONSE = DESCRIPTOR.message_types_by_name['HealthzResponse'] +_USERDEFINEDMESSAGE = DESCRIPTOR.message_types_by_name['UserDefinedMessage'] +_USERDEFINEDRESPONSE = DESCRIPTOR.message_types_by_name['UserDefinedResponse'] +_USERDEFINEDMESSAGE2 = DESCRIPTOR.message_types_by_name['UserDefinedMessage2'] +_USERDEFINEDRESPONSE2 = DESCRIPTOR.message_types_by_name['UserDefinedResponse2'] +_FRUITAMOUNTS = DESCRIPTOR.message_types_by_name['FruitAmounts'] +_FRUITCOSTS = DESCRIPTOR.message_types_by_name['FruitCosts'] +_ARRAYDATA = DESCRIPTOR.message_types_by_name['ArrayData'] +_STRINGDATA = DESCRIPTOR.message_types_by_name['StringData'] +_MODELOUTPUT = DESCRIPTOR.message_types_by_name['ModelOutput'] +_DEPLOYMENTARGS = DESCRIPTOR.message_types_by_name['DeploymentArgs'] +AutoscalingPolicy = _reflection.GeneratedProtocolMessageType('AutoscalingPolicy', (_message.Message,), { + 'DESCRIPTOR' : _AUTOSCALINGPOLICY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.AutoscalingPolicy) + }) +_sym_db.RegisterMessage(AutoscalingPolicy) + +AutoscalingConfig = _reflection.GeneratedProtocolMessageType('AutoscalingConfig', (_message.Message,), { + 'DESCRIPTOR' : _AUTOSCALINGCONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.AutoscalingConfig) + }) +_sym_db.RegisterMessage(AutoscalingConfig) + +LoggingConfig = _reflection.GeneratedProtocolMessageType('LoggingConfig', (_message.Message,), { + 'DESCRIPTOR' : _LOGGINGCONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LoggingConfig) + }) +_sym_db.RegisterMessage(LoggingConfig) + +RequestRouterConfig = _reflection.GeneratedProtocolMessageType('RequestRouterConfig', (_message.Message,), { + 'DESCRIPTOR' : _REQUESTROUTERCONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.RequestRouterConfig) + }) +_sym_db.RegisterMessage(RequestRouterConfig) + +DeploymentConfig = _reflection.GeneratedProtocolMessageType('DeploymentConfig', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTCONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentConfig) + }) +_sym_db.RegisterMessage(DeploymentConfig) + +RequestMetadata = _reflection.GeneratedProtocolMessageType('RequestMetadata', (_message.Message,), { + + 'ContextEntry' : _reflection.GeneratedProtocolMessageType('ContextEntry', (_message.Message,), { + 'DESCRIPTOR' : _REQUESTMETADATA_CONTEXTENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.RequestMetadata.ContextEntry) + }) + , + 'DESCRIPTOR' : _REQUESTMETADATA, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.RequestMetadata) + }) +_sym_db.RegisterMessage(RequestMetadata) +_sym_db.RegisterMessage(RequestMetadata.ContextEntry) + +RequestWrapper = _reflection.GeneratedProtocolMessageType('RequestWrapper', (_message.Message,), { + 'DESCRIPTOR' : _REQUESTWRAPPER, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.RequestWrapper) + }) +_sym_db.RegisterMessage(RequestWrapper) + +UpdatedObject = _reflection.GeneratedProtocolMessageType('UpdatedObject', (_message.Message,), { + 'DESCRIPTOR' : _UPDATEDOBJECT, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UpdatedObject) + }) +_sym_db.RegisterMessage(UpdatedObject) + +LongPollRequest = _reflection.GeneratedProtocolMessageType('LongPollRequest', (_message.Message,), { + + 'KeysToSnapshotIdsEntry' : _reflection.GeneratedProtocolMessageType('KeysToSnapshotIdsEntry', (_message.Message,), { + 'DESCRIPTOR' : _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LongPollRequest.KeysToSnapshotIdsEntry) + }) + , + 'DESCRIPTOR' : _LONGPOLLREQUEST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LongPollRequest) + }) +_sym_db.RegisterMessage(LongPollRequest) +_sym_db.RegisterMessage(LongPollRequest.KeysToSnapshotIdsEntry) + +LongPollResult = _reflection.GeneratedProtocolMessageType('LongPollResult', (_message.Message,), { + + 'UpdatedObjectsEntry' : _reflection.GeneratedProtocolMessageType('UpdatedObjectsEntry', (_message.Message,), { + 'DESCRIPTOR' : _LONGPOLLRESULT_UPDATEDOBJECTSENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LongPollResult.UpdatedObjectsEntry) + }) + , + 'DESCRIPTOR' : _LONGPOLLRESULT, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LongPollResult) + }) +_sym_db.RegisterMessage(LongPollResult) +_sym_db.RegisterMessage(LongPollResult.UpdatedObjectsEntry) + +EndpointInfo = _reflection.GeneratedProtocolMessageType('EndpointInfo', (_message.Message,), { + + 'ConfigEntry' : _reflection.GeneratedProtocolMessageType('ConfigEntry', (_message.Message,), { + 'DESCRIPTOR' : _ENDPOINTINFO_CONFIGENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.EndpointInfo.ConfigEntry) + }) + , + 'DESCRIPTOR' : _ENDPOINTINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.EndpointInfo) + }) +_sym_db.RegisterMessage(EndpointInfo) +_sym_db.RegisterMessage(EndpointInfo.ConfigEntry) + +EndpointSet = _reflection.GeneratedProtocolMessageType('EndpointSet', (_message.Message,), { + + 'EndpointsEntry' : _reflection.GeneratedProtocolMessageType('EndpointsEntry', (_message.Message,), { + 'DESCRIPTOR' : _ENDPOINTSET_ENDPOINTSENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.EndpointSet.EndpointsEntry) + }) + , + 'DESCRIPTOR' : _ENDPOINTSET, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.EndpointSet) + }) +_sym_db.RegisterMessage(EndpointSet) +_sym_db.RegisterMessage(EndpointSet.EndpointsEntry) + +ActorNameList = _reflection.GeneratedProtocolMessageType('ActorNameList', (_message.Message,), { + 'DESCRIPTOR' : _ACTORNAMELIST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ActorNameList) + }) +_sym_db.RegisterMessage(ActorNameList) + +DeploymentTargetInfo = _reflection.GeneratedProtocolMessageType('DeploymentTargetInfo', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTTARGETINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentTargetInfo) + }) +_sym_db.RegisterMessage(DeploymentTargetInfo) + +DeploymentVersion = _reflection.GeneratedProtocolMessageType('DeploymentVersion', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTVERSION, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentVersion) + }) +_sym_db.RegisterMessage(DeploymentVersion) + +ReplicaConfig = _reflection.GeneratedProtocolMessageType('ReplicaConfig', (_message.Message,), { + 'DESCRIPTOR' : _REPLICACONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ReplicaConfig) + }) +_sym_db.RegisterMessage(ReplicaConfig) + +DeploymentInfo = _reflection.GeneratedProtocolMessageType('DeploymentInfo', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentInfo) + }) +_sym_db.RegisterMessage(DeploymentInfo) + +DeploymentRoute = _reflection.GeneratedProtocolMessageType('DeploymentRoute', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTROUTE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentRoute) + }) +_sym_db.RegisterMessage(DeploymentRoute) + +DeploymentRouteList = _reflection.GeneratedProtocolMessageType('DeploymentRouteList', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTROUTELIST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentRouteList) + }) +_sym_db.RegisterMessage(DeploymentRouteList) + +DeploymentStatusInfo = _reflection.GeneratedProtocolMessageType('DeploymentStatusInfo', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTSTATUSINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentStatusInfo) + }) +_sym_db.RegisterMessage(DeploymentStatusInfo) + +DeploymentStatusInfoList = _reflection.GeneratedProtocolMessageType('DeploymentStatusInfoList', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTSTATUSINFOLIST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentStatusInfoList) + }) +_sym_db.RegisterMessage(DeploymentStatusInfoList) + +ApplicationStatusInfo = _reflection.GeneratedProtocolMessageType('ApplicationStatusInfo', (_message.Message,), { + 'DESCRIPTOR' : _APPLICATIONSTATUSINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ApplicationStatusInfo) + }) +_sym_db.RegisterMessage(ApplicationStatusInfo) + +StatusOverview = _reflection.GeneratedProtocolMessageType('StatusOverview', (_message.Message,), { + 'DESCRIPTOR' : _STATUSOVERVIEW, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.StatusOverview) + }) +_sym_db.RegisterMessage(StatusOverview) + +ListApplicationsRequest = _reflection.GeneratedProtocolMessageType('ListApplicationsRequest', (_message.Message,), { + 'DESCRIPTOR' : _LISTAPPLICATIONSREQUEST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ListApplicationsRequest) + }) +_sym_db.RegisterMessage(ListApplicationsRequest) + +ListApplicationsResponse = _reflection.GeneratedProtocolMessageType('ListApplicationsResponse', (_message.Message,), { + 'DESCRIPTOR' : _LISTAPPLICATIONSRESPONSE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ListApplicationsResponse) + }) +_sym_db.RegisterMessage(ListApplicationsResponse) + +HealthzRequest = _reflection.GeneratedProtocolMessageType('HealthzRequest', (_message.Message,), { + 'DESCRIPTOR' : _HEALTHZREQUEST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.HealthzRequest) + }) +_sym_db.RegisterMessage(HealthzRequest) + +HealthzResponse = _reflection.GeneratedProtocolMessageType('HealthzResponse', (_message.Message,), { + 'DESCRIPTOR' : _HEALTHZRESPONSE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.HealthzResponse) + }) +_sym_db.RegisterMessage(HealthzResponse) + +UserDefinedMessage = _reflection.GeneratedProtocolMessageType('UserDefinedMessage', (_message.Message,), { + 'DESCRIPTOR' : _USERDEFINEDMESSAGE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UserDefinedMessage) + }) +_sym_db.RegisterMessage(UserDefinedMessage) + +UserDefinedResponse = _reflection.GeneratedProtocolMessageType('UserDefinedResponse', (_message.Message,), { + 'DESCRIPTOR' : _USERDEFINEDRESPONSE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UserDefinedResponse) + }) +_sym_db.RegisterMessage(UserDefinedResponse) + +UserDefinedMessage2 = _reflection.GeneratedProtocolMessageType('UserDefinedMessage2', (_message.Message,), { + 'DESCRIPTOR' : _USERDEFINEDMESSAGE2, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UserDefinedMessage2) + }) +_sym_db.RegisterMessage(UserDefinedMessage2) + +UserDefinedResponse2 = _reflection.GeneratedProtocolMessageType('UserDefinedResponse2', (_message.Message,), { + 'DESCRIPTOR' : _USERDEFINEDRESPONSE2, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UserDefinedResponse2) + }) +_sym_db.RegisterMessage(UserDefinedResponse2) + +FruitAmounts = _reflection.GeneratedProtocolMessageType('FruitAmounts', (_message.Message,), { + 'DESCRIPTOR' : _FRUITAMOUNTS, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.FruitAmounts) + }) +_sym_db.RegisterMessage(FruitAmounts) + +FruitCosts = _reflection.GeneratedProtocolMessageType('FruitCosts', (_message.Message,), { + 'DESCRIPTOR' : _FRUITCOSTS, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.FruitCosts) + }) +_sym_db.RegisterMessage(FruitCosts) + +ArrayData = _reflection.GeneratedProtocolMessageType('ArrayData', (_message.Message,), { + 'DESCRIPTOR' : _ARRAYDATA, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ArrayData) + }) +_sym_db.RegisterMessage(ArrayData) + +StringData = _reflection.GeneratedProtocolMessageType('StringData', (_message.Message,), { + 'DESCRIPTOR' : _STRINGDATA, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.StringData) + }) +_sym_db.RegisterMessage(StringData) + +ModelOutput = _reflection.GeneratedProtocolMessageType('ModelOutput', (_message.Message,), { + 'DESCRIPTOR' : _MODELOUTPUT, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ModelOutput) + }) +_sym_db.RegisterMessage(ModelOutput) + +DeploymentArgs = _reflection.GeneratedProtocolMessageType('DeploymentArgs', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTARGS, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentArgs) + }) +_sym_db.RegisterMessage(DeploymentArgs) + +_RAYSERVEAPISERVICE = DESCRIPTOR.services_by_name['RayServeAPIService'] +_USERDEFINEDSERVICE = DESCRIPTOR.services_by_name['UserDefinedService'] +_FRUITSERVICE = DESCRIPTOR.services_by_name['FruitService'] +_RAYSERVEBENCHMARKSERVICE = DESCRIPTOR.services_by_name['RayServeBenchmarkService'] +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\026io.ray.serve.generatedB\013ServeProtosP\001' + _REQUESTMETADATA_CONTEXTENTRY._options = None + _REQUESTMETADATA_CONTEXTENTRY._serialized_options = b'8\001' + _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY._options = None + _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY._serialized_options = b'8\001' + _LONGPOLLRESULT_UPDATEDOBJECTSENTRY._options = None + _LONGPOLLRESULT_UPDATEDOBJECTSENTRY._serialized_options = b'8\001' + _ENDPOINTINFO_CONFIGENTRY._options = None + _ENDPOINTINFO_CONFIGENTRY._serialized_options = b'8\001' + _ENDPOINTSET_ENDPOINTSENTRY._options = None + _ENDPOINTSET_ENDPOINTSENTRY._serialized_options = b'8\001' + _ENCODINGTYPE._serialized_start=6702 + _ENCODINGTYPE._serialized_end=6736 + _DEPLOYMENTLANGUAGE._serialized_start=6738 + _DEPLOYMENTLANGUAGE._serialized_end=6780 + _TARGETCAPACITYDIRECTION._serialized_start=6782 + _TARGETCAPACITYDIRECTION._serialized_end=6836 + _DEPLOYMENTSTATUS._serialized_start=6839 + _DEPLOYMENTSTATUS._serialized_end=7058 + _DEPLOYMENTSTATUSTRIGGER._serialized_start=7061 + _DEPLOYMENTSTATUSTRIGGER._serialized_end=7571 + _APPLICATIONSTATUS._serialized_start=7574 + _APPLICATIONSTATUS._serialized_end=7800 + _AUTOSCALINGPOLICY._serialized_start=43 + _AUTOSCALINGPOLICY._serialized_end=82 + _AUTOSCALINGCONFIG._serialized_start=85 + _AUTOSCALINGCONFIG._serialized_end=959 + _LOGGINGCONFIG._serialized_start=962 + _LOGGINGCONFIG._serialized_end=1197 + _REQUESTROUTERCONFIG._serialized_start=1200 + _REQUESTROUTERCONFIG._serialized_end=1529 + _DEPLOYMENTCONFIG._serialized_start=1532 + _DEPLOYMENTCONFIG._serialized_end=2390 + _REQUESTMETADATA._serialized_start=2393 + _REQUESTMETADATA._serialized_end=2721 + _REQUESTMETADATA_CONTEXTENTRY._serialized_start=2663 + _REQUESTMETADATA_CONTEXTENTRY._serialized_end=2721 + _REQUESTWRAPPER._serialized_start=2723 + _REQUESTWRAPPER._serialized_end=2759 + _UPDATEDOBJECT._serialized_start=2761 + _UPDATEDOBJECT._serialized_end=2850 + _LONGPOLLREQUEST._serialized_start=2853 + _LONGPOLLREQUEST._serialized_end=3040 + _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY._serialized_start=2972 + _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY._serialized_end=3040 + _LONGPOLLRESULT._serialized_start=3043 + _LONGPOLLRESULT._serialized_end=3240 + _LONGPOLLRESULT_UPDATEDOBJECTSENTRY._serialized_start=3149 + _LONGPOLLRESULT_UPDATEDOBJECTSENTRY._serialized_end=3240 + _ENDPOINTINFO._serialized_start=3243 + _ENDPOINTINFO._serialized_end=3436 + _ENDPOINTINFO_CONFIGENTRY._serialized_start=3379 + _ENDPOINTINFO_CONFIGENTRY._serialized_end=3436 + _ENDPOINTSET._serialized_start=3439 + _ENDPOINTSET._serialized_end=3608 + _ENDPOINTSET_ENDPOINTSENTRY._serialized_start=3523 + _ENDPOINTSET_ENDPOINTSENTRY._serialized_end=3608 + _ACTORNAMELIST._serialized_start=3610 + _ACTORNAMELIST._serialized_end=3647 + _DEPLOYMENTTARGETINFO._serialized_start=3649 + _DEPLOYMENTTARGETINFO._serialized_end=3743 + _DEPLOYMENTVERSION._serialized_start=3746 + _DEPLOYMENTVERSION._serialized_end=4083 + _REPLICACONFIG._serialized_start=4086 + _REPLICACONFIG._serialized_end=4459 + _DEPLOYMENTINFO._serialized_start=4462 + _DEPLOYMENTINFO._serialized_end=4899 + _DEPLOYMENTROUTE._serialized_start=4901 + _DEPLOYMENTROUTE._serialized_end=5008 + _DEPLOYMENTROUTELIST._serialized_start=5010 + _DEPLOYMENTROUTELIST._serialized_end=5104 + _DEPLOYMENTSTATUSINFO._serialized_start=5107 + _DEPLOYMENTSTATUSINFO._serialized_end=5303 + _DEPLOYMENTSTATUSINFOLIST._serialized_start=5305 + _DEPLOYMENTSTATUSINFOLIST._serialized_end=5420 + _APPLICATIONSTATUSINFO._serialized_start=5423 + _APPLICATIONSTATUSINFO._serialized_end=5577 + _STATUSOVERVIEW._serialized_start=5580 + _STATUSOVERVIEW._serialized_end=5767 + _LISTAPPLICATIONSREQUEST._serialized_start=5769 + _LISTAPPLICATIONSREQUEST._serialized_end=5794 + _LISTAPPLICATIONSRESPONSE._serialized_start=5796 + _LISTAPPLICATIONSRESPONSE._serialized_end=5867 + _HEALTHZREQUEST._serialized_start=5869 + _HEALTHZREQUEST._serialized_end=5885 + _HEALTHZRESPONSE._serialized_start=5887 + _HEALTHZRESPONSE._serialized_end=5930 + _USERDEFINEDMESSAGE._serialized_start=5932 + _USERDEFINEDMESSAGE._serialized_end=6008 + _USERDEFINEDRESPONSE._serialized_start=6010 + _USERDEFINEDRESPONSE._serialized_end=6082 + _USERDEFINEDMESSAGE2._serialized_start=6084 + _USERDEFINEDMESSAGE2._serialized_end=6105 + _USERDEFINEDRESPONSE2._serialized_start=6107 + _USERDEFINEDRESPONSE2._serialized_end=6157 + _FRUITAMOUNTS._serialized_start=6159 + _FRUITAMOUNTS._serialized_end=6243 + _FRUITCOSTS._serialized_start=6245 + _FRUITCOSTS._serialized_end=6279 + _ARRAYDATA._serialized_start=6281 + _ARRAYDATA._serialized_end=6312 + _STRINGDATA._serialized_start=6314 + _STRINGDATA._serialized_end=6346 + _MODELOUTPUT._serialized_start=6348 + _MODELOUTPUT._serialized_end=6385 + _DEPLOYMENTARGS._serialized_start=6388 + _DEPLOYMENTARGS._serialized_end=6700 + _RAYSERVEAPISERVICE._serialized_start=7803 + _RAYSERVEAPISERVICE._serialized_end=7982 + _USERDEFINEDSERVICE._serialized_start=7985 + _USERDEFINEDSERVICE._serialized_end=8308 + _FRUITSERVICE._serialized_start=8310 + _FRUITSERVICE._serialized_end=8386 + _RAYSERVEBENCHMARKSERVICE._serialized_start=8389 + _RAYSERVEBENCHMARKSERVICE._serialized_end=8541 +# @@protoc_insertion_point(module_scope) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/serve_pb2_grpc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/serve_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a0fbfd5beb60db0b27f1914bb396a55049dfb8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/generated/serve_pb2_grpc.py @@ -0,0 +1,414 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +from . import serve_pb2 as src_dot_ray_dot_protobuf_dot_serve__pb2 + + +class RayServeAPIServiceStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.ListApplications = channel.unary_unary( + '/ray.serve.RayServeAPIService/ListApplications', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsRequest.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsResponse.FromString, + ) + self.Healthz = channel.unary_unary( + '/ray.serve.RayServeAPIService/Healthz', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzRequest.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzResponse.FromString, + ) + + +class RayServeAPIServiceServicer(object): + """Missing associated documentation comment in .proto file.""" + + def ListApplications(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Healthz(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_RayServeAPIServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'ListApplications': grpc.unary_unary_rpc_method_handler( + servicer.ListApplications, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsRequest.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsResponse.SerializeToString, + ), + 'Healthz': grpc.unary_unary_rpc_method_handler( + servicer.Healthz, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzRequest.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'ray.serve.RayServeAPIService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class RayServeAPIService(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def ListApplications(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.RayServeAPIService/ListApplications', + src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsRequest.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Healthz(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.RayServeAPIService/Healthz', + src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzRequest.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + +class UserDefinedServiceStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.__call__ = channel.unary_unary( + '/ray.serve.UserDefinedService/__call__', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + ) + self.Method1 = channel.unary_unary( + '/ray.serve.UserDefinedService/Method1', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + ) + self.Method2 = channel.unary_unary( + '/ray.serve.UserDefinedService/Method2', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage2.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse2.FromString, + ) + self.Streaming = channel.unary_stream( + '/ray.serve.UserDefinedService/Streaming', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + ) + + +class UserDefinedServiceServicer(object): + """Missing associated documentation comment in .proto file.""" + + def __call__(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Method1(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Method2(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Streaming(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_UserDefinedServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + '__call__': grpc.unary_unary_rpc_method_handler( + servicer.__call__, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.SerializeToString, + ), + 'Method1': grpc.unary_unary_rpc_method_handler( + servicer.Method1, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.SerializeToString, + ), + 'Method2': grpc.unary_unary_rpc_method_handler( + servicer.Method2, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage2.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse2.SerializeToString, + ), + 'Streaming': grpc.unary_stream_rpc_method_handler( + servicer.Streaming, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'ray.serve.UserDefinedService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class UserDefinedService(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def __call__(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.UserDefinedService/__call__', + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Method1(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.UserDefinedService/Method1', + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Method2(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.UserDefinedService/Method2', + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage2.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse2.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Streaming(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_stream(request, target, '/ray.serve.UserDefinedService/Streaming', + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + +class FruitServiceStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.FruitStand = channel.unary_unary( + '/ray.serve.FruitService/FruitStand', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.FruitAmounts.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.FruitCosts.FromString, + ) + + +class FruitServiceServicer(object): + """Missing associated documentation comment in .proto file.""" + + def FruitStand(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_FruitServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'FruitStand': grpc.unary_unary_rpc_method_handler( + servicer.FruitStand, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.FruitAmounts.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.FruitCosts.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'ray.serve.FruitService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class FruitService(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def FruitStand(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.FruitService/FruitStand', + src_dot_ray_dot_protobuf_dot_serve__pb2.FruitAmounts.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.FruitCosts.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + +class RayServeBenchmarkServiceStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.grpc_call = channel.unary_unary( + '/ray.serve.RayServeBenchmarkService/grpc_call', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ArrayData.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.FromString, + ) + self.call_with_string = channel.unary_unary( + '/ray.serve.RayServeBenchmarkService/call_with_string', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.StringData.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.FromString, + ) + + +class RayServeBenchmarkServiceServicer(object): + """Missing associated documentation comment in .proto file.""" + + def grpc_call(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def call_with_string(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_RayServeBenchmarkServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'grpc_call': grpc.unary_unary_rpc_method_handler( + servicer.grpc_call, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ArrayData.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.SerializeToString, + ), + 'call_with_string': grpc.unary_unary_rpc_method_handler( + servicer.call_with_string, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.StringData.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'ray.serve.RayServeBenchmarkService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class RayServeBenchmarkService(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def grpc_call(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.RayServeBenchmarkService/grpc_call', + src_dot_ray_dot_protobuf_dot_serve__pb2.ArrayData.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def call_with_string(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.RayServeBenchmarkService/call_with_string', + src_dot_ray_dot_protobuf_dot_serve__pb2.StringData.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3b04709a0bae0264efcae2c509ab8a58f8fac7da --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__init__.py @@ -0,0 +1,368 @@ +from typing import TYPE_CHECKING, Any, Dict, Optional, Union + +from ray.llm._internal.serve.configs.server_models import ( + CloudMirrorConfig as _CloudMirrorConfig, + LLMConfig as _LLMConfig, + LLMServingArgs as _LLMServingArgs, + LoraConfig as _LoraConfig, + ModelLoadingConfig as _ModelLoadingConfig, +) + +# For backward compatibility +from ray.llm._internal.serve.deployments.llm.llm_server import ( + LLMServer as _LLMServer, +) +from ray.llm._internal.serve.deployments.routers.router import ( + LLMRouter as _LLMRouter, +) + +# Using Deprecated from rllib since they are retuning better messages. +# TODO: Ray core should inherit that. +from ray.rllib.utils.deprecation import Deprecated +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.serve.deployment import Application + + +########## +# Models +########## + + +@PublicAPI(stability="alpha") +class LLMConfig(_LLMConfig): + """The configuration for starting an LLM deployment.""" + + pass + + +@PublicAPI(stability="alpha") +class LLMServingArgs(_LLMServingArgs): + """The configuration for starting an LLM deployment application.""" + + pass + + +@PublicAPI(stability="alpha") +class ModelLoadingConfig(_ModelLoadingConfig): + """The configuration for loading an LLM model.""" + + pass + + +@PublicAPI(stability="alpha") +class CloudMirrorConfig(_CloudMirrorConfig): + """The configuration for mirroring an LLM model from cloud storage.""" + + pass + + +@PublicAPI(stability="alpha") +class LoraConfig(_LoraConfig): + """The configuration for loading an LLM model with LoRA.""" + + pass + + +############# +# Deployments +############# + + +@Deprecated( + old="ray.serve.llm.LLMServer", new="ray.serve.llm.deployment.LLMServer", error=False +) +class LLMServer(_LLMServer): + pass + + +@Deprecated( + old="ray.serve.llm.LLMRouter", + new="ray.serve.llm.ingress.OpenAIIngress", + error=False, +) +class LLMRouter(_LLMRouter): + pass + + +########## +# Builders +########## + + +@PublicAPI(stability="alpha") +def build_llm_deployment( + llm_config: "LLMConfig", *, name_prefix: Optional[str] = None +) -> "Application": + """Helper to build a single vllm deployment from the given llm config. + + Examples: + .. testcode:: + :skipif: True + + from ray import serve + from ray.serve.llm import LLMConfig, build_llm_deployment + + # Configure the model + llm_config = LLMConfig( + model_loading_config=dict( + model_id="llama-3.1-8b", + model_source="meta-llama/Llama-3.1-8b-instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, + max_replicas=2, + ) + ), + accelerator_type="A10G", + ) + + # Build the deployment + llm_app = build_llm_deployment(llm_config) + + # Deploy the application + model_handle = serve.run(llm_app) + + # Querying the model handle + import asyncio + model_handle = model_handle.options(stream=True) + async def query_model(model_handle): + from ray.serve.llm.openai_api_models import ChatCompletionRequest + + request = ChatCompletionRequest( + model="qwen-0.5b", + messages=[ + { + "role": "user", + "content": "Hello, world!" + } + ] + ) + + resp = model_handle.chat.remote(request) + async for message in resp: + print("message: ", message) + + asyncio.run(query_model(model_handle)) + + Args: + llm_config: The llm config to build vllm deployment. + name_prefix: Optional prefix to be used for the deployment name. + + Returns: + The configured Ray Serve Application for vllm deployment. + """ + from ray.llm._internal.serve.builders import build_llm_deployment + + return build_llm_deployment(llm_config=llm_config, name_prefix=name_prefix) + + +@PublicAPI(stability="alpha") +def build_openai_app( + llm_serving_args: Union["LLMServingArgs", Dict[str, Any]] +) -> "Application": + """Helper to build an OpenAI compatible app with the llm deployment setup from + the given llm serving args. This is the main entry point for users to create a + Serve application serving LLMs. + + + Examples: + .. code-block:: python + :caption: Example usage in code. + + from ray import serve + from ray.serve.llm import LLMConfig, LLMServingArgs, build_openai_app + + llm_config1 = LLMConfig( + model_loading_config=dict( + model_id="qwen-0.5b", + model_source="Qwen/Qwen2.5-0.5B-Instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=2, + ) + ), + accelerator_type="A10G", + ) + + llm_config2 = LLMConfig( + model_loading_config=dict( + model_id="qwen-1.5b", + model_source="Qwen/Qwen2.5-1.5B-Instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=2, + ) + ), + accelerator_type="A10G", + ) + + # Deploy the application + llm_app = build_openai_app( + LLMServingArgs( + llm_configs=[ + llm_config1, + llm_config2, + ] + ) + ) + serve.run(llm_app) + + + # Querying the model via openai client + from openai import OpenAI + + # Initialize client + client = OpenAI(base_url="http://localhost:8000/v1", api_key="fake-key") + + # Basic completion + response = client.chat.completions.create( + model="qwen-0.5b", + messages=[{"role": "user", "content": "Hello!"}] + ) + + .. code-block:: yaml + :caption: Example usage in YAML. + + # config.yaml + applications: + - args: + llm_configs: + - model_loading_config: + model_id: qwen-0.5b + model_source: Qwen/Qwen2.5-0.5B-Instruct + accelerator_type: A10G + deployment_config: + autoscaling_config: + min_replicas: 1 + max_replicas: 2 + - model_loading_config: + model_id: qwen-1.5b + model_source: Qwen/Qwen2.5-1.5B-Instruct + accelerator_type: A10G + deployment_config: + autoscaling_config: + min_replicas: 1 + max_replicas: 2 + import_path: ray.serve.llm:build_openai_app + name: llm_app + route_prefix: "/" + + + Args: + llm_serving_args: Either a dict with "llm_configs" key containing a list of + LLMConfig objects, or an LLMServingArgs object. + + Returns: + The configured Ray Serve Application router. + """ + from ray.llm._internal.serve.builders import build_openai_app + + return build_openai_app(llm_serving_args=llm_serving_args) + + +@PublicAPI(stability="alpha") +def build_pd_openai_app(pd_serving_args: dict) -> "Application": + """Build a deployable application utilizing P/D disaggregation. + + + Examples: + .. code-block:: python + :caption: Example usage in code. + + from ray import serve + from ray.serve.llm import LLMConfig, build_pd_openai_app + + config = LLMConfig( + model_loading_config=dict( + model_id="qwen-0.5b", + model_source="Qwen/Qwen2.5-0.5B-Instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=2, + ) + ), + accelerator_type="A10G", + ) + + # Deploy the application + llm_app = build_pd_openai_app( + dict( + prefill_config=config, + decode_config=config, + ) + ) + + serve.run(llm_app) + + + # Querying the model via openai client + from openai import OpenAI + + # Initialize client + client = OpenAI(base_url="http://localhost:8000/v1", api_key="fake-key") + + # Basic completion + response = client.chat.completions.create( + model="qwen-0.5b", + messages=[{"role": "user", "content": "Hello!"}] + ) + + .. code-block:: yaml + :caption: Example usage in YAML. + + # config.yaml + applications: + - args: + prefill_config: + model_loading_config: + model_id: qwen-0.5b + model_source: Qwen/Qwen2.5-0.5B-Instruct + accelerator_type: A10G + deployment_config: + autoscaling_config: + min_replicas: 1 + max_replicas: 2 + decode_config: + model_loading_config: + model_id: qwen-1.5b + model_source: Qwen/Qwen2.5-1.5B-Instruct + accelerator_type: A10G + deployment_config: + autoscaling_config: + min_replicas: 1 + max_replicas: 2 + import_path: ray.serve.llm:build_pd_openai_app + name: llm_app + route_prefix: "/" + + + Args: + pd_serving_args: The dictionary containing prefill and decode configs. + + Returns: + The configured Ray Serve Application router. + """ + from ray.llm._internal.serve.deployments.prefill_decode_disagg.prefill_decode_disagg import ( + build_pd_openai_app as _build_pd_openai_app, + ) + + return _build_pd_openai_app(pd_serving_args=pd_serving_args) + + +__all__ = [ + "LLMConfig", + "LLMServingArgs", + "ModelLoadingConfig", + "CloudMirrorConfig", + "LoraConfig", + "build_llm_deployment", + "build_openai_app", + "LLMServer", + "LLMRouter", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2730f21476ad3759a2cb7abe85e33520be885e84 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/deployment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/deployment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aabf7db7167b86c2cf9d6cd4c5c5dfdc23a49d2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/deployment.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/gen_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/gen_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3f42a272470415c08c91d92527275c47c0c4905 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/gen_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/ingress.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/ingress.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7e1d92d5cab009685c4e64b2555db344d7a01b2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/ingress.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/openai_api_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/openai_api_models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d0da0dacf7167007586b4461250e34259babd2f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/openai_api_models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/request_router.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/request_router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92499f157dbc7f39374d7ad33121ff8a4349032f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/__pycache__/request_router.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/deployment.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..f4640a802c48a11078f6ef159975fb98e65e6ad1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/deployment.py @@ -0,0 +1,82 @@ +from ray.llm._internal.serve.deployments.llm.llm_server import ( + LLMServer as InternalLLMServer, +) + +# TODO (Kourosh): Update the internal namespace. +from ray.llm._internal.serve.deployments.prefill_decode_disagg.prefill_decode_disagg import ( + PDProxyServer, +) +from ray.util.annotations import PublicAPI + +############# +# Deployments +############# + + +@PublicAPI(stability="alpha") +class LLMServer(InternalLLMServer): + """The implementation of the vLLM engine deployment. + + To build a Deployment object you should use `build_llm_deployment` function. + We also expose a lower level API for more control over the deployment class + through `as_deployment` method. + + Examples: + .. testcode:: + :skipif: True + + from ray import serve + from ray.serve.llm import LLMConfig, LLMServer + + # Configure the model + llm_config = LLMConfig( + model_loading_config=dict( + served_model_name="llama-3.1-8b", + model_source="meta-llama/Llama-3.1-8b-instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, + max_replicas=8, + ) + ), + ) + + # Build the deployment directly + LLMDeployment = LLMServer.as_deployment(llm_config.get_serve_options()) + llm_app = LLMDeployment.bind(llm_config) + + model_handle = serve.run(llm_app) + + # Query the model via `chat` api + from ray.serve.llm.openai_api_models import ChatCompletionRequest + request = ChatCompletionRequest( + model="llama-3.1-8b", + messages=[ + { + "role": "user", + "content": "Hello, world!" + } + ] + ) + response = ray.get(model_handle.chat(request)) + print(response) + """ + + pass + + +@PublicAPI(stability="alpha") +class PDServer(PDProxyServer): + """A server for prefill-decode disaggregation. + + This server acts as a proxy in a prefill-decode disaggregated system. + For chat and completions, proxy sends the request to the prefill server + with max_tokens=1 and then sends the returned metadata to the decode server. + + Args: + prefill_server: The prefill server deployment handle. + decode_server: The decode server deployment handle. + """ + + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/gen_config.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/gen_config.py new file mode 100644 index 0000000000000000000000000000000000000000..27d880238f262ec2b56e5aa09eaffbe92311188f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/gen_config.py @@ -0,0 +1,10 @@ +from ray.llm._internal.serve.config_generator.start import gen_config + + +def main(): + """Entry point for the CLI when called as a module.""" + gen_config() + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/ingress.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/ingress.py new file mode 100644 index 0000000000000000000000000000000000000000..466f46bb2a5b70c424552693e25ae7ee0e055189 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/ingress.py @@ -0,0 +1,61 @@ +from ray.llm._internal.serve.deployments.routers.router import ( + LLMRouter as _LLMRouter, +) +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class OpenAiIngress(_LLMRouter): + + """The implementation of the OpenAI compatiple model router. + + This deployment creates the following endpoints: + - /v1/chat/completions: Chat interface (OpenAI-style) + - /v1/completions: Text completion + - /v1/models: List available models + - /v1/models/{model}: Model information + + + Examples: + .. testcode:: + :skipif: True + + + from ray import serve + from ray.serve.llm import LLMConfig + from ray.serve.llm.deployment import LLMServer + from ray.serve.llm.ingress import OpenAiIngress + from ray.serve.llm.openai_api_models import ChatCompletionRequest + + + llm_config1 = LLMConfig( + model_loading_config=dict( + served_model_name="llama-3.1-8b", # Name shown in /v1/models + model_source="meta-llama/Llama-3.1-8b-instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=8, + ) + ), + ) + llm_config2 = LLMConfig( + model_loading_config=dict( + served_model_name="llama-3.2-3b", # Name shown in /v1/models + model_source="meta-llama/Llama-3.2-3b-instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=8, + ) + ), + ) + + # Deploy the application + vllm_deployment1 = LLMServer.as_deployment(llm_config1.get_serve_options()).bind(llm_config1) + vllm_deployment2 = LLMServer.as_deployment(llm_config2.get_serve_options()).bind(llm_config2) + llm_app = OpenAiIngress.as_deployment().bind([vllm_deployment1, vllm_deployment2]) + serve.run(llm_app) + """ + + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/openai_api_models.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/openai_api_models.py new file mode 100644 index 0000000000000000000000000000000000000000..496cf794ac4bf38697e32bba68e6d12810835f13 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/openai_api_models.py @@ -0,0 +1,92 @@ +from ray.llm._internal.serve.configs.openai_api_models import ( + ChatCompletionRequest as _ChatCompletionRequest, + ChatCompletionResponse as _ChatCompletionResponse, + ChatCompletionStreamResponse as _ChatCompletionStreamResponse, + CompletionRequest as _CompletionRequest, + CompletionResponse as _CompletionResponse, + CompletionStreamResponse as _CompletionStreamResponse, + EmbeddingRequest as _EmbeddingRequest, + EmbeddingResponse as _EmbeddingResponse, + ErrorResponse as _ErrorResponse, +) +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ChatCompletionRequest(_ChatCompletionRequest): + """ChatCompletionRequest is the request body for the chat completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class CompletionRequest(_CompletionRequest): + """CompletionRequest is the request body for the completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class ChatCompletionStreamResponse(_ChatCompletionStreamResponse): + """ChatCompletionStreamResponse is the response body for the chat completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class ChatCompletionResponse(_ChatCompletionResponse): + """ChatCompletionResponse is the response body for the chat completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class CompletionStreamResponse(_CompletionStreamResponse): + """CompletionStreamResponse is the response body for the completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class CompletionResponse(_CompletionResponse): + """CompletionResponse is the response body for the completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +EmbeddingRequest = _EmbeddingRequest + + +@PublicAPI(stability="alpha") +class EmbeddingResponse(_EmbeddingResponse): + """EmbeddingResponse is the response body for the embedding API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class ErrorResponse(_ErrorResponse): + """The returned response in case of an error.""" + + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/request_router.py b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/request_router.py new file mode 100644 index 0000000000000000000000000000000000000000..95aaf8ef6cb6864486d0aaf426a0e554c74b555d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/serve/llm/request_router.py @@ -0,0 +1,42 @@ +from ray.llm._internal.serve.request_router.prefix_aware.prefix_aware_router import ( + PrefixCacheAffinityRouter as _PrefixCacheAffinityRouter, +) +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class PrefixCacheAffinityRouter(_PrefixCacheAffinityRouter): + """A request router that is aware of the KV cache. + + This router optimizes request routing by considering KV cache locality, + directing requests with similar prefixes to the same replica to improve + cache hit rates. + + The internal policy is this (it may change in the future): + + 1. Mixes between three strategies to balance prefix cache hit rate and load + balancing: + - When load is balanced (queue length difference < threshold), it + selects replicas with the highest prefix match rate for the input text + - When load is balanced but match rate is below 10%, it falls back to + the smallest tenants (i.e. the replica with the least kv cache) + - When load is imbalanced, it uses the default Power of Two selection + + 2. Maintains a prefix tree to track which replicas have processed similar + inputs: + - Inserts prompt text into the prefix tree after routing + - Uses this history to inform future routing decisions + + Parameters: + imbalanced_threshold: The threshold for considering the load imbalanced. + match_rate_threshold: The threshold for considering the match rate. + do_eviction: Whether to do eviction. + eviction_threshold_chars: Number of characters in the tree to trigger + eviction. + eviction_target_chars: Number of characters in the tree to target for + eviction. + eviction_interval_secs: How often (in seconds) to run the eviction + policy. + """ + + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/INSTALLER b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/METADATA b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a1b5c57543005b310ac2efb02243a6b6ab6d8932 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/METADATA @@ -0,0 +1,441 @@ +Metadata-Version: 2.1 +Name: colorama +Version: 0.4.6 +Summary: Cross-platform colored terminal text. +Project-URL: Homepage, https://github.com/tartley/colorama +Author-email: Jonathan Hartley +License-File: LICENSE.txt +Keywords: ansi,color,colour,crossplatform,terminal,text,windows,xplatform +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Terminals +Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7 +Description-Content-Type: text/x-rst + +.. image:: https://img.shields.io/pypi/v/colorama.svg + :target: https://pypi.org/project/colorama/ + :alt: Latest Version + +.. image:: https://img.shields.io/pypi/pyversions/colorama.svg + :target: https://pypi.org/project/colorama/ + :alt: Supported Python versions + +.. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg + :target: https://github.com/tartley/colorama/actions/workflows/test.yml + :alt: Build Status + +Colorama +======== + +Makes ANSI escape character sequences (for producing colored terminal text and +cursor positioning) work under MS Windows. + +.. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif + :target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama¤cy_code=USD + :alt: Donate with Paypal + +`PyPI for releases `_ | +`Github for source `_ | +`Colorama for enterprise on Tidelift `_ + +If you find Colorama useful, please |donate| to the authors. Thank you! + +Installation +------------ + +Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8. + +No requirements other than the standard library. + +.. code-block:: bash + + pip install colorama + # or + conda install -c anaconda colorama + +Description +----------- + +ANSI escape character sequences have long been used to produce colored terminal +text and cursor positioning on Unix and Macs. Colorama makes this work on +Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which +would appear as gobbledygook in the output), and converting them into the +appropriate win32 calls to modify the state of the terminal. On other platforms, +Colorama does nothing. + +This has the upshot of providing a simple cross-platform API for printing +colored terminal text from Python, and has the happy side-effect that existing +applications or libraries which use ANSI sequences to produce colored output on +Linux or Macs can now also work on Windows, simply by calling +``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()`` +(all versions, but may have other side-effects – see below). + +An alternative approach is to install ``ansi.sys`` on Windows machines, which +provides the same behaviour for all applications running in terminals. Colorama +is intended for situations where that isn't easy (e.g., maybe your app doesn't +have an installer.) + +Demo scripts in the source code repository print some colored text using +ANSI sequences. Compare their output under Gnome-terminal's built in ANSI +handling, versus on Windows Command-Prompt using Colorama: + +.. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png + :width: 661 + :height: 357 + :alt: ANSI sequences on Ubuntu under gnome-terminal. + +.. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png + :width: 668 + :height: 325 + :alt: Same ANSI sequences on Windows, using Colorama. + +These screenshots show that, on Windows, Colorama does not support ANSI 'dim +text'; it looks the same as 'normal text'. + +Usage +----- + +Initialisation +.............. + +If the only thing you want from Colorama is to get ANSI escapes to work on +Windows, then run: + +.. code-block:: python + + from colorama import just_fix_windows_console + just_fix_windows_console() + +If you're on a recent version of Windows 10 or better, and your stdout/stderr +are pointing to a Windows console, then this will flip the magic configuration +switch to enable Windows' built-in ANSI support. + +If you're on an older version of Windows, and your stdout/stderr are pointing to +a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a +magic file object that intercepts ANSI escape sequences and issues the +appropriate Win32 calls to emulate them. + +In all other circumstances, it does nothing whatsoever. Basically the idea is +that this makes Windows act like Unix with respect to ANSI escape handling. + +It's safe to call this function multiple times. It's safe to call this function +on non-Windows platforms, but it won't do anything. It's safe to call this +function when one or both of your stdout/stderr are redirected to a file – it +won't do anything to those streams. + +Alternatively, you can use the older interface with more features (but also more +potential footguns): + +.. code-block:: python + + from colorama import init + init() + +This does the same thing as ``just_fix_windows_console``, except for the +following differences: + +- It's not safe to call ``init`` multiple times; you can end up with multiple + layers of wrapping and broken ANSI support. + +- Colorama will apply a heuristic to guess whether stdout/stderr support ANSI, + and if it thinks they don't, then it will wrap ``sys.stdout`` and + ``sys.stderr`` in a magic file object that strips out ANSI escape sequences + before printing them. This happens on all platforms, and can be convenient if + you want to write your code to emit ANSI escape sequences unconditionally, and + let Colorama decide whether they should actually be output. But note that + Colorama's heuristic is not particularly clever. + +- ``init`` also accepts explicit keyword args to enable/disable various + functionality – see below. + +To stop using Colorama before your program exits, simply call ``deinit()``. +This will restore ``stdout`` and ``stderr`` to their original values, so that +Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is +cheaper than calling ``init()`` again (but does the same thing). + +Most users should depend on ``colorama >= 0.4.6``, and use +``just_fix_windows_console``. The old ``init`` interface will be supported +indefinitely for backwards compatibility, but we don't plan to fix any issues +with it, also for backwards compatibility. + +Colored Output +.............. + +Cross-platform printing of colored text can then be done using Colorama's +constant shorthand for ANSI escape sequences. These are deliberately +rudimentary, see below. + +.. code-block:: python + + from colorama import Fore, Back, Style + print(Fore.RED + 'some red text') + print(Back.GREEN + 'and with a green background') + print(Style.DIM + 'and in dim text') + print(Style.RESET_ALL) + print('back to normal now') + +...or simply by manually printing ANSI sequences from your own code: + +.. code-block:: python + + print('\033[31m' + 'some red text') + print('\033[39m') # and reset to default color + +...or, Colorama can be used in conjunction with existing ANSI libraries +such as the venerable `Termcolor `_ +the fabulous `Blessings `_, +or the incredible `_Rich `_. + +If you wish Colorama's Fore, Back and Style constants were more capable, +then consider using one of the above highly capable libraries to generate +colors, etc, and use Colorama just for its primary purpose: to convert +those ANSI sequences to also work on Windows: + +SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama. +We are only interested in converting ANSI codes to win32 API calls, not +shortcuts like the above to generate ANSI characters. + +.. code-block:: python + + from colorama import just_fix_windows_console + from termcolor import colored + + # use Colorama to make Termcolor work on Windows too + just_fix_windows_console() + + # then use Termcolor for all colored text output + print(colored('Hello, World!', 'green', 'on_red')) + +Available formatting constants are:: + + Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. + Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. + Style: DIM, NORMAL, BRIGHT, RESET_ALL + +``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will +perform this reset automatically on program exit. + +These are fairly well supported, but not part of the standard:: + + Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX + Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX + +Cursor Positioning +.................. + +ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for +an example of how to generate them. + +Init Keyword Args +................. + +``init()`` accepts some ``**kwargs`` to override default behaviour. + +init(autoreset=False): + If you find yourself repeatedly sending reset sequences to turn off color + changes at the end of every print, then ``init(autoreset=True)`` will + automate that: + + .. code-block:: python + + from colorama import init + init(autoreset=True) + print(Fore.RED + 'some red text') + print('automatically back to default color again') + +init(strip=None): + Pass ``True`` or ``False`` to override whether ANSI codes should be + stripped from the output. The default behaviour is to strip if on Windows + or if output is redirected (not a tty). + +init(convert=None): + Pass ``True`` or ``False`` to override whether to convert ANSI codes in the + output into win32 calls. The default behaviour is to convert if on Windows + and output is to a tty (terminal). + +init(wrap=True): + On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr`` + with proxy objects, which override the ``.write()`` method to do their work. + If this wrapping causes you problems, then this can be disabled by passing + ``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or + ``strip`` or ``convert`` are True. + + When wrapping is disabled, colored printing on non-Windows platforms will + continue to work as normal. To do cross-platform colored output, you can + use Colorama's ``AnsiToWin32`` proxy directly: + + .. code-block:: python + + import sys + from colorama import init, AnsiToWin32 + init(wrap=False) + stream = AnsiToWin32(sys.stderr).stream + + # Python 2 + print >>stream, Fore.BLUE + 'blue text on stderr' + + # Python 3 + print(Fore.BLUE + 'blue text on stderr', file=stream) + +Recognised ANSI Sequences +......................... + +ANSI sequences generally take the form:: + + ESC [ ; ... + +Where ```` is an integer, and ```` is a single letter. Zero or +more params are passed to a ````. If no params are passed, it is +generally synonymous with passing a single zero. No spaces exist in the +sequence; they have been inserted here simply to read more easily. + +The only ANSI sequences that Colorama converts into win32 calls are:: + + ESC [ 0 m # reset all (colors and brightness) + ESC [ 1 m # bright + ESC [ 2 m # dim (looks same as normal brightness) + ESC [ 22 m # normal brightness + + # FOREGROUND: + ESC [ 30 m # black + ESC [ 31 m # red + ESC [ 32 m # green + ESC [ 33 m # yellow + ESC [ 34 m # blue + ESC [ 35 m # magenta + ESC [ 36 m # cyan + ESC [ 37 m # white + ESC [ 39 m # reset + + # BACKGROUND + ESC [ 40 m # black + ESC [ 41 m # red + ESC [ 42 m # green + ESC [ 43 m # yellow + ESC [ 44 m # blue + ESC [ 45 m # magenta + ESC [ 46 m # cyan + ESC [ 47 m # white + ESC [ 49 m # reset + + # cursor positioning + ESC [ y;x H # position cursor at x across, y down + ESC [ y;x f # position cursor at x across, y down + ESC [ n A # move cursor n lines up + ESC [ n B # move cursor n lines down + ESC [ n C # move cursor n characters forward + ESC [ n D # move cursor n characters backward + + # clear the screen + ESC [ mode J # clear the screen + + # clear the line + ESC [ mode K # clear the line + +Multiple numeric params to the ``'m'`` command can be combined into a single +sequence:: + + ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background + +All other ANSI sequences of the form ``ESC [ ; ... `` +are silently stripped from the output on Windows. + +Any other form of ANSI sequence, such as single-character codes or alternative +initial characters, are not recognised or stripped. It would be cool to add +them though. Let me know if it would be useful for you, via the Issues on +GitHub. + +Status & Known Problems +----------------------- + +I've personally only tested it on Windows XP (CMD, Console2), Ubuntu +(gnome-terminal, xterm), and OS X. + +Some valid ANSI sequences aren't recognised. + +If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the +explanation there of why we do not want PRs that allow Colorama to generate new +types of ANSI codes. + +See outstanding issues and wish-list: +https://github.com/tartley/colorama/issues + +If anything doesn't work for you, or doesn't do what you expected or hoped for, +I'd love to hear about it on that issues list, would be delighted by patches, +and would be happy to grant commit access to anyone who submits a working patch +or two. + +.. _README-hacking.md: README-hacking.md + +License +------- + +Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see +LICENSE file. + +Professional support +-------------------- + +.. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png + :alt: Tidelift + :target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme + +.. list-table:: + :widths: 10 100 + + * - |tideliftlogo| + - Professional support for colorama is available as part of the + `Tidelift Subscription`_. + Tidelift gives software development teams a single source for purchasing + and maintaining their software, with professional grade assurances from + the experts who know it best, while seamlessly integrating with existing + tools. + +.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme + +Thanks +------ + +See the CHANGELOG for more thanks! + +* Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5. +* Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``, + providing a solution to issue #7's setuptools/distutils debate, + and other fixes. +* User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``. +* Matthew McCormick for politely pointing out a longstanding crash on non-Win. +* Ben Hoyt, for a magnificent fix under 64-bit Windows. +* Jesse at Empty Square for submitting a fix for examples in the README. +* User 'jamessp', an observant documentation fix for cursor positioning. +* User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7 + fix. +* Julien Stuyck, for wisely suggesting Python3 compatible updates to README. +* Daniel Griffith for multiple fabulous patches. +* Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty + output. +* Roger Binns, for many suggestions, valuable feedback, & bug reports. +* Tim Golden for thought and much appreciated feedback on the initial idea. +* User 'Zearin' for updates to the README file. +* John Szakmeister for adding support for light colors +* Charles Merriam for adding documentation to demos +* Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes +* Florian Bruhin for a fix when stdout or stderr are None +* Thomas Weininger for fixing ValueError on Windows +* Remi Rampin for better Github integration and fixes to the README file +* Simeon Visser for closing a file handle using 'with' and updating classifiers + to include Python 3.3 and 3.4 +* Andy Neff for fixing RESET of LIGHT_EX colors. +* Jonathan Hartley for the initial idea and implementation. diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/RECORD b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f71babf13786131e6ba7735b9e4ebbc4e6860262 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/RECORD @@ -0,0 +1,32 @@ +colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158 +colorama-0.4.6.dist-info/RECORD,, +colorama-0.4.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105 +colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491 +colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266 +colorama/__pycache__/__init__.cpython-312.pyc,, +colorama/__pycache__/ansi.cpython-312.pyc,, +colorama/__pycache__/ansitowin32.cpython-312.pyc,, +colorama/__pycache__/initialise.cpython-312.pyc,, +colorama/__pycache__/win32.cpython-312.pyc,, +colorama/__pycache__/winterm.cpython-312.pyc,, +colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522 +colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128 +colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325 +colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75 +colorama/tests/__pycache__/__init__.cpython-312.pyc,, +colorama/tests/__pycache__/ansi_test.cpython-312.pyc,, +colorama/tests/__pycache__/ansitowin32_test.cpython-312.pyc,, +colorama/tests/__pycache__/initialise_test.cpython-312.pyc,, +colorama/tests/__pycache__/isatty_test.cpython-312.pyc,, +colorama/tests/__pycache__/utils.cpython-312.pyc,, +colorama/tests/__pycache__/winterm_test.cpython-312.pyc,, +colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839 +colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678 +colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741 +colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866 +colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079 +colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709 +colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181 +colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/REQUESTED b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..383101cdb38706c305449674044e9288b92b7d75 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/__init__.py @@ -0,0 +1,7 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console +from .ansi import Fore, Back, Style, Cursor +from .ansitowin32 import AnsiToWin32 + +__version__ = '0.4.6' + diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/ansi.py b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/ansi.py new file mode 100644 index 0000000000000000000000000000000000000000..11ec695ff79627463a0282d25079527562de9e42 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/ansi.py @@ -0,0 +1,102 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +''' +This module generates ANSI character codes to printing colors to terminals. +See: http://en.wikipedia.org/wiki/ANSI_escape_code +''' + +CSI = '\033[' +OSC = '\033]' +BEL = '\a' + + +def code_to_chars(code): + return CSI + str(code) + 'm' + +def set_title(title): + return OSC + '2;' + title + BEL + +def clear_screen(mode=2): + return CSI + str(mode) + 'J' + +def clear_line(mode=2): + return CSI + str(mode) + 'K' + + +class AnsiCodes(object): + def __init__(self): + # the subclasses declare class attributes which are numbers. + # Upon instantiation we define instance attributes, which are the same + # as the class attributes but wrapped with the ANSI escape sequence + for name in dir(self): + if not name.startswith('_'): + value = getattr(self, name) + setattr(self, name, code_to_chars(value)) + + +class AnsiCursor(object): + def UP(self, n=1): + return CSI + str(n) + 'A' + def DOWN(self, n=1): + return CSI + str(n) + 'B' + def FORWARD(self, n=1): + return CSI + str(n) + 'C' + def BACK(self, n=1): + return CSI + str(n) + 'D' + def POS(self, x=1, y=1): + return CSI + str(y) + ';' + str(x) + 'H' + + +class AnsiFore(AnsiCodes): + BLACK = 30 + RED = 31 + GREEN = 32 + YELLOW = 33 + BLUE = 34 + MAGENTA = 35 + CYAN = 36 + WHITE = 37 + RESET = 39 + + # These are fairly well supported, but not part of the standard. + LIGHTBLACK_EX = 90 + LIGHTRED_EX = 91 + LIGHTGREEN_EX = 92 + LIGHTYELLOW_EX = 93 + LIGHTBLUE_EX = 94 + LIGHTMAGENTA_EX = 95 + LIGHTCYAN_EX = 96 + LIGHTWHITE_EX = 97 + + +class AnsiBack(AnsiCodes): + BLACK = 40 + RED = 41 + GREEN = 42 + YELLOW = 43 + BLUE = 44 + MAGENTA = 45 + CYAN = 46 + WHITE = 47 + RESET = 49 + + # These are fairly well supported, but not part of the standard. + LIGHTBLACK_EX = 100 + LIGHTRED_EX = 101 + LIGHTGREEN_EX = 102 + LIGHTYELLOW_EX = 103 + LIGHTBLUE_EX = 104 + LIGHTMAGENTA_EX = 105 + LIGHTCYAN_EX = 106 + LIGHTWHITE_EX = 107 + + +class AnsiStyle(AnsiCodes): + BRIGHT = 1 + DIM = 2 + NORMAL = 22 + RESET_ALL = 0 + +Fore = AnsiFore() +Back = AnsiBack() +Style = AnsiStyle() +Cursor = AnsiCursor() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/ansitowin32.py b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/ansitowin32.py new file mode 100644 index 0000000000000000000000000000000000000000..abf209e60c7c4a9b1ae57452e36b383969848c2e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/ansitowin32.py @@ -0,0 +1,277 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import re +import sys +import os + +from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL +from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle +from .win32 import windll, winapi_test + + +winterm = None +if windll is not None: + winterm = WinTerm() + + +class StreamWrapper(object): + ''' + Wraps a stream (such as stdout), acting as a transparent proxy for all + attribute access apart from method 'write()', which is delegated to our + Converter instance. + ''' + def __init__(self, wrapped, converter): + # double-underscore everything to prevent clashes with names of + # attributes on the wrapped stream object. + self.__wrapped = wrapped + self.__convertor = converter + + def __getattr__(self, name): + return getattr(self.__wrapped, name) + + def __enter__(self, *args, **kwargs): + # special method lookup bypasses __getattr__/__getattribute__, see + # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit + # thus, contextlib magic methods are not proxied via __getattr__ + return self.__wrapped.__enter__(*args, **kwargs) + + def __exit__(self, *args, **kwargs): + return self.__wrapped.__exit__(*args, **kwargs) + + def __setstate__(self, state): + self.__dict__ = state + + def __getstate__(self): + return self.__dict__ + + def write(self, text): + self.__convertor.write(text) + + def isatty(self): + stream = self.__wrapped + if 'PYCHARM_HOSTED' in os.environ: + if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__): + return True + try: + stream_isatty = stream.isatty + except AttributeError: + return False + else: + return stream_isatty() + + @property + def closed(self): + stream = self.__wrapped + try: + return stream.closed + # AttributeError in the case that the stream doesn't support being closed + # ValueError for the case that the stream has already been detached when atexit runs + except (AttributeError, ValueError): + return True + + +class AnsiToWin32(object): + ''' + Implements a 'write()' method which, on Windows, will strip ANSI character + sequences from the text, and if outputting to a tty, will convert them into + win32 function calls. + ''' + ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer + ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command + + def __init__(self, wrapped, convert=None, strip=None, autoreset=False): + # The wrapped stream (normally sys.stdout or sys.stderr) + self.wrapped = wrapped + + # should we reset colors to defaults after every .write() + self.autoreset = autoreset + + # create the proxy wrapping our output stream + self.stream = StreamWrapper(wrapped, self) + + on_windows = os.name == 'nt' + # We test if the WinAPI works, because even if we are on Windows + # we may be using a terminal that doesn't support the WinAPI + # (e.g. Cygwin Terminal). In this case it's up to the terminal + # to support the ANSI codes. + conversion_supported = on_windows and winapi_test() + try: + fd = wrapped.fileno() + except Exception: + fd = -1 + system_has_native_ansi = not on_windows or enable_vt_processing(fd) + have_tty = not self.stream.closed and self.stream.isatty() + need_conversion = conversion_supported and not system_has_native_ansi + + # should we strip ANSI sequences from our output? + if strip is None: + strip = need_conversion or not have_tty + self.strip = strip + + # should we should convert ANSI sequences into win32 calls? + if convert is None: + convert = need_conversion and have_tty + self.convert = convert + + # dict of ansi codes to win32 functions and parameters + self.win32_calls = self.get_win32_calls() + + # are we wrapping stderr? + self.on_stderr = self.wrapped is sys.stderr + + def should_wrap(self): + ''' + True if this class is actually needed. If false, then the output + stream will not be affected, nor will win32 calls be issued, so + wrapping stdout is not actually required. This will generally be + False on non-Windows platforms, unless optional functionality like + autoreset has been requested using kwargs to init() + ''' + return self.convert or self.strip or self.autoreset + + def get_win32_calls(self): + if self.convert and winterm: + return { + AnsiStyle.RESET_ALL: (winterm.reset_all, ), + AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), + AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), + AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), + AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), + AnsiFore.RED: (winterm.fore, WinColor.RED), + AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), + AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), + AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), + AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), + AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), + AnsiFore.WHITE: (winterm.fore, WinColor.GREY), + AnsiFore.RESET: (winterm.fore, ), + AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True), + AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True), + AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True), + AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True), + AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True), + AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True), + AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True), + AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True), + AnsiBack.BLACK: (winterm.back, WinColor.BLACK), + AnsiBack.RED: (winterm.back, WinColor.RED), + AnsiBack.GREEN: (winterm.back, WinColor.GREEN), + AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), + AnsiBack.BLUE: (winterm.back, WinColor.BLUE), + AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), + AnsiBack.CYAN: (winterm.back, WinColor.CYAN), + AnsiBack.WHITE: (winterm.back, WinColor.GREY), + AnsiBack.RESET: (winterm.back, ), + AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True), + AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True), + AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True), + AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True), + AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True), + AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True), + AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True), + AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True), + } + return dict() + + def write(self, text): + if self.strip or self.convert: + self.write_and_convert(text) + else: + self.wrapped.write(text) + self.wrapped.flush() + if self.autoreset: + self.reset_all() + + + def reset_all(self): + if self.convert: + self.call_win32('m', (0,)) + elif not self.strip and not self.stream.closed: + self.wrapped.write(Style.RESET_ALL) + + + def write_and_convert(self, text): + ''' + Write the given text to our wrapped stream, stripping any ANSI + sequences from the text, and optionally converting them into win32 + calls. + ''' + cursor = 0 + text = self.convert_osc(text) + for match in self.ANSI_CSI_RE.finditer(text): + start, end = match.span() + self.write_plain_text(text, cursor, start) + self.convert_ansi(*match.groups()) + cursor = end + self.write_plain_text(text, cursor, len(text)) + + + def write_plain_text(self, text, start, end): + if start < end: + self.wrapped.write(text[start:end]) + self.wrapped.flush() + + + def convert_ansi(self, paramstring, command): + if self.convert: + params = self.extract_params(command, paramstring) + self.call_win32(command, params) + + + def extract_params(self, command, paramstring): + if command in 'Hf': + params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';')) + while len(params) < 2: + # defaults: + params = params + (1,) + else: + params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0) + if len(params) == 0: + # defaults: + if command in 'JKm': + params = (0,) + elif command in 'ABCD': + params = (1,) + + return params + + + def call_win32(self, command, params): + if command == 'm': + for param in params: + if param in self.win32_calls: + func_args = self.win32_calls[param] + func = func_args[0] + args = func_args[1:] + kwargs = dict(on_stderr=self.on_stderr) + func(*args, **kwargs) + elif command in 'J': + winterm.erase_screen(params[0], on_stderr=self.on_stderr) + elif command in 'K': + winterm.erase_line(params[0], on_stderr=self.on_stderr) + elif command in 'Hf': # cursor position - absolute + winterm.set_cursor_position(params, on_stderr=self.on_stderr) + elif command in 'ABCD': # cursor position - relative + n = params[0] + # A - up, B - down, C - forward, D - back + x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command] + winterm.cursor_adjust(x, y, on_stderr=self.on_stderr) + + + def convert_osc(self, text): + for match in self.ANSI_OSC_RE.finditer(text): + start, end = match.span() + text = text[:start] + text[end:] + paramstring, command = match.groups() + if command == BEL: + if paramstring.count(";") == 1: + params = paramstring.split(";") + # 0 - change title and icon (we will only change title) + # 1 - change icon (we don't support this) + # 2 - change title + if params[0] in '02': + winterm.set_title(params[1]) + return text + + + def flush(self): + self.wrapped.flush() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/initialise.py b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/initialise.py new file mode 100644 index 0000000000000000000000000000000000000000..d5fd4b71fed1bb4871717f978f0c470280f099c1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/initialise.py @@ -0,0 +1,121 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import atexit +import contextlib +import sys + +from .ansitowin32 import AnsiToWin32 + + +def _wipe_internal_state_for_tests(): + global orig_stdout, orig_stderr + orig_stdout = None + orig_stderr = None + + global wrapped_stdout, wrapped_stderr + wrapped_stdout = None + wrapped_stderr = None + + global atexit_done + atexit_done = False + + global fixed_windows_console + fixed_windows_console = False + + try: + # no-op if it wasn't registered + atexit.unregister(reset_all) + except AttributeError: + # python 2: no atexit.unregister. Oh well, we did our best. + pass + + +def reset_all(): + if AnsiToWin32 is not None: # Issue #74: objects might become None at exit + AnsiToWin32(orig_stdout).reset_all() + + +def init(autoreset=False, convert=None, strip=None, wrap=True): + + if not wrap and any([autoreset, convert, strip]): + raise ValueError('wrap=False conflicts with any other arg=True') + + global wrapped_stdout, wrapped_stderr + global orig_stdout, orig_stderr + + orig_stdout = sys.stdout + orig_stderr = sys.stderr + + if sys.stdout is None: + wrapped_stdout = None + else: + sys.stdout = wrapped_stdout = \ + wrap_stream(orig_stdout, convert, strip, autoreset, wrap) + if sys.stderr is None: + wrapped_stderr = None + else: + sys.stderr = wrapped_stderr = \ + wrap_stream(orig_stderr, convert, strip, autoreset, wrap) + + global atexit_done + if not atexit_done: + atexit.register(reset_all) + atexit_done = True + + +def deinit(): + if orig_stdout is not None: + sys.stdout = orig_stdout + if orig_stderr is not None: + sys.stderr = orig_stderr + + +def just_fix_windows_console(): + global fixed_windows_console + + if sys.platform != "win32": + return + if fixed_windows_console: + return + if wrapped_stdout is not None or wrapped_stderr is not None: + # Someone already ran init() and it did stuff, so we won't second-guess them + return + + # On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the + # native ANSI support in the console as a side-effect. We only need to actually + # replace sys.stdout/stderr if we're in the old-style conversion mode. + new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False) + if new_stdout.convert: + sys.stdout = new_stdout + new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False) + if new_stderr.convert: + sys.stderr = new_stderr + + fixed_windows_console = True + +@contextlib.contextmanager +def colorama_text(*args, **kwargs): + init(*args, **kwargs) + try: + yield + finally: + deinit() + + +def reinit(): + if wrapped_stdout is not None: + sys.stdout = wrapped_stdout + if wrapped_stderr is not None: + sys.stderr = wrapped_stderr + + +def wrap_stream(stream, convert, strip, autoreset, wrap): + if wrap: + wrapper = AnsiToWin32(stream, + convert=convert, strip=strip, autoreset=autoreset) + if wrapper.should_wrap(): + stream = wrapper.stream + return stream + + +# Use this for initial setup as well, to reduce code duplication +_wipe_internal_state_for_tests() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/win32.py b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/win32.py new file mode 100644 index 0000000000000000000000000000000000000000..841b0e270a381cdfaca544a9be976d7276d83b1e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/win32.py @@ -0,0 +1,180 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. + +# from winbase.h +STDOUT = -11 +STDERR = -12 + +ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 + +try: + import ctypes + from ctypes import LibraryLoader + windll = LibraryLoader(ctypes.WinDLL) + from ctypes import wintypes +except (AttributeError, ImportError): + windll = None + SetConsoleTextAttribute = lambda *_: None + winapi_test = lambda *_: None +else: + from ctypes import byref, Structure, c_char, POINTER + + COORD = wintypes._COORD + + class CONSOLE_SCREEN_BUFFER_INFO(Structure): + """struct in wincon.h.""" + _fields_ = [ + ("dwSize", COORD), + ("dwCursorPosition", COORD), + ("wAttributes", wintypes.WORD), + ("srWindow", wintypes.SMALL_RECT), + ("dwMaximumWindowSize", COORD), + ] + def __str__(self): + return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( + self.dwSize.Y, self.dwSize.X + , self.dwCursorPosition.Y, self.dwCursorPosition.X + , self.wAttributes + , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right + , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X + ) + + _GetStdHandle = windll.kernel32.GetStdHandle + _GetStdHandle.argtypes = [ + wintypes.DWORD, + ] + _GetStdHandle.restype = wintypes.HANDLE + + _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo + _GetConsoleScreenBufferInfo.argtypes = [ + wintypes.HANDLE, + POINTER(CONSOLE_SCREEN_BUFFER_INFO), + ] + _GetConsoleScreenBufferInfo.restype = wintypes.BOOL + + _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute + _SetConsoleTextAttribute.argtypes = [ + wintypes.HANDLE, + wintypes.WORD, + ] + _SetConsoleTextAttribute.restype = wintypes.BOOL + + _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition + _SetConsoleCursorPosition.argtypes = [ + wintypes.HANDLE, + COORD, + ] + _SetConsoleCursorPosition.restype = wintypes.BOOL + + _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA + _FillConsoleOutputCharacterA.argtypes = [ + wintypes.HANDLE, + c_char, + wintypes.DWORD, + COORD, + POINTER(wintypes.DWORD), + ] + _FillConsoleOutputCharacterA.restype = wintypes.BOOL + + _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute + _FillConsoleOutputAttribute.argtypes = [ + wintypes.HANDLE, + wintypes.WORD, + wintypes.DWORD, + COORD, + POINTER(wintypes.DWORD), + ] + _FillConsoleOutputAttribute.restype = wintypes.BOOL + + _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW + _SetConsoleTitleW.argtypes = [ + wintypes.LPCWSTR + ] + _SetConsoleTitleW.restype = wintypes.BOOL + + _GetConsoleMode = windll.kernel32.GetConsoleMode + _GetConsoleMode.argtypes = [ + wintypes.HANDLE, + POINTER(wintypes.DWORD) + ] + _GetConsoleMode.restype = wintypes.BOOL + + _SetConsoleMode = windll.kernel32.SetConsoleMode + _SetConsoleMode.argtypes = [ + wintypes.HANDLE, + wintypes.DWORD + ] + _SetConsoleMode.restype = wintypes.BOOL + + def _winapi_test(handle): + csbi = CONSOLE_SCREEN_BUFFER_INFO() + success = _GetConsoleScreenBufferInfo( + handle, byref(csbi)) + return bool(success) + + def winapi_test(): + return any(_winapi_test(h) for h in + (_GetStdHandle(STDOUT), _GetStdHandle(STDERR))) + + def GetConsoleScreenBufferInfo(stream_id=STDOUT): + handle = _GetStdHandle(stream_id) + csbi = CONSOLE_SCREEN_BUFFER_INFO() + success = _GetConsoleScreenBufferInfo( + handle, byref(csbi)) + return csbi + + def SetConsoleTextAttribute(stream_id, attrs): + handle = _GetStdHandle(stream_id) + return _SetConsoleTextAttribute(handle, attrs) + + def SetConsoleCursorPosition(stream_id, position, adjust=True): + position = COORD(*position) + # If the position is out of range, do nothing. + if position.Y <= 0 or position.X <= 0: + return + # Adjust for Windows' SetConsoleCursorPosition: + # 1. being 0-based, while ANSI is 1-based. + # 2. expecting (x,y), while ANSI uses (y,x). + adjusted_position = COORD(position.Y - 1, position.X - 1) + if adjust: + # Adjust for viewport's scroll position + sr = GetConsoleScreenBufferInfo(STDOUT).srWindow + adjusted_position.Y += sr.Top + adjusted_position.X += sr.Left + # Resume normal processing + handle = _GetStdHandle(stream_id) + return _SetConsoleCursorPosition(handle, adjusted_position) + + def FillConsoleOutputCharacter(stream_id, char, length, start): + handle = _GetStdHandle(stream_id) + char = c_char(char.encode()) + length = wintypes.DWORD(length) + num_written = wintypes.DWORD(0) + # Note that this is hard-coded for ANSI (vs wide) bytes. + success = _FillConsoleOutputCharacterA( + handle, char, length, start, byref(num_written)) + return num_written.value + + def FillConsoleOutputAttribute(stream_id, attr, length, start): + ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' + handle = _GetStdHandle(stream_id) + attribute = wintypes.WORD(attr) + length = wintypes.DWORD(length) + num_written = wintypes.DWORD(0) + # Note that this is hard-coded for ANSI (vs wide) bytes. + return _FillConsoleOutputAttribute( + handle, attribute, length, start, byref(num_written)) + + def SetConsoleTitle(title): + return _SetConsoleTitleW(title) + + def GetConsoleMode(handle): + mode = wintypes.DWORD() + success = _GetConsoleMode(handle, byref(mode)) + if not success: + raise ctypes.WinError() + return mode.value + + def SetConsoleMode(handle, mode): + success = _SetConsoleMode(handle, mode) + if not success: + raise ctypes.WinError() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/winterm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/winterm.py new file mode 100644 index 0000000000000000000000000000000000000000..aad867e8c80b826bf6a060116f17fa08a8eb0765 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/thirdparty_files/colorama/winterm.py @@ -0,0 +1,195 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +try: + from msvcrt import get_osfhandle +except ImportError: + def get_osfhandle(_): + raise OSError("This isn't windows!") + + +from . import win32 + +# from wincon.h +class WinColor(object): + BLACK = 0 + BLUE = 1 + GREEN = 2 + CYAN = 3 + RED = 4 + MAGENTA = 5 + YELLOW = 6 + GREY = 7 + +# from wincon.h +class WinStyle(object): + NORMAL = 0x00 # dim text, dim background + BRIGHT = 0x08 # bright text, dim background + BRIGHT_BACKGROUND = 0x80 # dim text, bright background + +class WinTerm(object): + + def __init__(self): + self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes + self.set_attrs(self._default) + self._default_fore = self._fore + self._default_back = self._back + self._default_style = self._style + # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style. + # So that LIGHT_EX colors and BRIGHT style do not clobber each other, + # we track them separately, since LIGHT_EX is overwritten by Fore/Back + # and BRIGHT is overwritten by Style codes. + self._light = 0 + + def get_attrs(self): + return self._fore + self._back * 16 + (self._style | self._light) + + def set_attrs(self, value): + self._fore = value & 7 + self._back = (value >> 4) & 7 + self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND) + + def reset_all(self, on_stderr=None): + self.set_attrs(self._default) + self.set_console(attrs=self._default) + self._light = 0 + + def fore(self, fore=None, light=False, on_stderr=False): + if fore is None: + fore = self._default_fore + self._fore = fore + # Emulate LIGHT_EX with BRIGHT Style + if light: + self._light |= WinStyle.BRIGHT + else: + self._light &= ~WinStyle.BRIGHT + self.set_console(on_stderr=on_stderr) + + def back(self, back=None, light=False, on_stderr=False): + if back is None: + back = self._default_back + self._back = back + # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style + if light: + self._light |= WinStyle.BRIGHT_BACKGROUND + else: + self._light &= ~WinStyle.BRIGHT_BACKGROUND + self.set_console(on_stderr=on_stderr) + + def style(self, style=None, on_stderr=False): + if style is None: + style = self._default_style + self._style = style + self.set_console(on_stderr=on_stderr) + + def set_console(self, attrs=None, on_stderr=False): + if attrs is None: + attrs = self.get_attrs() + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + win32.SetConsoleTextAttribute(handle, attrs) + + def get_position(self, handle): + position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition + # Because Windows coordinates are 0-based, + # and win32.SetConsoleCursorPosition expects 1-based. + position.X += 1 + position.Y += 1 + return position + + def set_cursor_position(self, position=None, on_stderr=False): + if position is None: + # I'm not currently tracking the position, so there is no default. + # position = self.get_position() + return + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + win32.SetConsoleCursorPosition(handle, position) + + def cursor_adjust(self, x, y, on_stderr=False): + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + position = self.get_position(handle) + adjusted_position = (position.Y + y, position.X + x) + win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False) + + def erase_screen(self, mode=0, on_stderr=False): + # 0 should clear from the cursor to the end of the screen. + # 1 should clear from the cursor to the beginning of the screen. + # 2 should clear the entire screen, and move cursor to (1,1) + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + csbi = win32.GetConsoleScreenBufferInfo(handle) + # get the number of character cells in the current buffer + cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y + # get number of character cells before current cursor position + cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X + if mode == 0: + from_coord = csbi.dwCursorPosition + cells_to_erase = cells_in_screen - cells_before_cursor + elif mode == 1: + from_coord = win32.COORD(0, 0) + cells_to_erase = cells_before_cursor + elif mode == 2: + from_coord = win32.COORD(0, 0) + cells_to_erase = cells_in_screen + else: + # invalid mode + return + # fill the entire screen with blanks + win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) + # now set the buffer's attributes accordingly + win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) + if mode == 2: + # put the cursor where needed + win32.SetConsoleCursorPosition(handle, (1, 1)) + + def erase_line(self, mode=0, on_stderr=False): + # 0 should clear from the cursor to the end of the line. + # 1 should clear from the cursor to the beginning of the line. + # 2 should clear the entire line. + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + csbi = win32.GetConsoleScreenBufferInfo(handle) + if mode == 0: + from_coord = csbi.dwCursorPosition + cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X + elif mode == 1: + from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) + cells_to_erase = csbi.dwCursorPosition.X + elif mode == 2: + from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) + cells_to_erase = csbi.dwSize.X + else: + # invalid mode + return + # fill the entire screen with blanks + win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) + # now set the buffer's attributes accordingly + win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) + + def set_title(self, title): + win32.SetConsoleTitle(title) + + +def enable_vt_processing(fd): + if win32.windll is None or not win32.winapi_test(): + return False + + try: + handle = get_osfhandle(fd) + mode = win32.GetConsoleMode(handle) + win32.SetConsoleMode( + handle, + mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING, + ) + + mode = win32.GetConsoleMode(handle) + if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING: + return True + # Can get TypeError in testsuite where 'fd' is a Mock() + except (OSError, TypeError): + return False