diff --git a/.gitattributes b/.gitattributes index 0125908cebece282009183aabcf6ca5d2c8f1b64..4293da0604b2fe6df466c29a04f2bdc312fcf5e5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1452,3 +1452,4 @@ parrot/lib/python3.10/site-packages/numpy/linalg/__pycache__/_linalg.cpython-310 vllm/lib/python3.10/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/numpy/_core/lib/libnpymath.a filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/numpy/_core/_multiarray_tests.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_ufunc.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_ufunc.cpython-310.pyc b/parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_ufunc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06ae780f9afadc201ae5776005bc35c00247f8d3 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_ufunc.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a4d941a6095db86ad6e706837ad9fb6bb6ee240ed2aada924c37002d0a75470 +size 105385 diff --git a/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/_idl.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/_idl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..199c7e7f5024ec2103dc175efc8fe3bd715d940f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/_idl.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/idl.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/idl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca0a55d1ac531c47f14b708eac4b2058772e1785 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/idl.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/mmio.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/mmio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcfba67f4d8c428848e22f2c1ab733068dd665e8 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/mmio.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/netcdf.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/netcdf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21ddaaacd3bf64c4103be030d3d0505a6cb98bc4 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/io/__pycache__/netcdf.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat new file mode 100644 index 0000000000000000000000000000000000000000..351801fd47a2e3e48d9b63034fbae28f8318c9f9 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat differ diff --git a/parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..49c0ec1d18d9f08111fe2d2a269ed407da71b158 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat differ diff --git a/parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav new file mode 100644 index 0000000000000000000000000000000000000000..fc9da5796eab6ce9fb59488b836ba2f567de7b25 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav differ diff --git a/parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..d16f4655cc20318db2b0d629cd5ed6d7be01b518 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/base_env.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/base_env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0776fcd2af8566d9f4ce450022c57f50b1181c15 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/base_env.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c77d8631bd3418faeb77657a8ed65d728c73411a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f368f4f6221694ff1f18e5e5ee20f39dc1e8ca9 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d1029453d46c67b1a2662fdd41c24b073e02727 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/task_settable_env.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/task_settable_env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e814bcda7c998b784c8c3436f635024a24810ecd Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/task_settable_env.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/external_multi_agent_env.py b/vllm/lib/python3.10/site-packages/ray/rllib/env/external_multi_agent_env.py new file mode 100644 index 0000000000000000000000000000000000000000..1350d5c7c3563f52a8c2c8a7951369d702a0307f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/env/external_multi_agent_env.py @@ -0,0 +1,161 @@ +import uuid +import gymnasium as gym +from typing import Optional + +from ray.rllib.utils.annotations import override, OldAPIStack +from ray.rllib.env.external_env import ExternalEnv, _ExternalEnvEpisode +from ray.rllib.utils.typing import MultiAgentDict + + +@OldAPIStack +class ExternalMultiAgentEnv(ExternalEnv): + """This is the multi-agent version of ExternalEnv.""" + + def __init__( + self, + action_space: gym.Space, + observation_space: gym.Space, + ): + """Initializes an ExternalMultiAgentEnv instance. + + Args: + action_space: Action space of the env. + observation_space: Observation space of the env. + """ + ExternalEnv.__init__(self, action_space, observation_space) + + # We require to know all agents' spaces. + if isinstance(self.action_space, dict) or isinstance( + self.observation_space, dict + ): + if not (self.action_space.keys() == self.observation_space.keys()): + raise ValueError( + "Agent ids disagree for action space and obs " + "space dict: {} {}".format( + self.action_space.keys(), self.observation_space.keys() + ) + ) + + def run(self): + """Override this to implement the multi-agent run loop. + + Your loop should continuously: + 1. Call self.start_episode(episode_id) + 2. Call self.get_action(episode_id, obs_dict) + -or- + self.log_action(episode_id, obs_dict, action_dict) + 3. Call self.log_returns(episode_id, reward_dict) + 4. Call self.end_episode(episode_id, obs_dict) + 5. Wait if nothing to do. + + Multiple episodes may be started at the same time. + """ + raise NotImplementedError + + @override(ExternalEnv) + def start_episode( + self, episode_id: Optional[str] = None, training_enabled: bool = True + ) -> str: + if episode_id is None: + episode_id = uuid.uuid4().hex + + if episode_id in self._finished: + raise ValueError("Episode {} has already completed.".format(episode_id)) + + if episode_id in self._episodes: + raise ValueError("Episode {} is already started".format(episode_id)) + + self._episodes[episode_id] = _ExternalEnvEpisode( + episode_id, self._results_avail_condition, training_enabled, multiagent=True + ) + + return episode_id + + @override(ExternalEnv) + def get_action( + self, episode_id: str, observation_dict: MultiAgentDict + ) -> MultiAgentDict: + """Record an observation and get the on-policy action. + + Thereby, observation_dict is expected to contain the observation + of all agents acting in this episode step. + + Args: + episode_id: Episode id returned from start_episode(). + observation_dict: Current environment observation. + + Returns: + action: Action from the env action space. + """ + + episode = self._get(episode_id) + return episode.wait_for_action(observation_dict) + + @override(ExternalEnv) + def log_action( + self, + episode_id: str, + observation_dict: MultiAgentDict, + action_dict: MultiAgentDict, + ) -> None: + """Record an observation and (off-policy) action taken. + + Args: + episode_id: Episode id returned from start_episode(). + observation_dict: Current environment observation. + action_dict: Action for the observation. + """ + + episode = self._get(episode_id) + episode.log_action(observation_dict, action_dict) + + @override(ExternalEnv) + def log_returns( + self, + episode_id: str, + reward_dict: MultiAgentDict, + info_dict: MultiAgentDict = None, + multiagent_done_dict: MultiAgentDict = None, + ) -> None: + """Record returns from the environment. + + The reward will be attributed to the previous action taken by the + episode. Rewards accumulate until the next action. If no reward is + logged before the next action, a reward of 0.0 is assumed. + + Args: + episode_id: Episode id returned from start_episode(). + reward_dict: Reward from the environment agents. + info_dict: Optional info dict. + multiagent_done_dict: Optional done dict for agents. + """ + + episode = self._get(episode_id) + + # Accumulate reward by agent. + # For existing agents, we want to add the reward up. + for agent, rew in reward_dict.items(): + if agent in episode.cur_reward_dict: + episode.cur_reward_dict[agent] += rew + else: + episode.cur_reward_dict[agent] = rew + + if multiagent_done_dict: + for agent, done in multiagent_done_dict.items(): + episode.cur_done_dict[agent] = done + + if info_dict: + episode.cur_info_dict = info_dict or {} + + @override(ExternalEnv) + def end_episode(self, episode_id: str, observation_dict: MultiAgentDict) -> None: + """Record the end of an episode. + + Args: + episode_id: Episode id returned from start_episode(). + observation_dict: Current environment observation. + """ + + episode = self._get(episode_id) + self._finished.add(episode.episode_id) + episode.done(observation_dict) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/remote_base_env.py b/vllm/lib/python3.10/site-packages/ray/rllib/env/remote_base_env.py new file mode 100644 index 0000000000000000000000000000000000000000..b9e388d50bcfbbb663f22e670b4707849400b6f7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/env/remote_base_env.py @@ -0,0 +1,462 @@ +import gymnasium as gym +import logging +from typing import Callable, Dict, List, Optional, Set, Tuple, TYPE_CHECKING + +import ray +from ray.util import log_once +from ray.rllib.env.base_env import BaseEnv, _DUMMY_AGENT_ID, ASYNC_RESET_RETURN +from ray.rllib.utils.annotations import override, OldAPIStack +from ray.rllib.utils.typing import AgentID, EnvID, EnvType, MultiEnvDict + +if TYPE_CHECKING: + from ray.rllib.evaluation.rollout_worker import RolloutWorker + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class RemoteBaseEnv(BaseEnv): + """BaseEnv that executes its sub environments as @ray.remote actors. + + This provides dynamic batching of inference as observations are returned + from the remote simulator actors. Both single and multi-agent child envs + are supported, and envs can be stepped synchronously or asynchronously. + + NOTE: This class implicitly assumes that the remote envs are gym.Env's + + You shouldn't need to instantiate this class directly. It's automatically + inserted when you use the `remote_worker_envs=True` option in your + Algorithm's config. + """ + + def __init__( + self, + make_env: Callable[[int], EnvType], + num_envs: int, + multiagent: bool, + remote_env_batch_wait_ms: int, + existing_envs: Optional[List[ray.actor.ActorHandle]] = None, + worker: Optional["RolloutWorker"] = None, + restart_failed_sub_environments: bool = False, + ): + """Initializes a RemoteVectorEnv instance. + + Args: + make_env: Callable that produces a single (non-vectorized) env, + given the vector env index as only arg. + num_envs: The number of sub-environments to create for the + vectorization. + multiagent: Whether this is a multiagent env or not. + remote_env_batch_wait_ms: Time to wait for (ray.remote) + sub-environments to have new observations available when + polled. Only when none of the sub-environments is ready, + repeat the `ray.wait()` call until at least one sub-env + is ready. Then return only the observations of the ready + sub-environment(s). + existing_envs: Optional list of already created sub-environments. + These will be used as-is and only as many new sub-envs as + necessary (`num_envs - len(existing_envs)`) will be created. + worker: An optional RolloutWorker that owns the env. This is only + used if `remote_worker_envs` is True in your config and the + `on_sub_environment_created` custom callback needs to be + called on each created actor. + restart_failed_sub_environments: If True and any sub-environment (within + a vectorized env) throws any error during env stepping, the + Sampler will try to restart the faulty sub-environment. This is done + without disturbing the other (still intact) sub-environment and without + the RolloutWorker crashing. + """ + + # Could be creating local or remote envs. + self.make_env = make_env + self.num_envs = num_envs + self.multiagent = multiagent + self.poll_timeout = remote_env_batch_wait_ms / 1000 + self.worker = worker + self.restart_failed_sub_environments = restart_failed_sub_environments + + # Already existing env objects (generated by the RolloutWorker). + existing_envs = existing_envs or [] + + # Whether the given `make_env` callable already returns ActorHandles + # (@ray.remote class instances) or not. + self.make_env_creates_actors = False + + self._observation_space = None + self._action_space = None + + # List of ray actor handles (each handle points to one @ray.remote + # sub-environment). + self.actors: Optional[List[ray.actor.ActorHandle]] = None + + # `self.make_env` already produces Actors: Use it directly. + if len(existing_envs) > 0 and isinstance( + existing_envs[0], ray.actor.ActorHandle + ): + self.make_env_creates_actors = True + self.actors = existing_envs + while len(self.actors) < self.num_envs: + self.actors.append(self._make_sub_env(len(self.actors))) + + # `self.make_env` produces gym.Envs (or children thereof, such + # as MultiAgentEnv): Need to auto-wrap it here. The problem with + # this is that custom methods wil get lost. If you would like to + # keep your custom methods in your envs, you should provide the + # env class directly in your config (w/o tune.register_env()), + # such that your class can directly be made a @ray.remote + # (w/o the wrapping via `_Remote[Multi|Single]AgentEnv`). + # Also, if `len(existing_envs) > 0`, we have to throw those away + # as we need to create ray actors here. + else: + self.actors = [self._make_sub_env(i) for i in range(self.num_envs)] + # Utilize existing envs for inferring observation/action spaces. + if len(existing_envs) > 0: + self._observation_space = existing_envs[0].observation_space + self._action_space = existing_envs[0].action_space + # Have to call actors' remote methods to get observation/action spaces. + else: + self._observation_space, self._action_space = ray.get( + [ + self.actors[0].observation_space.remote(), + self.actors[0].action_space.remote(), + ] + ) + + # Dict mapping object refs (return values of @ray.remote calls), + # whose actual values we are waiting for (via ray.wait in + # `self.poll()`) to their corresponding actor handles (the actors + # that created these return values). + # Call `reset()` on all @ray.remote sub-environment actors. + self.pending: Dict[ray.actor.ActorHandle] = { + a.reset.remote(): a for a in self.actors + } + + @override(BaseEnv) + def poll( + self, + ) -> Tuple[ + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + ]: + + # each keyed by env_id in [0, num_remote_envs) + obs, rewards, terminateds, truncateds, infos = {}, {}, {}, {}, {} + ready = [] + + # Wait for at least 1 env to be ready here. + while not ready: + ready, _ = ray.wait( + list(self.pending), + num_returns=len(self.pending), + timeout=self.poll_timeout, + ) + + # Get and return observations for each of the ready envs + env_ids = set() + for obj_ref in ready: + # Get the corresponding actor handle from our dict and remove the + # object ref (we will call `ray.get()` on it and it will no longer + # be "pending"). + actor = self.pending.pop(obj_ref) + env_id = self.actors.index(actor) + env_ids.add(env_id) + # Get the ready object ref (this may be return value(s) of + # `reset()` or `step()`). + try: + ret = ray.get(obj_ref) + except Exception as e: + # Something happened on the actor during stepping/resetting. + # Restart sub-environment (create new actor; close old one). + if self.restart_failed_sub_environments: + logger.exception(e.args[0]) + self.try_restart(env_id) + # Always return multi-agent data. + # Set the observation to the exception, no rewards, + # terminated[__all__]=True (episode will be discarded anyways), + # no infos. + ret = ( + e, + {}, + {"__all__": True}, + {"__all__": False}, + {}, + ) + # Do not try to restart. Just raise the error. + else: + raise e + + # Our sub-envs are simple Actor-turned gym.Envs or MultiAgentEnvs. + if self.make_env_creates_actors: + rew, terminated, truncated, info = None, None, None, None + if self.multiagent: + if isinstance(ret, tuple): + # Gym >= 0.26: `step()` result: Obs, reward, terminated, + # truncated, info. + if len(ret) == 5: + ob, rew, terminated, truncated, info = ret + # Gym >= 0.26: `reset()` result: Obs and infos. + elif len(ret) == 2: + ob = ret[0] + info = ret[1] + # Gym < 0.26? Something went wrong. + else: + raise AssertionError( + "Your gymnasium.Env seems to NOT return the correct " + "number of return values for `step()` (needs to return" + " 5 values: obs, reward, terminated, truncated and " + "info) or `reset()` (needs to return 2 values: obs and " + "info)!" + ) + # Gym < 0.26: `reset()` result: Only obs. + else: + raise AssertionError( + "Your gymnasium.Env seems to only return a single value " + "upon `reset()`! Must return 2 (obs AND infos)." + ) + else: + if isinstance(ret, tuple): + # `step()` result: Obs, reward, terminated, truncated, info. + if len(ret) == 5: + ob = {_DUMMY_AGENT_ID: ret[0]} + rew = {_DUMMY_AGENT_ID: ret[1]} + terminated = {_DUMMY_AGENT_ID: ret[2], "__all__": ret[2]} + truncated = {_DUMMY_AGENT_ID: ret[3], "__all__": ret[3]} + info = {_DUMMY_AGENT_ID: ret[4]} + # `reset()` result: Obs and infos. + elif len(ret) == 2: + ob = {_DUMMY_AGENT_ID: ret[0]} + info = {_DUMMY_AGENT_ID: ret[1]} + # Gym < 0.26? Something went wrong. + else: + raise AssertionError( + "Your gymnasium.Env seems to NOT return the correct " + "number of return values for `step()` (needs to return" + " 5 values: obs, reward, terminated, truncated and " + "info) or `reset()` (needs to return 2 values: obs and " + "info)!" + ) + # Gym < 0.26? + else: + raise AssertionError( + "Your gymnasium.Env seems to only return a single value " + "upon `reset()`! Must return 2 (obs and infos)." + ) + + # If this is a `reset()` return value, we only have the initial + # observations and infos: Set rewards, terminateds, and truncateds to + # dummy values. + if rew is None: + rew = {agent_id: 0 for agent_id in ob.keys()} + terminated = {"__all__": False} + truncated = {"__all__": False} + + # Our sub-envs are auto-wrapped (by `_RemoteSingleAgentEnv` or + # `_RemoteMultiAgentEnv`) and already behave like multi-agent + # envs. + else: + ob, rew, terminated, truncated, info = ret + obs[env_id] = ob + rewards[env_id] = rew + terminateds[env_id] = terminated + truncateds[env_id] = truncated + infos[env_id] = info + + logger.debug(f"Got obs batch for actors {env_ids}") + return obs, rewards, terminateds, truncateds, infos, {} + + @override(BaseEnv) + def send_actions(self, action_dict: MultiEnvDict) -> None: + for env_id, actions in action_dict.items(): + actor = self.actors[env_id] + # `actor` is a simple single-agent (remote) env, e.g. a gym.Env + # that was made a @ray.remote. + if not self.multiagent and self.make_env_creates_actors: + obj_ref = actor.step.remote(actions[_DUMMY_AGENT_ID]) + # `actor` is already a _RemoteSingleAgentEnv or + # _RemoteMultiAgentEnv wrapper + # (handles the multi-agent action_dict automatically). + else: + obj_ref = actor.step.remote(actions) + self.pending[obj_ref] = actor + + @override(BaseEnv) + def try_reset( + self, + env_id: Optional[EnvID] = None, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Tuple[MultiEnvDict, MultiEnvDict]: + actor = self.actors[env_id] + obj_ref = actor.reset.remote(seed=seed, options=options) + + self.pending[obj_ref] = actor + # Because this env type does not support synchronous reset requests (with + # immediate return value), we return ASYNC_RESET_RETURN here to indicate + # that the reset results will be available via the next `poll()` call. + return ASYNC_RESET_RETURN, ASYNC_RESET_RETURN + + @override(BaseEnv) + def try_restart(self, env_id: Optional[EnvID] = None) -> None: + # Try closing down the old (possibly faulty) sub-env, but ignore errors. + try: + # Close the env on the remote side. + self.actors[env_id].close.remote() + except Exception as e: + if log_once("close_sub_env"): + logger.warning( + "Trying to close old and replaced sub-environment (at vector " + f"index={env_id}), but closing resulted in error:\n{e}" + ) + + # Terminate the actor itself to free up its resources. + self.actors[env_id].__ray_terminate__.remote() + + # Re-create a new sub-environment. + self.actors[env_id] = self._make_sub_env(env_id) + + @override(BaseEnv) + def stop(self) -> None: + if self.actors is not None: + for actor in self.actors: + actor.__ray_terminate__.remote() + + @override(BaseEnv) + def get_sub_environments(self, as_dict: bool = False) -> List[EnvType]: + if as_dict: + return {env_id: actor for env_id, actor in enumerate(self.actors)} + return self.actors + + @property + @override(BaseEnv) + def observation_space(self) -> gym.spaces.Dict: + return self._observation_space + + @property + @override(BaseEnv) + def action_space(self) -> gym.Space: + return self._action_space + + def _make_sub_env(self, idx: Optional[int] = None): + """Re-creates a sub-environment at the new index.""" + + # Our `make_env` creates ray actors directly. + if self.make_env_creates_actors: + sub_env = self.make_env(idx) + if self.worker is not None: + self.worker.callbacks.on_sub_environment_created( + worker=self.worker, + sub_environment=self.actors[idx], + env_context=self.worker.env_context.copy_with_overrides( + vector_index=idx + ), + ) + + # Our `make_env` returns actual envs -> Have to convert them into actors + # using our utility wrapper classes. + else: + + def make_remote_env(i): + logger.info("Launching env {} in remote actor".format(i)) + if self.multiagent: + sub_env = _RemoteMultiAgentEnv.remote(self.make_env, i) + else: + sub_env = _RemoteSingleAgentEnv.remote(self.make_env, i) + + if self.worker is not None: + self.worker.callbacks.on_sub_environment_created( + worker=self.worker, + sub_environment=sub_env, + env_context=self.worker.env_context.copy_with_overrides( + vector_index=i + ), + ) + + return sub_env + + sub_env = make_remote_env(idx) + + return sub_env + + @override(BaseEnv) + def get_agent_ids(self) -> Set[AgentID]: + if self.multiagent: + return ray.get(self.actors[0].get_agent_ids.remote()) + else: + return {_DUMMY_AGENT_ID} + + +@ray.remote(num_cpus=0) +class _RemoteMultiAgentEnv: + """Wrapper class for making a multi-agent env a remote actor.""" + + def __init__(self, make_env, i): + self.env = make_env(i) + self.agent_ids = set() + + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + obs, info = self.env.reset(seed=seed, options=options) + + # each keyed by agent_id in the env + rew = {} + for agent_id in obs.keys(): + self.agent_ids.add(agent_id) + rew[agent_id] = 0.0 + terminated = {"__all__": False} + truncated = {"__all__": False} + return obs, rew, terminated, truncated, info + + def step(self, action_dict): + return self.env.step(action_dict) + + # Defining these 2 functions that way this information can be queried + # with a call to ray.get(). + def observation_space(self): + return self.env.observation_space + + def action_space(self): + return self.env.action_space + + def get_agent_ids(self) -> Set[AgentID]: + return self.agent_ids + + +@ray.remote(num_cpus=0) +class _RemoteSingleAgentEnv: + """Wrapper class for making a gym env a remote actor.""" + + def __init__(self, make_env, i): + self.env = make_env(i) + + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + obs_and_info = self.env.reset(seed=seed, options=options) + + obs = {_DUMMY_AGENT_ID: obs_and_info[0]} + info = {_DUMMY_AGENT_ID: obs_and_info[1]} + + rew = {_DUMMY_AGENT_ID: 0.0} + terminated = {"__all__": False} + truncated = {"__all__": False} + return obs, rew, terminated, truncated, info + + def step(self, action): + results = self.env.step(action[_DUMMY_AGENT_ID]) + + obs, rew, terminated, truncated, info = [{_DUMMY_AGENT_ID: x} for x in results] + + terminated["__all__"] = terminated[_DUMMY_AGENT_ID] + truncated["__all__"] = truncated[_DUMMY_AGENT_ID] + + return obs, rew, terminated, truncated, info + + # Defining these 2 functions that way this information can be queried + # with a call to ray.get(). + def observation_space(self): + return self.env.observation_space + + def action_space(self): + return self.env.action_space diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/env/utils/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/env/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..09dfbe227e5a6c29bdfa7096758d529ddcb72d55 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py b/vllm/lib/python3.10/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..cd84a8518097f17633fe731ad3d12dab95cae31b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py @@ -0,0 +1,707 @@ +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, +) + + +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, np.array(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: + data_to_use = self.data[:-1] + if _add_last_ts_value is not None: + data_to_use = np.append(data_to_use.copy(), _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/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56b3d834c4acc68d2d9b7c8b8a4dc15afed56b2c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/action_dist.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/action_dist.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..764821a83b63fd82d3c95fc2ef03fccb2a2581ff Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/action_dist.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/catalog.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/catalog.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbc413f737e4e3b66043db480a82abc9390dcbc0 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/catalog.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/distributions.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d983f444741f161de86e4bac2bb0cf38f19f003 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/distributions.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/modelv2.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/modelv2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65614a303a6019b75bc8dc82d07e98d557273765 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/modelv2.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/preprocessors.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/preprocessors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44ef61512ce9becd6017074da584287908ff426a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/preprocessors.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/repeated_values.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/repeated_values.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35cb19652ffc408a77e8f0139cadc5a8a9dda94e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/repeated_values.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/utils.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa819c6103f84f610ee0195815dee64e4063a7a4 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/utils.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/preprocessors.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/preprocessors.py new file mode 100644 index 0000000000000000000000000000000000000000..ad15d0c155124e38ba7fb8c84b162b7a564d4c9a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/models/preprocessors.py @@ -0,0 +1,447 @@ +from collections import OrderedDict +import logging +import numpy as np +import gymnasium as gym +from typing import Any, List + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.spaces.repeated import Repeated +from ray.rllib.utils.typing import TensorType +from ray.rllib.utils.images import resize +from ray.rllib.utils.spaces.space_utils import convert_element_to_space_type + +ATARI_OBS_SHAPE = (210, 160, 3) +ATARI_RAM_OBS_SHAPE = (128,) + +# Only validate env observations vs the observation space every n times in a +# Preprocessor. +OBS_VALIDATION_INTERVAL = 100 + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class Preprocessor: + """Defines an abstract observation preprocessor function. + + Attributes: + shape (List[int]): Shape of the preprocessed output. + """ + + def __init__(self, obs_space: gym.Space, options: dict = None): + _legacy_patch_shapes(obs_space) + self._obs_space = obs_space + if not options: + from ray.rllib.models.catalog import MODEL_DEFAULTS + + self._options = MODEL_DEFAULTS.copy() + else: + self._options = options + self.shape = self._init_shape(obs_space, self._options) + self._size = int(np.prod(self.shape)) + self._i = 0 + self._obs_for_type_matching = self._obs_space.sample() + + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + """Returns the shape after preprocessing.""" + raise NotImplementedError + + def transform(self, observation: TensorType) -> np.ndarray: + """Returns the preprocessed observation.""" + raise NotImplementedError + + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + """Alternative to transform for more efficient flattening.""" + array[offset : offset + self._size] = self.transform(observation) + + def check_shape(self, observation: Any) -> None: + """Checks the shape of the given observation.""" + if self._i % OBS_VALIDATION_INTERVAL == 0: + # Convert lists to np.ndarrays. + if type(observation) is list and isinstance( + self._obs_space, gym.spaces.Box + ): + observation = np.array(observation).astype(np.float32) + if not self._obs_space.contains(observation): + observation = convert_element_to_space_type( + observation, self._obs_for_type_matching + ) + try: + if not self._obs_space.contains(observation): + raise ValueError( + "Observation ({} dtype={}) outside given space ({})!".format( + observation, + observation.dtype + if isinstance(self._obs_space, gym.spaces.Box) + else None, + self._obs_space, + ) + ) + except AttributeError as e: + raise ValueError( + "Observation for a Box/MultiBinary/MultiDiscrete space " + "should be an np.array, not a Python list.", + observation, + ) from e + self._i += 1 + + @property + def size(self) -> int: + return self._size + + @property + def observation_space(self) -> gym.Space: + obs_space = gym.spaces.Box(-1.0, 1.0, self.shape, dtype=np.float32) + # Stash the unwrapped space so that we can unwrap dict and tuple spaces + # automatically in modelv2.py + classes = ( + DictFlatteningPreprocessor, + OneHotPreprocessor, + RepeatedValuesPreprocessor, + TupleFlatteningPreprocessor, + AtariRamPreprocessor, + GenericPixelPreprocessor, + ) + if isinstance(self, classes): + obs_space.original_space = self._obs_space + return obs_space + + +@OldAPIStack +class GenericPixelPreprocessor(Preprocessor): + """Generic image preprocessor. + + Note: for Atari games, use config {"preprocessor_pref": "deepmind"} + instead for deepmind-style Atari preprocessing. + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + self._grayscale = options.get("grayscale") + self._zero_mean = options.get("zero_mean") + self._dim = options.get("dim") + if self._grayscale: + shape = (self._dim, self._dim, 1) + else: + shape = (self._dim, self._dim, 3) + + return shape + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + """Downsamples images from (210, 160, 3) by the configured factor.""" + self.check_shape(observation) + scaled = observation[25:-25, :, :] + if self._dim < 84: + scaled = resize(scaled, height=84, width=84) + # OpenAI: Resize by half, then down to 42x42 (essentially mipmapping). + # If we resize directly we lose pixels that, when mapped to 42x42, + # aren't close enough to the pixel boundary. + scaled = resize(scaled, height=self._dim, width=self._dim) + if self._grayscale: + scaled = scaled.mean(2) + scaled = scaled.astype(np.float32) + # Rescale needed for maintaining 1 channel + scaled = np.reshape(scaled, [self._dim, self._dim, 1]) + if self._zero_mean: + scaled = (scaled - 128) / 128 + else: + scaled *= 1.0 / 255.0 + return scaled + + +@OldAPIStack +class AtariRamPreprocessor(Preprocessor): + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + return (128,) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + return (observation.astype("float32") - 128) / 128 + + +@OldAPIStack +class OneHotPreprocessor(Preprocessor): + """One-hot preprocessor for Discrete and MultiDiscrete spaces. + + .. testcode:: + :skipif: True + + self.transform(Discrete(3).sample()) + + .. testoutput:: + + np.array([0.0, 1.0, 0.0]) + + .. testcode:: + :skipif: True + + self.transform(MultiDiscrete([2, 3]).sample()) + + .. testoutput:: + + np.array([0.0, 1.0, 0.0, 0.0, 1.0]) + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + if isinstance(obs_space, gym.spaces.Discrete): + return (self._obs_space.n,) + else: + return (np.sum(self._obs_space.nvec),) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + return gym.spaces.utils.flatten(self._obs_space, observation).astype(np.float32) + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + array[offset : offset + self.size] = self.transform(observation) + + +@OldAPIStack +class NoPreprocessor(Preprocessor): + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + return self._obs_space.shape + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + return observation + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + array[offset : offset + self._size] = np.array(observation, copy=False).ravel() + + @property + @override(Preprocessor) + def observation_space(self) -> gym.Space: + return self._obs_space + + +@OldAPIStack +class MultiBinaryPreprocessor(Preprocessor): + """Preprocessor that turns a MultiBinary space into a Box. + + Note: Before RLModules were introduced, RLlib's ModelCatalogV2 would produce + ComplexInputNetworks that treat MultiBinary spaces as Boxes. This preprocessor is + needed to get rid of the ComplexInputNetworks and use RLModules instead because + RLModules lack the logic to handle MultiBinary or other non-Box spaces. + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + return self._obs_space.shape + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + # The shape stays the same, but the dtype changes. + self.check_shape(observation) + return observation.astype(np.float32) + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + array[offset : offset + self._size] = np.array(observation, copy=False).ravel() + + @property + @override(Preprocessor) + def observation_space(self) -> gym.Space: + obs_space = gym.spaces.Box(0.0, 1.0, self.shape, dtype=np.float32) + obs_space.original_space = self._obs_space + return obs_space + + +@OldAPIStack +class TupleFlatteningPreprocessor(Preprocessor): + """Preprocesses each tuple element, then flattens it all into a vector. + + RLlib models will unpack the flattened output before _build_layers_v2(). + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + assert isinstance(self._obs_space, gym.spaces.Tuple) + size = 0 + self.preprocessors = [] + for i in range(len(self._obs_space.spaces)): + space = self._obs_space.spaces[i] + logger.debug("Creating sub-preprocessor for {}".format(space)) + preprocessor_class = get_preprocessor(space) + if preprocessor_class is not None: + preprocessor = preprocessor_class(space, self._options) + size += preprocessor.size + else: + preprocessor = None + size += int(np.prod(space.shape)) + self.preprocessors.append(preprocessor) + return (size,) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + array = np.zeros(self.shape, dtype=np.float32) + self.write(observation, array, 0) + return array + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + assert len(observation) == len(self.preprocessors), observation + for o, p in zip(observation, self.preprocessors): + p.write(o, array, offset) + offset += p.size + + +@OldAPIStack +class DictFlatteningPreprocessor(Preprocessor): + """Preprocesses each dict value, then flattens it all into a vector. + + RLlib models will unpack the flattened output before _build_layers_v2(). + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + assert isinstance(self._obs_space, gym.spaces.Dict) + size = 0 + self.preprocessors = [] + for space in self._obs_space.spaces.values(): + logger.debug("Creating sub-preprocessor for {}".format(space)) + preprocessor_class = get_preprocessor(space) + if preprocessor_class is not None: + preprocessor = preprocessor_class(space, self._options) + size += preprocessor.size + else: + preprocessor = None + size += int(np.prod(space.shape)) + self.preprocessors.append(preprocessor) + return (size,) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + array = np.zeros(self.shape, dtype=np.float32) + self.write(observation, array, 0) + return array + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + if not isinstance(observation, OrderedDict): + observation = OrderedDict(sorted(observation.items())) + assert len(observation) == len(self.preprocessors), ( + len(observation), + len(self.preprocessors), + ) + for o, p in zip(observation.values(), self.preprocessors): + p.write(o, array, offset) + offset += p.size + + +@OldAPIStack +class RepeatedValuesPreprocessor(Preprocessor): + """Pads and batches the variable-length list value.""" + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + assert isinstance(self._obs_space, Repeated) + child_space = obs_space.child_space + self.child_preprocessor = get_preprocessor(child_space)( + child_space, self._options + ) + # The first slot encodes the list length. + size = 1 + self.child_preprocessor.size * obs_space.max_len + return (size,) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + array = np.zeros(self.shape) + if isinstance(observation, list): + for elem in observation: + self.child_preprocessor.check_shape(elem) + else: + pass # ValueError will be raised in write() below. + self.write(observation, array, 0) + return array + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + if not isinstance(observation, (list, np.ndarray)): + raise ValueError( + "Input for {} must be list type, got {}".format(self, observation) + ) + elif len(observation) > self._obs_space.max_len: + raise ValueError( + "Input {} exceeds max len of space {}".format( + observation, self._obs_space.max_len + ) + ) + # The first slot encodes the list length. + array[offset] = len(observation) + for i, elem in enumerate(observation): + offset_i = offset + 1 + i * self.child_preprocessor.size + self.child_preprocessor.write(elem, array, offset_i) + + +@OldAPIStack +def get_preprocessor(space: gym.Space, include_multi_binary=False) -> type: + """Returns an appropriate preprocessor class for the given space.""" + + _legacy_patch_shapes(space) + obs_shape = space.shape + + if isinstance(space, (gym.spaces.Discrete, gym.spaces.MultiDiscrete)): + preprocessor = OneHotPreprocessor + elif obs_shape == ATARI_OBS_SHAPE: + logger.debug( + "Defaulting to RLlib's GenericPixelPreprocessor because input " + "space has the atari-typical shape {}. Turn this behaviour off by setting " + "`preprocessor_pref=None` or " + "`preprocessor_pref='deepmind'` or disabling the preprocessing API " + "altogether with `_disable_preprocessor_api=True`.".format(ATARI_OBS_SHAPE) + ) + preprocessor = GenericPixelPreprocessor + elif obs_shape == ATARI_RAM_OBS_SHAPE: + logger.debug( + "Defaulting to RLlib's AtariRamPreprocessor because input " + "space has the atari-typical shape {}. Turn this behaviour off by setting " + "`preprocessor_pref=None` or " + "`preprocessor_pref='deepmind' or disabling the preprocessing API " + "altogether with `_disable_preprocessor_api=True`." + "`.".format(ATARI_OBS_SHAPE) + ) + preprocessor = AtariRamPreprocessor + elif isinstance(space, gym.spaces.Tuple): + preprocessor = TupleFlatteningPreprocessor + elif isinstance(space, gym.spaces.Dict): + preprocessor = DictFlatteningPreprocessor + elif isinstance(space, Repeated): + preprocessor = RepeatedValuesPreprocessor + # We usually only want to include this when using RLModules + elif isinstance(space, gym.spaces.MultiBinary) and include_multi_binary: + preprocessor = MultiBinaryPreprocessor + else: + preprocessor = NoPreprocessor + + return preprocessor + + +def _legacy_patch_shapes(space: gym.Space) -> List[int]: + """Assigns shapes to spaces that don't have shapes. + + This is only needed for older gym versions that don't set shapes properly + for Tuple and Discrete spaces. + """ + + if not hasattr(space, "shape"): + if isinstance(space, gym.spaces.Discrete): + space.shape = () + elif isinstance(space, gym.spaces.Tuple): + shapes = [] + for s in space.spaces: + shape = _legacy_patch_shapes(s) + shapes.append(shape) + space.shape = tuple(shapes) + + return space.shape diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/repeated_values.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/repeated_values.py new file mode 100644 index 0000000000000000000000000000000000000000..7ecef777f667bffec0008bb0b1fdf1aa7c88d52e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/models/repeated_values.py @@ -0,0 +1,204 @@ +from typing import List + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import TensorType, TensorStructType + + +@OldAPIStack +class RepeatedValues: + """Represents a variable-length list of items from spaces.Repeated. + + RepeatedValues are created when you use spaces.Repeated, and are + accessible as part of input_dict["obs"] in ModelV2 forward functions. + + Example: + Suppose the gym space definition was: + Repeated(Repeated(Box(K), N), M) + + Then in the model forward function, input_dict["obs"] is of type: + RepeatedValues(RepeatedValues()) + + The tensor is accessible via: + input_dict["obs"].values.values + + And the actual data lengths via: + # outer repetition, shape [B], range [0, M] + input_dict["obs"].lengths + -and- + # inner repetition, shape [B, M], range [0, N] + input_dict["obs"].values.lengths + + Attributes: + values: The padded data tensor of shape [B, max_len, ..., sz], + where B is the batch dimension, max_len is the max length of this + list, followed by any number of sub list max lens, followed by the + actual data size. + lengths (List[int]): Tensor of shape [B, ...] that represents the + number of valid items in each list. When the list is nested within + other lists, there will be extra dimensions for the parent list + max lens. + max_len: The max number of items allowed in each list. + + TODO(ekl): support conversion to tf.RaggedTensor. + """ + + def __init__(self, values: TensorType, lengths: List[int], max_len: int): + self.values = values + self.lengths = lengths + self.max_len = max_len + self._unbatched_repr = None + + def unbatch_all(self) -> List[List[TensorType]]: + """Unbatch both the repeat and batch dimensions into Python lists. + + This is only supported in PyTorch / TF eager mode. + + This lets you view the data unbatched in its original form, but is + not efficient for processing. + + .. testcode:: + :skipif: True + + batch = RepeatedValues() + items = batch.unbatch_all() + print(len(items) == B) + + .. testoutput:: + + True + + .. testcode:: + :skipif: True + + print(max(len(x) for x in items) <= N) + + .. testoutput:: + + True + + .. testcode:: + :skipif: True + + print(items) + + .. testoutput:: + + [[, ..., ], + ... + [, ], + ... + [], + ... + [, ..., ]] + """ + + if self._unbatched_repr is None: + B = _get_batch_dim_helper(self.values) + if B is None: + raise ValueError( + "Cannot call unbatch_all() when batch_dim is unknown. " + "This is probably because you are using TF graph mode." + ) + else: + B = int(B) + slices = self.unbatch_repeat_dim() + result = [] + for i in range(B): + if hasattr(self.lengths[i], "item"): + dynamic_len = int(self.lengths[i].item()) + else: + dynamic_len = int(self.lengths[i].numpy()) + dynamic_slice = [] + for j in range(dynamic_len): + dynamic_slice.append(_batch_index_helper(slices, i, j)) + result.append(dynamic_slice) + self._unbatched_repr = result + + return self._unbatched_repr + + def unbatch_repeat_dim(self) -> List[TensorType]: + """Unbatches the repeat dimension (the one `max_len` in size). + + This removes the repeat dimension. The result will be a Python list of + with length `self.max_len`. Note that the data is still padded. + + .. testcode:: + :skipif: True + + batch = RepeatedValues() + items = batch.unbatch() + len(items) == batch.max_len + + .. testoutput:: + + True + + .. testcode:: + :skipif: True + + print(items) + + .. testoutput:: + + [, ..., ] + """ + return _unbatch_helper(self.values, self.max_len) + + def __repr__(self): + return "RepeatedValues(value={}, lengths={}, max_len={})".format( + repr(self.values), repr(self.lengths), self.max_len + ) + + def __str__(self): + return repr(self) + + +def _get_batch_dim_helper(v: TensorStructType) -> int: + """Tries to find the batch dimension size of v, or None.""" + if isinstance(v, dict): + for u in v.values(): + return _get_batch_dim_helper(u) + elif isinstance(v, tuple): + return _get_batch_dim_helper(v[0]) + elif isinstance(v, RepeatedValues): + return _get_batch_dim_helper(v.values) + else: + B = v.shape[0] + if hasattr(B, "value"): + B = B.value # TensorFlow + return B + + +def _unbatch_helper(v: TensorStructType, max_len: int) -> TensorStructType: + """Recursively unpacks the repeat dimension (max_len).""" + if isinstance(v, dict): + return {k: _unbatch_helper(u, max_len) for (k, u) in v.items()} + elif isinstance(v, tuple): + return tuple(_unbatch_helper(u, max_len) for u in v) + elif isinstance(v, RepeatedValues): + unbatched = _unbatch_helper(v.values, max_len) + return [ + RepeatedValues(u, v.lengths[:, i, ...], v.max_len) + for i, u in enumerate(unbatched) + ] + else: + return [v[:, i, ...] for i in range(max_len)] + + +def _batch_index_helper(v: TensorStructType, i: int, j: int) -> TensorStructType: + """Selects the item at the ith batch index and jth repetition.""" + if isinstance(v, dict): + return {k: _batch_index_helper(u, i, j) for (k, u) in v.items()} + elif isinstance(v, tuple): + return tuple(_batch_index_helper(u, i, j) for u in v) + elif isinstance(v, list): + # This is the output of unbatch_repeat_dim(). Unfortunately we have to + # process it here instead of in unbatch_all(), since it may be buried + # under a dict / tuple. + return _batch_index_helper(v[j], i, j) + elif isinstance(v, RepeatedValues): + unbatched = v.unbatch_all() + # Don't need to select j here; that's already done in unbatch_all. + return unbatched[i] + else: + return v[i, ...] diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/attention_net.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/attention_net.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c70ba8105651cc45aad35045addec97e36c8be2e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/attention_net.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/complex_input_net.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/complex_input_net.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fc42a141304fa56c7d66f899df9b7fda3455f0e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/complex_input_net.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/fcnet.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/fcnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fedbb0f5a0f40a23bbb5751e19889d83dde3761 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/fcnet.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/misc.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/misc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d23e0acbc9d4ea58f1a2355d59a1cd340329405c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/misc.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/noop.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/noop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a508cc3e87e37cf8538c79a49bfb8c27313a641e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/noop.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/recurrent_net.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/recurrent_net.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7e36cf52e516eb3305d78272392b19d1504049d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/recurrent_net.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/tf_distributions.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/tf_distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ee8d4f5dc79fbd1ac0cfcf2ead0aabc6c7304cb Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/tf_distributions.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/visionnet.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/visionnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..797f4fd53c3c5b4c76705958aaabf7ceaf0b667f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/visionnet.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/fcnet.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/fcnet.py new file mode 100644 index 0000000000000000000000000000000000000000..56a09de0361acf371f5d6b8ab60fc7d2790565c7 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6a9e522e9e8ab27e034f3922cf835a2d3bc6561 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/gru_gate.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/gru_gate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebc526e1230289a44b2e26b15e88ce8f68c253f7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/gru_gate.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/multi_head_attention.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/multi_head_attention.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3510f28b84eddb39831c5dcba957f1491518aa5e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/multi_head_attention.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/noisy_layer.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/noisy_layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9c437eda47496f418c3e10c9038ba358c388e72 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/noisy_layer.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/relative_multi_head_attention.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/relative_multi_head_attention.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f4346e1943bdf590c109bb8e372a1f4dde3f11a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/relative_multi_head_attention.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/skip_connection.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/skip_connection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccda9d886d52db12b54ccef8ddea62543cd8f568 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/skip_connection.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/gru_gate.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/gru_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..a41b23bbf534a15d0d3c71333bcba1bb0c0a6d3b --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/multi_head_attention.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/multi_head_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..595608989f0b7da66e640a041289ae646cb36ae4 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/noisy_layer.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/noisy_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..5bc149d5de13beee0e77fcda069e321850507633 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/relative_multi_head_attention.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/relative_multi_head_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..f88486ff20516c19fcebdab3718fc829591215fb --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/skip_connection.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/skip_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee1751caf36e4a760da3c60c08fe279400dcb12 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/tf_action_dist.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/tf/tf_action_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..683d1939776d3f346ec5f52e97ca5b95e049cdb6 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abbe5ef604646d8de477335e18c0bc4c88363b2c --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef1e2e2f1ff876ceb717b8df3ce074339a765db3 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/attention_net.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/attention_net.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73c8f2619ababda33af14eb96261db6b52af3e24 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/attention_net.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/complex_input_net.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/complex_input_net.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c6138aa7cb549b7efe210f8059fae893e2a931f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/complex_input_net.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/fcnet.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/fcnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0fb504f603067b3d3548decd3be7fdeed67c901 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/fcnet.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/mingpt.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/mingpt.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dcbdd8be26ea454064bd363763f08e9c55b06ea Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/mingpt.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/misc.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/misc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78f0cb4bcbb7b083e4cbb76848018308ad5e169a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/misc.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/noop.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/noop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47a9799b14055cfb9fbf8d4071f1f688f5c39338 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/noop.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/recurrent_net.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/recurrent_net.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b2bf67948555f1ad8488f9715fec8da03a1853 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/recurrent_net.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_action_dist.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_action_dist.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..693e535ba4047a18ee308be02866472382b00196 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_action_dist.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_distributions.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d46ee961f64acf057f0c59e736a796a8b9f0726 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_distributions.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_modelv2.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_modelv2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9245d054f916b89555b23ab81bde7c63ea5abff1 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/torch_modelv2.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/visionnet.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/visionnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abb8c93fa6fcf7818efc23262f13072cc7b703e4 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/__pycache__/visionnet.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/attention_net.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/attention_net.py new file mode 100644 index 0000000000000000000000000000000000000000..2382a4da1381a7dad748155498578009b13170e0 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/complex_input_net.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/complex_input_net.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c81dba790c4f97f2c6ab5d2b765af0691005c8 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4f7ff649b61e42cd4bedd2b94e88851038bec5f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/convtranspose2d_stack.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/convtranspose2d_stack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac5dd3fe6cdc7512115441ebc0af71f603f7026c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/convtranspose2d_stack.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/gru_gate.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/gru_gate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c87b2a1c7214ebd50d3eefd513281d5ebabd914 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/gru_gate.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/multi_head_attention.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/multi_head_attention.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40a7db5a3ecf1bd890a76af4991e6af34fd50407 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/multi_head_attention.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/noisy_layer.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/noisy_layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98316df12d8255ca98011c6e49ebda8a93196870 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/noisy_layer.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/relative_multi_head_attention.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/relative_multi_head_attention.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6844e22c8c98448327024c5f059a9c81bffc9ab Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/relative_multi_head_attention.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/skip_connection.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/skip_connection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..551a3be7e38c960869131f5f5f651834238b8a2f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/__pycache__/skip_connection.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/noisy_layer.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/noisy_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9fe999cf79baeaa35af895311fbe8ecacdd302 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/relative_multi_head_attention.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/modules/relative_multi_head_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..aa19207e024d7d3f4a365e455974b4127b279606 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/recurrent_net.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/recurrent_net.py new file mode 100644 index 0000000000000000000000000000000000000000..01fbab223e29fe721914bab0e15860cb91f760d4 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/torch_action_dist.py b/vllm/lib/python3.10/site-packages/ray/rllib/models/torch/torch_action_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..91c69180070e9797d62f39939db03340979ee2d6 --- /dev/null +++ b/vllm/lib/python3.10/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)