diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1274c5cd248bfbd7d1384112e9a387e90c2225c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/clip_reward.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/clip_reward.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19b8581931f204660fe64f71e95e98f2d71638ac Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/clip_reward.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/env_sampling.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/env_sampling.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e426e9887f0449afd80b4a66913da920acf4d2b1 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/env_sampling.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/lambdas.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/lambdas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a3e666e193c4a8572090b04a88ff46dc01a1308 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/lambdas.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/mean_std_filter.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/mean_std_filter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b7fea4b5e6f8f2a178c0473419ca5a4149046df Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/mean_std_filter.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1709de214d49933353b4d81bee74f2c88392a28a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a83c90a93547a0826239d0e2af39814a4cdd6ad6 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/state_buffer.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/state_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..380413ffeebea6a15b242fc0e4342ff6fc87e3a0 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/state_buffer.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/synced_filter.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/synced_filter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e3a1415d353edde75e21d4f88631093e2d0ff1b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/synced_filter.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/view_requirement.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/view_requirement.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..035381ce69e88c8092d1fba70da452feeb0b01f0 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/view_requirement.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/clip_reward.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/clip_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..9d55e4aea24ab16691aa61116dd76ac7e9a71608 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/clip_reward.py @@ -0,0 +1,56 @@ +from typing import Any + +import numpy as np + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class ClipRewardAgentConnector(AgentConnector): + def __init__(self, ctx: ConnectorContext, sign=False, limit=None): + super().__init__(ctx) + assert ( + not sign or not limit + ), "should not enable both sign and limit reward clipping." + self.sign = sign + self.limit = limit + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) == dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + + if SampleBatch.REWARDS not in d: + # Nothing to clip. May happen for initial obs. + return ac_data + + if self.sign: + d[SampleBatch.REWARDS] = np.sign(d[SampleBatch.REWARDS]) + elif self.limit: + d[SampleBatch.REWARDS] = np.clip( + d[SampleBatch.REWARDS], + a_min=-self.limit, + a_max=self.limit, + ) + return ac_data + + def to_state(self): + return ClipRewardAgentConnector.__name__, { + "sign": self.sign, + "limit": self.limit, + } + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ClipRewardAgentConnector(ctx, **params) + + +register_connector(ClipRewardAgentConnector.__name__, ClipRewardAgentConnector) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/env_sampling.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/env_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ba6f0a4384caccd6647edde520cb7a84f0dc65 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/env_sampling.py @@ -0,0 +1,30 @@ +from typing import Any + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class EnvSamplingAgentConnector(AgentConnector): + def __init__(self, ctx: ConnectorContext, sign=False, limit=None): + super().__init__(ctx) + self.observation_space = ctx.observation_space + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + # EnvSamplingAgentConnector is a no-op connector. + return ac_data + + def to_state(self): + return EnvSamplingAgentConnector.__name__, {} + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return EnvSamplingAgentConnector(ctx, **params) + + +register_connector(EnvSamplingAgentConnector.__name__, EnvSamplingAgentConnector) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/lambdas.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/lambdas.py new file mode 100644 index 0000000000000000000000000000000000000000..05a714a0df982e36bce96c33ddfb6f6e9ce05188 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/lambdas.py @@ -0,0 +1,86 @@ +from typing import Any, Callable, Type + +import numpy as np +import tree # dm_tree + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import ( + AgentConnectorDataType, + AgentConnectorsOutput, +) +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +def register_lambda_agent_connector( + name: str, fn: Callable[[Any], Any] +) -> Type[AgentConnector]: + """A util to register any simple transforming function as an AgentConnector + + The only requirement is that fn should take a single data object and return + a single data object. + + Args: + name: Name of the resulting actor connector. + fn: The function that transforms env / agent data. + + Returns: + A new AgentConnector class that transforms data using fn. + """ + + class LambdaAgentConnector(AgentConnector): + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + return AgentConnectorDataType( + ac_data.env_id, ac_data.agent_id, fn(ac_data.data) + ) + + def to_state(self): + return name, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return LambdaAgentConnector(ctx) + + LambdaAgentConnector.__name__ = name + LambdaAgentConnector.__qualname__ = name + + register_connector(name, LambdaAgentConnector) + + return LambdaAgentConnector + + +@OldAPIStack +def flatten_data(data: AgentConnectorsOutput): + assert isinstance( + data, AgentConnectorsOutput + ), "Single agent data must be of type AgentConnectorsOutput" + + raw_dict = data.raw_dict + sample_batch = data.sample_batch + + flattened = {} + for k, v in sample_batch.items(): + if k in [SampleBatch.INFOS, SampleBatch.ACTIONS] or k.startswith("state_out_"): + # Do not flatten infos, actions, and state_out_ columns. + flattened[k] = v + continue + if v is None: + # Keep the same column shape. + flattened[k] = None + continue + flattened[k] = np.array(tree.flatten(v)) + flattened = SampleBatch(flattened, is_training=False) + + return AgentConnectorsOutput(raw_dict, flattened) + + +# Agent connector to build and return a flattened observation SampleBatch +# in addition to the original input dict. +FlattenDataAgentConnector = OldAPIStack( + register_lambda_agent_connector("FlattenDataAgentConnector", flatten_data) +) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/mean_std_filter.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/mean_std_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..64de99164267737eaa84d048611ea5b9efea654f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/mean_std_filter.py @@ -0,0 +1,187 @@ +from typing import Any, List +from gymnasium.spaces import Discrete, MultiDiscrete + +import numpy as np +import tree + +from ray.rllib.connectors.agent.synced_filter import SyncedFilterAgentConnector +from ray.rllib.connectors.connector import AgentConnector +from ray.rllib.connectors.connector import ( + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.filter import Filter +from ray.rllib.utils.filter import MeanStdFilter, ConcurrentMeanStdFilter +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.filter import RunningStat + + +@OldAPIStack +class MeanStdObservationFilterAgentConnector(SyncedFilterAgentConnector): + """A connector used to mean-std-filter observations. + + Incoming observations are filtered such that the output of this filter is on + average zero and has a standard deviation of 1. This filtering is applied + separately per element of the observation space. + """ + + def __init__( + self, + ctx: ConnectorContext, + demean: bool = True, + destd: bool = True, + clip: float = 10.0, + ): + SyncedFilterAgentConnector.__init__(self, ctx) + # We simply use the old MeanStdFilter until non-connector env_runner is fully + # deprecated to avoid duplicate code + + filter_shape = tree.map_structure( + lambda s: ( + None + if isinstance(s, (Discrete, MultiDiscrete)) # noqa + else np.array(s.shape) + ), + get_base_struct_from_space(ctx.observation_space), + ) + self.filter = MeanStdFilter(filter_shape, demean=demean, destd=destd, clip=clip) + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) == dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + if SampleBatch.OBS in d: + d[SampleBatch.OBS] = self.filter( + d[SampleBatch.OBS], update=self._is_training + ) + if SampleBatch.NEXT_OBS in d: + d[SampleBatch.NEXT_OBS] = self.filter( + d[SampleBatch.NEXT_OBS], update=self._is_training + ) + + return ac_data + + def to_state(self): + # Flattening is deterministic + flattened_rs = tree.flatten(self.filter.running_stats) + flattened_buffer = tree.flatten(self.filter.buffer) + return MeanStdObservationFilterAgentConnector.__name__, { + "shape": self.filter.shape, + "no_preprocessor": self.filter.no_preprocessor, + "demean": self.filter.demean, + "destd": self.filter.destd, + "clip": self.filter.clip, + "running_stats": [s.to_state() for s in flattened_rs], + "buffer": [s.to_state() for s in flattened_buffer], + } + + # demean, destd, clip, and a state dict + @staticmethod + def from_state( + ctx: ConnectorContext, + params: List[Any] = None, + demean: bool = True, + destd: bool = True, + clip: float = 10.0, + ): + connector = MeanStdObservationFilterAgentConnector(ctx, demean, destd, clip) + if params: + connector.filter.shape = params["shape"] + connector.filter.no_preprocessor = params["no_preprocessor"] + connector.filter.demean = params["demean"] + connector.filter.destd = params["destd"] + connector.filter.clip = params["clip"] + + # Unflattening is deterministic + running_stats = [RunningStat.from_state(s) for s in params["running_stats"]] + connector.filter.running_stats = tree.unflatten_as( + connector.filter.shape, running_stats + ) + + # Unflattening is deterministic + buffer = [RunningStat.from_state(s) for s in params["buffer"]] + connector.filter.buffer = tree.unflatten_as(connector.filter.shape, buffer) + + return connector + + def reset_state(self) -> None: + """Creates copy of current state and resets accumulated state""" + if not self._is_training: + raise ValueError( + "State of {} can only be changed when trainin.".format(self.__name__) + ) + self.filter.reset_buffer() + + def apply_changes(self, other: "Filter", *args, **kwargs) -> None: + """Updates self with state from other filter.""" + # inline this as soon as we deprecate ordinary filter with non-connector + # env_runner + if not self._is_training: + raise ValueError( + "Changes can only be applied to {} when trainin.".format(self.__name__) + ) + return self.filter.apply_changes(other, *args, **kwargs) + + def copy(self) -> "Filter": + """Creates a new object with same state as self. + + This is a legacy Filter method that we need to keep around for now + + Returns: + A copy of self. + """ + # inline this as soon as we deprecate ordinary filter with non-connector + # env_runner + return self.filter.copy() + + def sync(self, other: "AgentConnector") -> None: + """Copies all state from other filter to self.""" + # inline this as soon as we deprecate ordinary filter with non-connector + # env_runner + if not self._is_training: + raise ValueError( + "{} can only be synced when trainin.".format(self.__name__) + ) + return self.filter.sync(other.filter) + + +@OldAPIStack +class ConcurrentMeanStdObservationFilterAgentConnector( + MeanStdObservationFilterAgentConnector +): + """A concurrent version of the MeanStdObservationFilterAgentConnector. + + This version's filter has all operations wrapped by a threading.RLock. + It can therefore be safely used by multiple threads. + """ + + def __init__(self, ctx: ConnectorContext, demean=True, destd=True, clip=10.0): + SyncedFilterAgentConnector.__init__(self, ctx) + # We simply use the old MeanStdFilter until non-connector env_runner is fully + # deprecated to avoid duplicate code + + filter_shape = tree.map_structure( + lambda s: ( + None + if isinstance(s, (Discrete, MultiDiscrete)) # noqa + else np.array(s.shape) + ), + get_base_struct_from_space(ctx.observation_space), + ) + self.filter = ConcurrentMeanStdFilter( + filter_shape, demean=True, destd=True, clip=10.0 + ) + + +register_connector( + MeanStdObservationFilterAgentConnector.__name__, + MeanStdObservationFilterAgentConnector, +) +register_connector( + ConcurrentMeanStdObservationFilterAgentConnector.__name__, + ConcurrentMeanStdObservationFilterAgentConnector, +) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/obs_preproc.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/obs_preproc.py new file mode 100644 index 0000000000000000000000000000000000000000..41b23745c05ac84e27d563908df2f98fe0e3505f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/obs_preproc.py @@ -0,0 +1,69 @@ +from typing import Any + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.models.preprocessors import get_preprocessor, NoPreprocessor +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class ObsPreprocessorConnector(AgentConnector): + """A connector that wraps around existing RLlib observation preprocessors. + + This includes: + - OneHotPreprocessor for Discrete and Multi-Discrete spaces. + - GenericPixelPreprocessor and AtariRamPreprocessor for Atari spaces. + - TupleFlatteningPreprocessor and DictFlatteningPreprocessor for flattening + arbitrary nested input observations. + - RepeatedValuesPreprocessor for padding observations from RLlib Repeated + observation space. + """ + + def __init__(self, ctx: ConnectorContext): + super().__init__(ctx) + + if hasattr(ctx.observation_space, "original_space"): + # ctx.observation_space is the space this Policy deals with. + # We need to preprocess data from the original observation space here. + obs_space = ctx.observation_space.original_space + else: + obs_space = ctx.observation_space + + self._preprocessor = get_preprocessor(obs_space)( + obs_space, ctx.config.get("model", {}) + ) + + def is_identity(self): + """Returns whether this preprocessor connector is a no-op preprocessor.""" + return isinstance(self._preprocessor, NoPreprocessor) + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert type(d) == dict, ( + "Single agent data must be of type Dict[str, TensorStructType] but is of " + "type {}".format(type(d)) + ) + + if SampleBatch.OBS in d: + d[SampleBatch.OBS] = self._preprocessor.transform(d[SampleBatch.OBS]) + if SampleBatch.NEXT_OBS in d: + d[SampleBatch.NEXT_OBS] = self._preprocessor.transform( + d[SampleBatch.NEXT_OBS] + ) + + return ac_data + + def to_state(self): + return ObsPreprocessorConnector.__name__, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ObsPreprocessorConnector(ctx) + + +register_connector(ObsPreprocessorConnector.__name__, ObsPreprocessorConnector) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/pipeline.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..0113c1c45887a05ef480bbf3a34d6e60eb8edea7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/pipeline.py @@ -0,0 +1,72 @@ +import logging +from typing import Any, List +from collections import defaultdict + +from ray.rllib.connectors.connector import ( + AgentConnector, + Connector, + ConnectorContext, + ConnectorPipeline, +) +from ray.rllib.connectors.registry import get_connector, register_connector +from ray.rllib.utils.typing import ActionConnectorDataType, AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack +from ray.util.timer import _Timer + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class AgentConnectorPipeline(ConnectorPipeline, AgentConnector): + def __init__(self, ctx: ConnectorContext, connectors: List[Connector]): + super().__init__(ctx, connectors) + self.timers = defaultdict(_Timer) + + def reset(self, env_id: str): + for c in self.connectors: + c.reset(env_id) + + def on_policy_output(self, output: ActionConnectorDataType): + for c in self.connectors: + c.on_policy_output(output) + + def __call__( + self, acd_list: List[AgentConnectorDataType] + ) -> List[AgentConnectorDataType]: + ret = acd_list + for c in self.connectors: + timer = self.timers[str(c)] + with timer: + ret = c(ret) + return ret + + def to_state(self): + children = [] + for c in self.connectors: + state = c.to_state() + assert isinstance(state, tuple) and len(state) == 2, ( + "Serialized connector state must be in the format of " + f"Tuple[name: str, params: Any]. Instead we got {state}" + f"for connector {c.__name__}." + ) + children.append(state) + return AgentConnectorPipeline.__name__, children + + @staticmethod + def from_state(ctx: ConnectorContext, params: List[Any]): + assert ( + type(params) == list + ), "AgentConnectorPipeline takes a list of connector params." + connectors = [] + for state in params: + try: + name, subparams = state + connectors.append(get_connector(name, ctx, subparams)) + except Exception as e: + logger.error(f"Failed to de-serialize connector state: {state}") + raise e + return AgentConnectorPipeline(ctx, connectors) + + +register_connector(AgentConnectorPipeline.__name__, AgentConnectorPipeline) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/state_buffer.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/state_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..4516abd8bbe0ad47d6cc96baedb8909ff26b62fd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/state_buffer.py @@ -0,0 +1,120 @@ +from collections import defaultdict +import logging +import pickle +from typing import Any + +import numpy as np +from ray.rllib.utils.annotations import override +import tree # dm_tree + +from ray.rllib.connectors.connector import ( + AgentConnector, + Connector, + ConnectorContext, +) +from ray import cloudpickle +from ray.rllib.connectors.registry import register_connector +from ray.rllib.core.columns import Columns +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import ActionConnectorDataType, AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class StateBufferConnector(AgentConnector): + def __init__(self, ctx: ConnectorContext, states: Any = None): + super().__init__(ctx) + + self._initial_states = ctx.initial_states + self._action_space_struct = get_base_struct_from_space(ctx.action_space) + + self._states = defaultdict(lambda: defaultdict(lambda: (None, None, None))) + self._enable_new_api_stack = False + # TODO(jungong) : we would not need this if policies are never stashed + # during the rollout of a single episode. + if states: + try: + self._states = cloudpickle.loads(states) + except pickle.UnpicklingError: + # StateBufferConnector states are only needed for rare cases + # like stashing then restoring a policy during the rollout of + # a single episode. + # It is ok to ignore the error for most of the cases here. + logger.info( + "Can not restore StateBufferConnector states. This warning can " + "usually be ignore, unless it is from restoring a stashed policy." + ) + + @override(Connector) + def in_eval(self): + super().in_eval() + + def reset(self, env_id: str): + # States should not be carried over between episodes. + if env_id in self._states: + del self._states[env_id] + + def on_policy_output(self, ac_data: ActionConnectorDataType): + # Buffer latest output states for next input __call__. + self._states[ac_data.env_id][ac_data.agent_id] = ac_data.output + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) is dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + + env_id = ac_data.env_id + agent_id = ac_data.agent_id + assert ( + env_id is not None and agent_id is not None + ), f"StateBufferConnector requires env_id(f{env_id}) and agent_id(f{agent_id})" + + action, states, fetches = self._states[env_id][agent_id] + + if action is not None: + d[SampleBatch.ACTIONS] = action # Last action + else: + # Default zero action. + d[SampleBatch.ACTIONS] = tree.map_structure( + lambda s: np.zeros_like(s.sample(), s.dtype) + if hasattr(s, "dtype") + else np.zeros_like(s.sample()), + self._action_space_struct, + ) + + if states is None: + states = self._initial_states + if self._enable_new_api_stack: + if states: + d[Columns.STATE_OUT] = states + else: + for i, v in enumerate(states): + d["state_out_{}".format(i)] = v + + # Also add extra fetches if available. + if fetches: + d.update(fetches) + + return ac_data + + def to_state(self): + # Note(jungong) : it is ok to use cloudpickle here for stats because: + # 1. self._states may contain arbitary data objects, and will be hard + # to serialize otherwise. + # 2. seriazlized states are only useful if a policy is stashed and + # restored during the rollout of a single episode. So it is ok to + # use cloudpickle for such non-persistent data bits. + states = cloudpickle.dumps(self._states) + return StateBufferConnector.__name__, states + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return StateBufferConnector(ctx, params) + + +register_connector(StateBufferConnector.__name__, StateBufferConnector) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/synced_filter.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/synced_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..51c625d9aceec9401599ef87b42cf522704c5ea3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/synced_filter.py @@ -0,0 +1,52 @@ +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.filter import Filter + + +@OldAPIStack +class SyncedFilterAgentConnector(AgentConnector): + """An agent connector that filters with synchronized parameters.""" + + def __init__(self, ctx: ConnectorContext, *args, **kwargs): + super().__init__(ctx) + if args or kwargs: + raise ValueError( + "SyncedFilterAgentConnector does not take any additional arguments, " + "but got args=`{}` and kwargs={}.".format(args, kwargs) + ) + + def apply_changes(self, other: "Filter", *args, **kwargs) -> None: + """Updates self with state from other filter.""" + # TODO: (artur) inline this as soon as we deprecate ordinary filter with + # non-connecto env_runner + return self.filter.apply_changes(other, *args, **kwargs) + + def copy(self) -> "Filter": + """Creates a new object with same state as self. + + This is a legacy Filter method that we need to keep around for now + + Returns: + A copy of self. + """ + # inline this as soon as we deprecate ordinary filter with non-connector + # env_runner + return self.filter.copy() + + def sync(self, other: "AgentConnector") -> None: + """Copies all state from other filter to self.""" + # TODO: (artur) inline this as soon as we deprecate ordinary filter with + # non-connector env_runner + return self.filter.sync(other.filter) + + def reset_state(self) -> None: + """Creates copy of current state and resets accumulated state""" + raise NotImplementedError + + def as_serializable(self) -> "Filter": + # TODO: (artur) inline this as soon as we deprecate ordinary filter with + # non-connector env_runner + return self.filter.as_serializable() diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/view_requirement.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/view_requirement.py new file mode 100644 index 0000000000000000000000000000000000000000..7f035bb97a92c7856ecc11e6dc7eac169a823a51 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/view_requirement.py @@ -0,0 +1,135 @@ +from collections import defaultdict +from typing import Any + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import ( + AgentConnectorDataType, + AgentConnectorsOutput, +) +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.evaluation.collectors.agent_collector import AgentCollector + + +@OldAPIStack +class ViewRequirementAgentConnector(AgentConnector): + """This connector does 2 things: + 1. It filters data columns based on view_requirements for training and inference. + 2. It buffers the right amount of history for computing the sample batch for + action computation. + The output of this connector is AgentConnectorsOut, which basically is + a tuple of 2 things: + { + "raw_dict": {"obs": ...} + "sample_batch": SampleBatch + } + raw_dict, which contains raw data for the latest time slice, + can be used to construct a complete episode by Sampler for training purpose. + The "for_action" SampleBatch can be used to directly call the policy. + """ + + def __init__(self, ctx: ConnectorContext): + super().__init__(ctx) + + self._view_requirements = ctx.view_requirements + _enable_new_api_stack = False + + # a dict of env_id to a dict of agent_id to a list of agent_collector objects + self.agent_collectors = defaultdict( + lambda: defaultdict( + lambda: AgentCollector( + self._view_requirements, + max_seq_len=ctx.config["model"]["max_seq_len"], + intial_states=ctx.initial_states, + disable_action_flattening=ctx.config.get( + "_disable_action_flattening", False + ), + is_policy_recurrent=ctx.is_policy_recurrent, + # Note(jungong): We only leverage AgentCollector for building sample + # batches for computing actions. + # So regardless of whether this ViewRequirement connector is in + # training or inference mode, we should tell these AgentCollectors + # to behave in inference mode, so they don't accumulate episode data + # that is not useful for inference. + is_training=False, + _enable_new_api_stack=_enable_new_api_stack, + ) + ) + ) + + def reset(self, env_id: str): + if env_id in self.agent_collectors: + del self.agent_collectors[env_id] + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) is dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + + env_id = ac_data.env_id + agent_id = ac_data.agent_id + # TODO: we don't keep episode_id around so use env_id as episode_id ? + episode_id = env_id if SampleBatch.EPS_ID not in d else d[SampleBatch.EPS_ID] + + assert env_id is not None and agent_id is not None, ( + f"ViewRequirementAgentConnector requires env_id({env_id}) " + "and agent_id({agent_id})" + ) + + assert ( + self._view_requirements + ), "ViewRequirements required by ViewRequirementAgentConnector" + + # Note(jungong) : we need to keep the entire input dict here. + # A column may be used by postprocessing (GAE) even if its + # view_requirement.used_for_training is False. + training_dict = d + + agent_collector = self.agent_collectors[env_id][agent_id] + + if SampleBatch.NEXT_OBS not in d: + raise ValueError(f"connector data {d} should contain next_obs.") + # TODO(avnishn; kourosh) Unsure how agent_index is necessary downstream + # since there is no mapping from agent_index to agent_id that exists. + # need to remove this from the SampleBatch later. + # fall back to using dummy index if no index is available + if SampleBatch.AGENT_INDEX in d: + agent_index = d[SampleBatch.AGENT_INDEX] + else: + try: + agent_index = float(agent_id) + except ValueError: + agent_index = -1 + if agent_collector.is_empty(): + agent_collector.add_init_obs( + episode_id=episode_id, + agent_index=agent_index, + env_id=env_id, + init_obs=d[SampleBatch.NEXT_OBS], + init_infos=d.get(SampleBatch.INFOS), + ) + else: + agent_collector.add_action_reward_next_obs(d) + sample_batch = agent_collector.build_for_inference() + + return_data = AgentConnectorDataType( + env_id, agent_id, AgentConnectorsOutput(training_dict, sample_batch) + ) + return return_data + + def to_state(self): + return ViewRequirementAgentConnector.__name__, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ViewRequirementAgentConnector(ctx) + + +register_connector( + ViewRequirementAgentConnector.__name__, ViewRequirementAgentConnector +) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector.py new file mode 100644 index 0000000000000000000000000000000000000000..80c5003085b17bd586e22e5d39e4dbec34a50c79 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector.py @@ -0,0 +1,478 @@ +"""This file defines base types and common structures for RLlib connectors. +""" + +import abc +import logging +from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union + +import gymnasium as gym + +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.typing import ( + ActionConnectorDataType, + AgentConnectorDataType, + AlgorithmConfigDict, + TensorType, +) +from ray.rllib.utils.annotations import OldAPIStack + +if TYPE_CHECKING: + from ray.rllib.policy.policy import Policy + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class ConnectorContext: + """Data bits that may be needed for running connectors. + + Note(jungong) : we need to be really careful with the data fields here. + E.g., everything needs to be serializable, in case we need to fetch them + in a remote setting. + """ + + # TODO(jungong) : figure out how to fetch these in a remote setting. + # Probably from a policy server when initializing a policy client. + + def __init__( + self, + config: AlgorithmConfigDict = None, + initial_states: List[TensorType] = None, + observation_space: gym.Space = None, + action_space: gym.Space = None, + view_requirements: Dict[str, ViewRequirement] = None, + is_policy_recurrent: bool = False, + ): + """Construct a ConnectorContext instance. + + Args: + initial_states: States that are used for constructing + the initial input dict for RNN models. [] if a model is not recurrent. + action_space_struct: a policy's action space, in python + data format. E.g., python dict instead of DictSpace, python tuple + instead of TupleSpace. + """ + self.config = config or {} + self.initial_states = initial_states or [] + self.observation_space = observation_space + self.action_space = action_space + self.view_requirements = view_requirements + self.is_policy_recurrent = is_policy_recurrent + + @staticmethod + def from_policy(policy: "Policy") -> "ConnectorContext": + """Build ConnectorContext from a given policy. + + Args: + policy: Policy + + Returns: + A ConnectorContext instance. + """ + return ConnectorContext( + config=policy.config, + initial_states=policy.get_initial_state(), + observation_space=policy.observation_space, + action_space=policy.action_space, + view_requirements=policy.view_requirements, + is_policy_recurrent=policy.is_recurrent(), + ) + + +@OldAPIStack +class Connector(abc.ABC): + """Connector base class. + + A connector is a step of transformation, of either envrionment data before they + get to a policy, or policy output before it is sent back to the environment. + + Connectors may be training-aware, for example, behave slightly differently + during training and inference. + + All connectors are required to be serializable and implement to_state(). + """ + + def __init__(self, ctx: ConnectorContext): + # Default is training mode. + self._is_training = True + + def in_training(self): + self._is_training = True + + def in_eval(self): + self._is_training = False + + def __str__(self, indentation: int = 0): + return " " * indentation + self.__class__.__name__ + + def to_state(self) -> Tuple[str, Any]: + """Serialize a connector into a JSON serializable Tuple. + + to_state is required, so that all Connectors are serializable. + + Returns: + A tuple of connector's name and its serialized states. + String should match the name used to register the connector, + while state can be any single data structure that contains the + serialized state of the connector. If a connector is stateless, + state can simply be None. + """ + # Must implement by each connector. + return NotImplementedError + + @staticmethod + def from_state(self, ctx: ConnectorContext, params: Any) -> "Connector": + """De-serialize a JSON params back into a Connector. + + from_state is required, so that all Connectors are serializable. + + Args: + ctx: Context for constructing this connector. + params: Serialized states of the connector to be recovered. + + Returns: + De-serialized connector. + """ + # Must implement by each connector. + return NotImplementedError + + +@OldAPIStack +class AgentConnector(Connector): + """Connector connecting user environments to RLlib policies. + + An agent connector transforms a list of agent data in AgentConnectorDataType + format into a new list in the same AgentConnectorDataTypes format. + The input API is designed so agent connectors can have access to all the + agents assigned to a particular policy. + + AgentConnectorDataTypes can be used to specify arbitrary type of env data, + + Example: + + Represent a list of agent data from one env step() call. + + .. testcode:: + + import numpy as np + ac = AgentConnectorDataType( + env_id="env_1", + agent_id=None, + data={ + "agent_1": np.array([1, 2, 3]), + "agent_2": np.array([4, 5, 6]), + } + ) + + Or a single agent data ready to be preprocessed. + + .. testcode:: + + ac = AgentConnectorDataType( + env_id="env_1", + agent_id="agent_1", + data=np.array([1, 2, 3]), + ) + + We can also adapt a simple stateless function into an agent connector by + using register_lambda_agent_connector: + + .. testcode:: + + import numpy as np + from ray.rllib.connectors.agent.lambdas import ( + register_lambda_agent_connector + ) + TimesTwoAgentConnector = register_lambda_agent_connector( + "TimesTwoAgentConnector", lambda data: data * 2 + ) + + # More complicated agent connectors can be implemented by extending this + # AgentConnector class: + + class FrameSkippingAgentConnector(AgentConnector): + def __init__(self, n): + self._n = n + self._frame_count = default_dict(str, default_dict(str, int)) + + def reset(self, env_id: str): + del self._frame_count[env_id] + + def __call__( + self, ac_data: List[AgentConnectorDataType] + ) -> List[AgentConnectorDataType]: + ret = [] + for d in ac_data: + assert d.env_id and d.agent_id, "Skipping works per agent!" + + count = self._frame_count[ac_data.env_id][ac_data.agent_id] + self._frame_count[ac_data.env_id][ac_data.agent_id] = ( + count + 1 + ) + + if count % self._n == 0: + ret.append(d) + return ret + + As shown, an agent connector may choose to emit an empty list to stop input + observations from being further prosessed. + """ + + def reset(self, env_id: str): + """Reset connector state for a specific environment. + + For example, at the end of an episode. + + Args: + env_id: required. ID of a user environment. Required. + """ + pass + + def on_policy_output(self, output: ActionConnectorDataType): + """Callback on agent connector of policy output. + + This is useful for certain connectors, for example RNN state buffering, + where the agent connect needs to be aware of the output of a policy + forward pass. + + Args: + ctx: Context for running this connector call. + output: Env and agent IDs, plus data output from policy forward pass. + """ + pass + + def __call__( + self, acd_list: List[AgentConnectorDataType] + ) -> List[AgentConnectorDataType]: + """Transform a list of data items from env before they reach policy. + + Args: + ac_data: List of env and agent IDs, plus arbitrary data items from + an environment or upstream agent connectors. + + Returns: + A list of transformed data items in AgentConnectorDataType format. + The shape of a returned list does not have to match that of the input list. + An AgentConnector may choose to derive multiple outputs for a single piece + of input data, for example multi-agent obs -> multiple single agent obs. + Agent connectors may also choose to skip emitting certain inputs, + useful for connectors such as frame skipping. + """ + assert isinstance( + acd_list, (list, tuple) + ), "Input to agent connectors are list of AgentConnectorDataType." + # Default implementation. Simply call transform on each agent connector data. + return [self.transform(d) for d in acd_list] + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + """Transform a single agent connector data item. + + Args: + data: Env and agent IDs, plus arbitrary data item from a single agent + of an environment. + + Returns: + A transformed piece of agent connector data. + """ + raise NotImplementedError + + +@OldAPIStack +class ActionConnector(Connector): + """Action connector connects policy outputs including actions, + to user environments. + + An action connector transforms a single piece of policy output in + ActionConnectorDataType format, which is basically PolicyOutputType plus env and + agent IDs. + + Any functions that operate directly on PolicyOutputType can be easily adapted + into an ActionConnector by using register_lambda_action_connector. + + Example: + + .. testcode:: + + from ray.rllib.connectors.action.lambdas import ( + register_lambda_action_connector + ) + ZeroActionConnector = register_lambda_action_connector( + "ZeroActionsConnector", + lambda actions, states, fetches: ( + np.zeros_like(actions), states, fetches + ) + ) + + More complicated action connectors can also be implemented by sub-classing + this ActionConnector class. + """ + + def __call__(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + """Transform policy output before they are sent to a user environment. + + Args: + ac_data: Env and agent IDs, plus policy output. + + Returns: + The processed action connector data. + """ + return self.transform(ac_data) + + def transform(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + """Implementation of the actual transform. + + Users should override transform instead of __call__ directly. + + Args: + ac_data: Env and agent IDs, plus policy output. + + Returns: + The processed action connector data. + """ + raise NotImplementedError + + +@OldAPIStack +class ConnectorPipeline(abc.ABC): + """Utility class for quick manipulation of a connector pipeline.""" + + def __init__(self, ctx: ConnectorContext, connectors: List[Connector]): + self.connectors = connectors + + def in_training(self): + for c in self.connectors: + c.in_training() + + def in_eval(self): + for c in self.connectors: + c.in_eval() + + def remove(self, name: str): + """Remove a connector by + + Args: + name: name of the connector to be removed. + """ + idx = -1 + for i, c in enumerate(self.connectors): + if c.__class__.__name__ == name: + idx = i + break + if idx >= 0: + del self.connectors[idx] + logger.info(f"Removed connector {name} from {self.__class__.__name__}.") + else: + logger.warning(f"Trying to remove a non-existent connector {name}.") + + def insert_before(self, name: str, connector: Connector): + """Insert a new connector before connector + + Args: + name: name of the connector before which a new connector + will get inserted. + connector: a new connector to be inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if c.__class__.__name__ == name: + break + if idx < 0: + raise ValueError(f"Can not find connector {name}") + self.connectors.insert(idx, connector) + + logger.info( + f"Inserted {connector.__class__.__name__} before {name} " + f"to {self.__class__.__name__}." + ) + + def insert_after(self, name: str, connector: Connector): + """Insert a new connector after connector + + Args: + name: name of the connector after which a new connector + will get inserted. + connector: a new connector to be inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if c.__class__.__name__ == name: + break + if idx < 0: + raise ValueError(f"Can not find connector {name}") + self.connectors.insert(idx + 1, connector) + + logger.info( + f"Inserted {connector.__class__.__name__} after {name} " + f"to {self.__class__.__name__}." + ) + + def prepend(self, connector: Connector): + """Append a new connector at the beginning of a connector pipeline. + + Args: + connector: a new connector to be appended. + """ + self.connectors.insert(0, connector) + + logger.info( + f"Added {connector.__class__.__name__} to the beginning of " + f"{self.__class__.__name__}." + ) + + def append(self, connector: Connector): + """Append a new connector at the end of a connector pipeline. + + Args: + connector: a new connector to be appended. + """ + self.connectors.append(connector) + + logger.info( + f"Added {connector.__class__.__name__} to the end of " + f"{self.__class__.__name__}." + ) + + def __str__(self, indentation: int = 0): + return "\n".join( + [" " * indentation + self.__class__.__name__] + + [c.__str__(indentation + 4) for c in self.connectors] + ) + + def __getitem__(self, key: Union[str, int, type]): + """Returns a list of connectors that fit 'key'. + + If key is a number n, we return a list with the nth element of this pipeline. + If key is a Connector class or a string matching the class name of a + Connector class, we return a list of all connectors in this pipeline matching + the specified class. + + Args: + key: The key to index by + + Returns: The Connector at index `key`. + """ + # In case key is a class + if not isinstance(key, str): + if isinstance(key, slice): + raise NotImplementedError( + "Slicing of ConnectorPipeline is currently not supported." + ) + elif isinstance(key, int): + return [self.connectors[key]] + elif isinstance(key, type): + results = [] + for c in self.connectors: + if issubclass(c.__class__, key): + results.append(c) + return results + else: + raise NotImplementedError( + "Indexing by {} is currently not supported.".format(type(key)) + ) + + results = [] + for c in self.connectors: + if c.__class__.__name__ == key: + results.append(c) + + return results diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_pipeline_v2.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_pipeline_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..583825fb1d677f7f06c27ce4470c01fc53837e7d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_pipeline_v2.py @@ -0,0 +1,381 @@ +from collections import defaultdict +import logging +from typing import Any, Collection, Dict, List, Optional, Tuple, Type, Union + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.typing import EpisodeType, StateDict +from ray.util.annotations import PublicAPI +from ray.util.timer import _Timer + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="alpha") +class ConnectorPipelineV2(ConnectorV2): + """Utility class for quick manipulation of a connector pipeline.""" + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + self._fix_spaces(input_observation_space, input_action_space) + return self.observation_space + + @override(ConnectorV2) + def recompute_output_action_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + self._fix_spaces(input_observation_space, input_action_space) + return self.action_space + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + connectors: Optional[List[ConnectorV2]] = None, + **kwargs, + ): + """Initializes a ConnectorPipelineV2 instance. + + Args: + input_observation_space: The (optional) input observation space for this + connector piece. This is the space coming from a previous connector + piece in the (env-to-module or learner) pipeline or is directly + defined within the gym.Env. + input_action_space: The (optional) input action space for this connector + piece. This is the space coming from a previous connector piece in the + (module-to-env) pipeline or is directly defined within the gym.Env. + connectors: A list of individual ConnectorV2 pieces to be added to this + pipeline during construction. Note that you can always add (or remove) + more ConnectorV2 pieces later on the fly. + """ + self.connectors = [] + + for conn in connectors: + # If we have a `ConnectorV2` instance just append. + if isinstance(conn, ConnectorV2): + self.connectors.append(conn) + # If, we have a class with `args` and `kwargs`, build the instance. + # Note that this way of constructing a pipeline should only be + # used internally when restoring the pipeline state from a + # checkpoint. + elif isinstance(conn, tuple) and len(conn) == 3: + self.connectors.append(conn[0](*conn[1], **conn[2])) + + super().__init__(input_observation_space, input_action_space, **kwargs) + + self.timers = defaultdict(_Timer) + + def __len__(self): + return len(self.connectors) + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + """In a pipeline, we simply call each of our connector pieces after each other. + + Each connector piece receives as input the output of the previous connector + piece in the pipeline. + """ + shared_data = shared_data if shared_data is not None else {} + # Loop through connector pieces and call each one with the output of the + # previous one. Thereby, time each connector piece's call. + for connector in self.connectors: + timer = self.timers[str(connector)] + with timer: + batch = connector( + rl_module=rl_module, + batch=batch, + episodes=episodes, + explore=explore, + shared_data=shared_data, + # Deprecated arg. + data=batch, + **kwargs, + ) + if not isinstance(batch, dict): + raise ValueError( + f"`data` returned by ConnectorV2 {connector} must be a dict! " + f"You returned {batch}. Check your (custom) connectors' " + f"`__call__()` method's return value and make sure you return " + f"the `data` arg passed in (either altered or unchanged)." + ) + return batch + + def remove(self, name_or_class: Union[str, Type]): + """Remove a single connector piece in this pipeline by its name or class. + + Args: + name: The name of the connector piece to be removed from the pipeline. + """ + idx = -1 + for i, c in enumerate(self.connectors): + if c.__class__.__name__ == name_or_class: + idx = i + break + if idx >= 0: + del self.connectors[idx] + self._fix_spaces(self.input_observation_space, self.input_action_space) + logger.info( + f"Removed connector {name_or_class} from {self.__class__.__name__}." + ) + else: + logger.warning( + f"Trying to remove a non-existent connector {name_or_class}." + ) + + def insert_before( + self, + name_or_class: Union[str, type], + connector: ConnectorV2, + ) -> ConnectorV2: + """Insert a new connector piece before an existing piece (by name or class). + + Args: + name_or_class: Name or class of the connector piece before which `connector` + will get inserted. + connector: The new connector piece to be inserted. + + Returns: + The ConnectorV2 before which `connector` has been inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if ( + isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class + ) or (isinstance(name_or_class, type) and c.__class__ is name_or_class): + break + if idx < 0: + raise ValueError( + f"Can not find connector with name or type '{name_or_class}'!" + ) + next_connector = self.connectors[idx] + + self.connectors.insert(idx, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Inserted {connector.__class__.__name__} before {name_or_class} " + f"to {self.__class__.__name__}." + ) + return next_connector + + def insert_after( + self, + name_or_class: Union[str, Type], + connector: ConnectorV2, + ) -> ConnectorV2: + """Insert a new connector piece after an existing piece (by name or class). + + Args: + name_or_class: Name or class of the connector piece after which `connector` + will get inserted. + connector: The new connector piece to be inserted. + + Returns: + The ConnectorV2 after which `connector` has been inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if ( + isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class + ) or (isinstance(name_or_class, type) and c.__class__ is name_or_class): + break + if idx < 0: + raise ValueError( + f"Can not find connector with name or type '{name_or_class}'!" + ) + prev_connector = self.connectors[idx] + + self.connectors.insert(idx + 1, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Inserted {connector.__class__.__name__} after {name_or_class} " + f"to {self.__class__.__name__}." + ) + + return prev_connector + + def prepend(self, connector: ConnectorV2) -> None: + """Prepend a new connector at the beginning of a connector pipeline. + + Args: + connector: The new connector piece to be prepended to this pipeline. + """ + self.connectors.insert(0, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Added {connector.__class__.__name__} to the beginning of " + f"{self.__class__.__name__}." + ) + + def append(self, connector: ConnectorV2) -> None: + """Append a new connector at the end of a connector pipeline. + + Args: + connector: The new connector piece to be appended to this pipeline. + """ + self.connectors.append(connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Added {connector.__class__.__name__} to the end of " + f"{self.__class__.__name__}." + ) + + @override(ConnectorV2) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + state = {} + for conn in self.connectors: + conn_name = type(conn).__name__ + if self._check_component(conn_name, components, not_components): + state[conn_name] = conn.get_state( + components=self._get_subcomponents(conn_name, components), + not_components=self._get_subcomponents(conn_name, not_components), + **kwargs, + ) + return state + + @override(ConnectorV2) + def set_state(self, state: Dict[str, Any]) -> None: + for conn in self.connectors: + conn_name = type(conn).__name__ + if conn_name in state: + conn.set_state(state[conn_name]) + + @override(Checkpointable) + def get_checkpointable_components(self) -> List[Tuple[str, "Checkpointable"]]: + return [(type(conn).__name__, conn) for conn in self.connectors] + + # Note that we don't have to override Checkpointable.get_ctor_args_and_kwargs and + # don't have to return the `connectors` c'tor kwarg from there. This is b/c all + # connector pieces in this pipeline are themselves Checkpointable components, + # so they will be properly written into this pipeline's checkpoint. + @override(Checkpointable) + def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]: + return ( + (self.input_observation_space, self.input_action_space), # *args + { + "connectors": [ + (type(conn), *conn.get_ctor_args_and_kwargs()) + for conn in self.connectors + ] + }, + ) + + @override(ConnectorV2) + def reset_state(self) -> None: + for conn in self.connectors: + conn.reset_state() + + @override(ConnectorV2) + def merge_states(self, states: List[Dict[str, Any]]) -> Dict[str, Any]: + merged_states = {} + if not states: + return merged_states + for i, (key, item) in enumerate(states[0].items()): + state_list = [state[key] for state in states] + conn = self.connectors[i] + merged_states[key] = conn.merge_states(state_list) + return merged_states + + def __repr__(self, indentation: int = 0): + return "\n".join( + [" " * indentation + self.__class__.__name__] + + [c.__str__(indentation + 4) for c in self.connectors] + ) + + def __getitem__( + self, + key: Union[str, int, Type], + ) -> Union[ConnectorV2, List[ConnectorV2]]: + """Returns a single ConnectorV2 or list of ConnectorV2s that fit `key`. + + If key is an int, we return a single ConnectorV2 at that index in this pipeline. + If key is a ConnectorV2 type or a string matching the class name of a + ConnectorV2 in this pipeline, we return a list of all ConnectorV2s in this + pipeline matching the specified class. + + Args: + key: The key to find or to index by. + + Returns: + A single ConnectorV2 or a list of ConnectorV2s matching `key`. + """ + # Key is an int -> Index into pipeline and return. + if isinstance(key, int): + return self.connectors[key] + # Key is a class. + elif isinstance(key, type): + results = [] + for c in self.connectors: + if issubclass(c.__class__, key): + results.append(c) + return results + # Key is a string -> Find connector(s) by name. + elif isinstance(key, str): + results = [] + for c in self.connectors: + if c.name == key: + results.append(c) + return results + # Slicing not supported (yet). + elif isinstance(key, slice): + raise NotImplementedError( + "Slicing of ConnectorPipelineV2 is currently not supported!" + ) + else: + raise NotImplementedError( + f"Indexing ConnectorPipelineV2 by {type(key)} is currently not " + f"supported!" + ) + + @property + def observation_space(self): + if len(self) > 0: + return self.connectors[-1].observation_space + return self._observation_space + + @property + def action_space(self): + if len(self) > 0: + return self.connectors[-1].action_space + return self._action_space + + def _fix_spaces(self, input_observation_space, input_action_space): + if len(self) > 0: + # Fix each connector's input_observation- and input_action space in + # the pipeline. + obs_space = input_observation_space + act_space = input_action_space + for con in self.connectors: + con.input_action_space = act_space + con.input_observation_space = obs_space + obs_space = con.observation_space + act_space = con.action_space diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_v2.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..2ecae3f00421bb85639d8b494c21a006f6064b46 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_v2.py @@ -0,0 +1,1013 @@ +import abc +from collections import defaultdict +import inspect +from typing import ( + Any, + Callable, + Collection, + Dict, + Iterator, + List, + Optional, + Tuple, + Union, +) + +import gymnasium as gym +import tree + +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import override, OverrideToImplementCustomLogic +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.spaces.space_utils import BatchedNdArray +from ray.rllib.utils.typing import AgentID, EpisodeType, ModuleID, StateDict +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ConnectorV2(Checkpointable, abc.ABC): + """Base class defining the API for an individual "connector piece". + + A ConnectorV2 ("connector piece") is usually part of a whole series of connector + pieces within a so-called connector pipeline, which in itself also abides to this + very API. + For example, you might have a connector pipeline consisting of two connector pieces, + A and B, both instances of subclasses of ConnectorV2 and each one performing a + particular transformation on their input data. The resulting connector pipeline + (A->B) itself also abides to this very ConnectorV2 API and could thus be part of yet + another, higher-level connector pipeline, e.g. (A->B)->C->D. + + Any ConnectorV2 instance (individual pieces or several connector pieces in a + pipeline) is a callable and users should override the `__call__()` method. + When called, they take the outputs of a previous connector piece (or an empty dict + if there are no previous pieces) and all the data collected thus far in the + ongoing episode(s) (only applies to connectors used in EnvRunners) or retrieved + from a replay buffer or from an environment sampling step (only applies to + connectors used in Learner pipelines). From this input data, a ConnectorV2 then + performs a transformation step. + + There are 3 types of pipelines any ConnectorV2 piece can belong to: + 1) EnvToModulePipeline: The connector transforms environment data before it gets to + the RLModule. This type of pipeline is used by an EnvRunner for transforming + env output data into RLModule readable data (for the next RLModule forward pass). + For example, such a pipeline would include observation postprocessors, -filters, + or any RNN preparation code related to time-sequences and zero-padding. + 2) ModuleToEnvPipeline: This type of pipeline is used by an + EnvRunner to transform RLModule output data to env readable actions (for the next + `env.step()` call). For example, in case the RLModule only outputs action + distribution parameters (but not actual actions), the ModuleToEnvPipeline would + take care of sampling the actions to be sent back to the end from the + resulting distribution (made deterministic if exploration is off). + 3) LearnerConnectorPipeline: This connector pipeline type transforms data coming + from an `EnvRunner.sample()` call or a replay buffer and will then be sent into the + RLModule's `forward_train()` method in order to compute loss function inputs. + This type of pipeline is used by a Learner worker to transform raw training data + (a batch or a list of episodes) to RLModule readable training data (for the next + RLModule `forward_train()` call). + + Some connectors might be stateful, for example for keeping track of observation + filtering stats (mean and stddev values). Any Algorithm, which uses connectors is + responsible for frequently synchronizing the states of all connectors and connector + pipelines between the EnvRunners (owning the env-to-module and module-to-env + pipelines) and the Learners (owning the Learner pipelines). + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + **kwargs, + ): + """Initializes a ConnectorV2 instance. + + Args: + input_observation_space: The (optional) input observation space for this + connector piece. This is the space coming from a previous connector + piece in the (env-to-module or learner) pipeline or is directly + defined within the gym.Env. + input_action_space: The (optional) input action space for this connector + piece. This is the space coming from a previous connector piece in the + (module-to-env) pipeline or is directly defined within the gym.Env. + **kwargs: Forward API-compatibility kwargs. + """ + self._observation_space = None + self._action_space = None + self._input_observation_space = None + self._input_action_space = None + + self.input_action_space = input_action_space + self.input_observation_space = input_observation_space + + # Store child's constructor args and kwargs for the default + # `get_ctor_args_and_kwargs` implementation (to be able to restore from a + # checkpoint). + if self.__class__.__dict__.get("__init__") is not None: + caller_frame = inspect.stack()[1].frame + arg_info = inspect.getargvalues(caller_frame) + # Separate positional arguments and keyword arguments. + caller_locals = ( + arg_info.locals + ) # Dictionary of all local variables in the caller + self._ctor_kwargs = { + arg: caller_locals[arg] for arg in arg_info.args if arg != "self" + } + else: + self._ctor_kwargs = { + "input_observation_space": self.input_observation_space, + "input_action_space": self.input_action_space, + } + + @OverrideToImplementCustomLogic + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + """Re-computes a new (output) observation space based on the input spaces. + + This method should be overridden by users to make sure a ConnectorPipelineV2 + knows how the input spaces through its individual ConnectorV2 pieces are being + transformed. + + .. testcode:: + + from gymnasium.spaces import Box, Discrete + import numpy as np + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + from ray.rllib.utils.numpy import one_hot + from ray.rllib.utils.test_utils import check + + class OneHotConnector(ConnectorV2): + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ): + return Box(0.0, 1.0, (input_observation_space.n,), np.float32) + + def __call__( + self, + *, + rl_module, + batch, + episodes, + explore=None, + shared_data=None, + **kwargs, + ): + assert "obs" in batch + batch["obs"] = one_hot(batch["obs"]) + return batch + + connector = OneHotConnector(input_observation_space=Discrete(2)) + batch = {"obs": np.array([1, 0, 0], np.int32)} + output = connector(rl_module=None, batch=batch, episodes=None) + + check(output, {"obs": np.array([[0.0, 1.0], [1.0, 0.0], [1.0, 0.0]])}) + + If this ConnectorV2 does not change the observation space in any way, leave + this parent method implementation untouched. + + Args: + input_observation_space: The input observation space (either coming from the + environment if `self` is the first connector piece in the pipeline or + from the previous connector piece in the pipeline). + input_action_space: The input action space (either coming from the + environment if `self is the first connector piece in the pipeline or + from the previous connector piece in the pipeline). + + Returns: + The new observation space (after data has passed through this ConnectorV2 + piece). + """ + return self.input_observation_space + + @OverrideToImplementCustomLogic + def recompute_output_action_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + """Re-computes a new (output) action space based on the input space. + + This method should be overridden by users to make sure a ConnectorPipelineV2 + knows how the input spaces through its individual ConnectorV2 pieces are being + transformed. + + If this ConnectorV2 does not change the action space in any way, leave + this parent method implementation untouched. + + Args: + input_observation_space: The input observation space (either coming from the + environment if `self` is the first connector piece in the pipeline or + from the previous connector piece in the pipeline). + input_action_space: The input action space (either coming from the + environment if `self is the first connector piece in the pipeline or + from the previous connector piece in the pipeline). + + Returns: + The new action space (after data has passed through this ConenctorV2 + piece). + """ + return self.input_action_space + + @abc.abstractmethod + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + """Method for transforming an input `batch` into an output `batch`. + + Args: + rl_module: The RLModule object that the connector connects to or from. + batch: The input data to be transformed by this connector. Transformations + might either be done in-place or a new structure may be returned. + Note that the information in `batch` will eventually either become the + forward batch for the RLModule (env-to-module and learner connectors) + or the input to the `env.step()` call (module-to-env connectors). Note + that in the first case (`batch` is a forward batch for RLModule), the + information in `batch` will be discarded after that RLModule forward + pass. Any transformation of information (e.g. observation preprocessing) + that you have only done inside `batch` will be lost, unless you have + written it back into the corresponding `episodes` during the connector + pass. + episodes: The list of SingleAgentEpisode or MultiAgentEpisode objects, + each corresponding to one slot in the vector env. Note that episodes + can be read from (e.g. to place information into `batch`), but also + written to. You should only write back (changed, transformed) + information into the episodes, if you want these changes to be + "permanent". For example if you sample from an environment, pick up + observations from the episodes and place them into `batch`, then + transform these observations, and would like to make these + transformations permanent (note that `batch` gets discarded after the + RLModule forward pass), then you have to write the transformed + observations back into the episode to make sure you do not have to + perform the same transformation again on the learner (or replay buffer) + side. The Learner will hence work on the already changed episodes (and + compile the train batch using the Learner connector). + explore: Whether `explore` is currently on. Per convention, if True, the + RLModule's `forward_exploration` method should be called, if False, the + EnvRunner should call `forward_inference` instead. + shared_data: Optional additional context data that needs to be exchanged + between different ConnectorV2 pieces (in the same pipeline) or across + ConnectorV2 pipelines (meaning between env-to-module and module-to-env). + kwargs: Forward API-compatibility kwargs. + + Returns: + The transformed connector output. + """ + + @staticmethod + def single_agent_episode_iterator( + episodes: List[EpisodeType], + agents_that_stepped_only: bool = True, + zip_with_batch_column: Optional[Union[List[Any], Dict[Tuple, Any]]] = None, + ) -> Iterator[SingleAgentEpisode]: + """An iterator over a list of episodes yielding always SingleAgentEpisodes. + + In case items in the list are MultiAgentEpisodes, these are broken down + into their individual agents' SingleAgentEpisodes and those are then yielded + one after the other. + + Useful for connectors that operate on both single-agent and multi-agent + episodes. + + Args: + episodes: The list of SingleAgent- or MultiAgentEpisode objects. + agents_that_stepped_only: If True (and multi-agent setup), will only place + items of those agents into the batch that have just stepped in the + actual MultiAgentEpisode (this is checked via a + `MultiAgentEpside.episode.get_agents_to_act()`). Note that this setting + is ignored in a single-agent setups b/c the agent steps at each timestep + regardless. + zip_with_batch_column: If provided, must be a list of batch items + corresponding to the given `episodes` (single agent case) or a dict + mapping (AgentID, ModuleID) tuples to lists of individual batch items + corresponding to this agent/module combination. The iterator will then + yield tuples of SingleAgentEpisode objects (1st item) along with the + data item (2nd item) that this episode was responsible for generating + originally. + + Yields: + All SingleAgentEpisodes in the input list, whereby MultiAgentEpisodes will + be broken down into their individual SingleAgentEpisode components. + """ + list_indices = defaultdict(int) + + # Single-agent case. + if episodes and isinstance(episodes[0], SingleAgentEpisode): + if zip_with_batch_column is not None: + if len(zip_with_batch_column) != len(episodes): + raise ValueError( + "Invalid `zip_with_batch_column` data: Must have the same " + f"length as the list of episodes ({len(episodes)}), but has " + f"length {len(zip_with_batch_column)}!" + ) + # Simple case: Items are stored in lists directly under the column (str) + # key. + if isinstance(zip_with_batch_column, list): + for episode, data in zip(episodes, zip_with_batch_column): + yield episode, data + # Normal single-agent case: Items are stored in dicts under the column + # (str) key. These dicts map (eps_id,)-tuples to lists of individual + # items. + else: + for episode, (eps_id_tuple, data) in zip( + episodes, + zip_with_batch_column.items(), + ): + assert episode.id_ == eps_id_tuple[0] + d = data[list_indices[eps_id_tuple]] + list_indices[eps_id_tuple] += 1 + yield episode, d + else: + for episode in episodes: + yield episode + return + + # Multi-agent case. + for episode in episodes: + for agent_id in ( + episode.get_agents_that_stepped() + if agents_that_stepped_only + else episode.agent_ids + ): + sa_episode = episode.agent_episodes[agent_id] + # for sa_episode in episode.agent_episodes.values(): + if zip_with_batch_column is not None: + key = ( + sa_episode.multi_agent_episode_id, + sa_episode.agent_id, + sa_episode.module_id, + ) + if len(zip_with_batch_column[key]) <= list_indices[key]: + raise ValueError( + "Invalid `zip_with_batch_column` data: Must structurally " + "match the single-agent contents in the given list of " + "(multi-agent) episodes!" + ) + d = zip_with_batch_column[key][list_indices[key]] + list_indices[key] += 1 + yield sa_episode, d + else: + yield sa_episode + + @staticmethod + def add_batch_item( + batch: Dict[str, Any], + column: str, + item_to_add: Any, + single_agent_episode: Optional[SingleAgentEpisode] = None, + ) -> None: + """Adds a data item under `column` to the given `batch`. + + The `item_to_add` is stored in the `batch` in the following manner: + 1) If `single_agent_episode` is not provided (None), will store the item in a + list directly under `column`: + `column` -> [item, item, ...] + 2) If `single_agent_episode`'s `agent_id` and `module_id` properties are None + (`single_agent_episode` is not part of a multi-agent episode), will append + `item_to_add` to a list under a `(,)` key under `column`: + `column` -> `(,)` -> [item, item, ...] + 3) If `single_agent_episode`'s `agent_id` and `module_id` are NOT None + (`single_agent_episode` is part of a multi-agent episode), will append + `item_to_add` to a list under a `(,,)` key + under `column`: + `column` -> `(,,)` -> [item, item, ...] + + See the these examples here for clarification of these three cases: + + .. testcode:: + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # 1) Simple case (no episodes provided) -> Store data in a list directly + # under `column`: + batch = {} + ConnectorV2.add_batch_item(batch, "test_col", item_to_add=5) + ConnectorV2.add_batch_item(batch, "test_col", item_to_add=6) + check(batch, {"test_col": [5, 6]}) + ConnectorV2.add_batch_item(batch, "test_col_2", item_to_add=-10) + check(batch, { + "test_col": [5, 6], + "test_col_2": [-10], + }) + + # 2) Single-agent case (SingleAgentEpisode provided) -> Store data in a list + # under the keys: `column` -> `(,)` -> [...]: + batch = {} + episode = SingleAgentEpisode( + id_="SA-EPS0", + observations=[0, 1, 2, 3], + actions=[1, 2, 3], + rewards=[1.0, 2.0, 3.0], + ) + ConnectorV2.add_batch_item(batch, "test_col", 5, episode) + ConnectorV2.add_batch_item(batch, "test_col", 6, episode) + ConnectorV2.add_batch_item(batch, "test_col_2", -10, episode) + check(batch, { + "test_col": {("SA-EPS0",): [5, 6]}, + "test_col_2": {("SA-EPS0",): [-10]}, + }) + + # 3) Multi-agent case (SingleAgentEpisode provided that has `agent_id` and + # `module_id` information) -> Store data in a list under the keys: + # `column` -> `(,,)` -> [...]: + batch = {} + ma_episode = MultiAgentEpisode( + id_="MA-EPS1", + observations=[ + {"ag0": 0, "ag1": 1}, {"ag0": 2, "ag1": 4} + ], + actions=[{"ag0": 0, "ag1": 1}], + rewards=[{"ag0": -0.1, "ag1": -0.2}], + # ag0 maps to mod0, ag1 maps to mod1, etc.. + agent_to_module_mapping_fn=lambda aid, eps: f"mod{aid[2:]}", + ) + ConnectorV2.add_batch_item( + batch, + "test_col", + item_to_add=5, + single_agent_episode=ma_episode.agent_episodes["ag0"], + ) + ConnectorV2.add_batch_item( + batch, + "test_col", + item_to_add=6, + single_agent_episode=ma_episode.agent_episodes["ag0"], + ) + ConnectorV2.add_batch_item( + batch, + "test_col_2", + item_to_add=10, + single_agent_episode=ma_episode.agent_episodes["ag1"], + ) + check( + batch, + { + "test_col": {("MA-EPS1", "ag0", "mod0"): [5, 6]}, + "test_col_2": {("MA-EPS1", "ag1", "mod1"): [10]}, + }, + ) + + Args: + batch: The batch to store `item_to_add` in. + column: The column name (str) within the `batch` to store `item_to_add` + under. + item_to_add: The data item to store in the batch. + single_agent_episode: An optional SingleAgentEpisode. + If provided and its `agent_id` and `module_id` properties are None, + creates a further sub dictionary under `column`, mapping from + `(,)` to a list of data items (to which `item_to_add` will + be appended in this call). + If provided and its `agent_id` and `module_id` properties are NOT None, + creates a further sub dictionary under `column`, mapping from + `(,,,)` to a list of data items (to which + `item_to_add` will be appended in this call). + If not provided, will append `item_to_add` to a list directly under + `column`. + """ + sub_key = None + # SAEpisode is provided ... + if single_agent_episode is not None: + module_id = single_agent_episode.module_id + # ... and has `module_id` AND that `module_id` is already a top-level key in + # `batch` (`batch` is already in module-major form, mapping ModuleID to + # columns mapping to data). + if module_id is not None and module_id in batch: + raise ValueError( + "Can't call `add_batch_item` on a `batch` that is already " + "module-major (meaning ModuleID is top-level with column names on " + "the level thereunder)! Make sure to only call `add_batch_items` " + "before the `AgentToModuleMapping` ConnectorV2 piece is applied." + ) + + # ... and has `agent_id` -> Use `single_agent_episode`'s agent ID and + # module ID. + elif single_agent_episode.agent_id is not None: + sub_key = ( + single_agent_episode.multi_agent_episode_id, + single_agent_episode.agent_id, + single_agent_episode.module_id, + ) + # Otherwise, just use episode's ID. + else: + sub_key = (single_agent_episode.id_,) + + if column not in batch: + batch[column] = [] if sub_key is None else {sub_key: []} + if sub_key is not None: + if sub_key not in batch[column]: + batch[column][sub_key] = [] + batch[column][sub_key].append(item_to_add) + else: + batch[column].append(item_to_add) + + @staticmethod + def add_n_batch_items( + batch: Dict[str, Any], + column: str, + items_to_add: Any, + num_items: int, + single_agent_episode: Optional[SingleAgentEpisode] = None, + ) -> None: + """Adds a list of items (or batched item) under `column` to the given `batch`. + + If `items_to_add` is not a list, but an already batched struct (of np.ndarray + leafs), the `items_to_add` will be appended to possibly existing data under the + same `column` as-is. A subsequent `BatchIndividualItems` ConnectorV2 piece will + recognize this and batch the data properly into a single (batched) item. + This is much faster than first splitting up `items_to_add` and then adding each + item individually. + + If `single_agent_episode` is provided and its `agent_id` and `module_id` + properties are None, creates a further sub dictionary under `column`, mapping + from `(,)` to a list of data items (to which `items_to_add` will + be appended in this call). + If `single_agent_episode` is provided and its `agent_id` and `module_id` + properties are NOT None, creates a further sub dictionary under `column`, + mapping from `(,,,)` to a list of data items (to + which `items_to_add` will be appended in this call). + If `single_agent_episode` is not provided, will append `items_to_add` to a list + directly under `column`. + + .. testcode:: + + import numpy as np + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Simple case (no episodes provided) -> Store data in a list directly under + # `column`: + batch = {} + ConnectorV2.add_n_batch_items( + batch, + "test_col", + # List of (complex) structs. + [{"a": np.array(3), "b": 4}, {"a": np.array(5), "b": 6}], + num_items=2, + ) + check( + batch["test_col"], + [{"a": np.array(3), "b": 4}, {"a": np.array(5), "b": 6}], + ) + # In a new column (test_col_2), store some already batched items. + # This way, you may avoid having to disassemble an already batched item + # (e.g. a numpy array of shape (10, 2)) into its individual items (e.g. + # split the array into a list of len=10) and then adding these individually. + # The performance gains may be quite large when providing already batched + # items (such as numpy arrays with a batch dim): + ConnectorV2.add_n_batch_items( + batch, + "test_col_2", + # One (complex) already batched struct. + {"a": np.array([3, 5]), "b": np.array([4, 6])}, + num_items=2, + ) + # Add more already batched items (this time with a different batch size) + ConnectorV2.add_n_batch_items( + batch, + "test_col_2", + {"a": np.array([7, 7, 7]), "b": np.array([8, 8, 8])}, + num_items=3, # <- in this case, this must be the batch size + ) + check( + batch["test_col_2"], + [ + {"a": np.array([3, 5]), "b": np.array([4, 6])}, + {"a": np.array([7, 7, 7]), "b": np.array([8, 8, 8])}, + ], + ) + + # Single-agent case (SingleAgentEpisode provided) -> Store data in a list + # under the keys: `column` -> `(,)`: + batch = {} + episode = SingleAgentEpisode( + id_="SA-EPS0", + observations=[0, 1, 2, 3], + actions=[1, 2, 3], + rewards=[1.0, 2.0, 3.0], + ) + ConnectorV2.add_n_batch_items( + batch=batch, + column="test_col", + items_to_add=[5, 6, 7], + num_items=3, + single_agent_episode=episode, + ) + check(batch, { + "test_col": {("SA-EPS0",): [5, 6, 7]}, + }) + + # Multi-agent case (SingleAgentEpisode provided that has `agent_id` and + # `module_id` information) -> Store data in a list under the keys: + # `column` -> `(,,)`: + batch = {} + ma_episode = MultiAgentEpisode( + id_="MA-EPS1", + observations=[ + {"ag0": 0, "ag1": 1}, {"ag0": 2, "ag1": 4} + ], + actions=[{"ag0": 0, "ag1": 1}], + rewards=[{"ag0": -0.1, "ag1": -0.2}], + # ag0 maps to mod0, ag1 maps to mod1, etc.. + agent_to_module_mapping_fn=lambda aid, eps: f"mod{aid[2:]}", + ) + ConnectorV2.add_batch_item( + batch, + "test_col", + item_to_add=5, + single_agent_episode=ma_episode.agent_episodes["ag0"], + ) + ConnectorV2.add_batch_item( + batch, + "test_col", + item_to_add=6, + single_agent_episode=ma_episode.agent_episodes["ag0"], + ) + ConnectorV2.add_batch_item( + batch, + "test_col_2", + item_to_add=10, + single_agent_episode=ma_episode.agent_episodes["ag1"], + ) + check( + batch, + { + "test_col": {("MA-EPS1", "ag0", "mod0"): [5, 6]}, + "test_col_2": {("MA-EPS1", "ag1", "mod1"): [10]}, + }, + ) + + Args: + batch: The batch to store n `items_to_add` in. + column: The column name (str) within the `batch` to store `item_to_add` + under. + items_to_add: The list of data items to store in the batch OR an already + batched (possibly nested) struct. In the latter case, the `items_to_add` + will be appended to possibly existing data under the same `column` + as-is. A subsequent `BatchIndividualItems` ConnectorV2 piece will + recognize this and batch the data properly into a single (batched) item. + This is much faster than first splitting up `items_to_add` and then + adding each item individually. + num_items: The number of items in `items_to_add`. This arg is mostly for + asserting the correct usage of this method by checking, whether the + given data in `items_to_add` really has the right amount of individual + items. + single_agent_episode: An optional SingleAgentEpisode. + If provided and its `agent_id` and `module_id` properties are None, + creates a further sub dictionary under `column`, mapping from + `(,)` to a list of data items (to which `items_to_add` will + be appended in this call). + If provided and its `agent_id` and `module_id` properties are NOT None, + creates a further sub dictionary under `column`, mapping from + `(,,,)` to a list of data items (to which + `items_to_add` will be appended in this call). + If not provided, will append `items_to_add` to a list directly under + `column`. + """ + # Process n list items by calling `add_batch_item` on each of them individually. + if isinstance(items_to_add, list): + if len(items_to_add) != num_items: + raise ValueError( + f"Mismatch breteen `num_items` ({num_items}) and the length " + f"of the provided list ({len(items_to_add)}) in " + f"{ConnectorV2.__name__}.add_n_batch_items()!" + ) + for item in items_to_add: + ConnectorV2.add_batch_item( + batch=batch, + column=column, + item_to_add=item, + single_agent_episode=single_agent_episode, + ) + return + + # Process a batched (possibly complex) struct. + # We could just unbatch the item (split it into a list) and then add each + # individual item to our `batch`. However, this comes with a heavy performance + # penalty. Instead, we tag the thus added array(s) here as "_has_batch_dim=True" + # and then know that when batching the entire list under the respective + # (eps_id, agent_id, module_id)-tuple key, we need to concatenate, not stack + # the items in there. + def _tag(s): + return BatchedNdArray(s) + + ConnectorV2.add_batch_item( + batch=batch, + column=column, + # Convert given input into BatchedNdArray(s) such that the `batch` utility + # knows that it'll have to concat, not stack. + item_to_add=tree.map_structure(_tag, items_to_add), + single_agent_episode=single_agent_episode, + ) + + @staticmethod + def foreach_batch_item_change_in_place( + batch: Dict[str, Any], + column: Union[str, List[str], Tuple[str]], + func: Callable[ + [Any, Optional[int], Optional[AgentID], Optional[ModuleID]], Any + ], + ) -> None: + """Runs the provided `func` on all items under one or more columns in the batch. + + Use this method to conveniently loop through all items in a batch + and transform them in place. + + `func` takes the following as arguments: + - The item itself. If column is a list of column names, this argument is a tuple + of items. + - The EpisodeID. This value might be None. + - The AgentID. This value might be None in the single-agent case. + - The ModuleID. This value might be None in the single-agent case. + + The return value(s) of `func` are used to directly override the values in the + given `batch`. + + Args: + batch: The batch to process in-place. + column: A single column name (str) or a list thereof. If a list is provided, + the first argument to `func` is a tuple of items. If a single + str is provided, the first argument to `func` is an individual + item. + func: The function to call on each item or tuple of item(s). + + .. testcode:: + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + from ray.rllib.utils.test_utils import check + + # Simple case: Batch items are in lists directly under their column names. + batch = { + "col1": [0, 1, 2, 3], + "col2": [0, -1, -2, -3], + } + # Increase all ints by 1. + ConnectorV2.foreach_batch_item_change_in_place( + batch=batch, + column="col1", + func=lambda item, *args: item + 1, + ) + check(batch["col1"], [1, 2, 3, 4]) + + # Further increase all ints by 1 in col1 and flip sign in col2. + ConnectorV2.foreach_batch_item_change_in_place( + batch=batch, + column=["col1", "col2"], + func=(lambda items, *args: (items[0] + 1, -items[1])), + ) + check(batch["col1"], [2, 3, 4, 5]) + check(batch["col2"], [0, 1, 2, 3]) + + # Single-agent case: Batch items are in lists under (eps_id,)-keys in a dict + # under their column names. + batch = { + "col1": { + ("eps1",): [0, 1, 2, 3], + ("eps2",): [400, 500, 600], + }, + } + # Increase all ints of eps1 by 1 and divide all ints of eps2 by 100. + ConnectorV2.foreach_batch_item_change_in_place( + batch=batch, + column="col1", + func=lambda item, eps_id, *args: ( + item + 1 if eps_id == "eps1" else item / 100 + ), + ) + check(batch["col1"], { + ("eps1",): [1, 2, 3, 4], + ("eps2",): [4, 5, 6], + }) + + # Multi-agent case: Batch items are in lists under + # (eps_id, agent_id, module_id)-keys in a dict + # under their column names. + batch = { + "col1": { + ("eps1", "ag1", "mod1"): [1, 2, 3, 4], + ("eps2", "ag1", "mod2"): [400, 500, 600], + ("eps2", "ag2", "mod3"): [-1, -2, -3, -4, -5], + }, + } + # Decrease all ints of "eps1" by 1, divide all ints of "mod2" by 100, and + # flip sign of all ints of "ag2". + ConnectorV2.foreach_batch_item_change_in_place( + batch=batch, + column="col1", + func=lambda item, eps_id, ag_id, mod_id: ( + item - 1 + if eps_id == "eps1" + else item / 100 + if mod_id == "mod2" + else -item + ), + ) + check(batch["col1"], { + ("eps1", "ag1", "mod1"): [0, 1, 2, 3], + ("eps2", "ag1", "mod2"): [4, 5, 6], + ("eps2", "ag2", "mod3"): [1, 2, 3, 4, 5], + }) + """ + data_to_process = [batch.get(c) for c in force_list(column)] + single_col = isinstance(column, str) + if any(d is None for d in data_to_process): + raise ValueError( + f"Invalid column name(s) ({column})! One or more not found in " + f"given batch. Found columns {list(batch.keys())}." + ) + + # Simple case: Data items are stored in a list directly under the column + # name(s). + if isinstance(data_to_process[0], list): + for list_pos, data_tuple in enumerate(zip(*data_to_process)): + results = func( + data_tuple[0] if single_col else data_tuple, + None, # episode_id + None, # agent_id + None, # module_id + ) + # Tuple'ize results if single_col. + results = (results,) if single_col else results + for col_slot, result in enumerate(force_list(results)): + data_to_process[col_slot][list_pos] = result + # Single-agent/multi-agent cases. + else: + for key, d0_list in data_to_process[0].items(): + # Multi-agent case: There is a dict mapping from a + # (eps id, AgentID, ModuleID)-tuples to lists of individual data items. + if len(key) == 3: + eps_id, agent_id, module_id = key + # Single-agent case: There is a dict mapping from a (eps_id,)-tuple + # to lists of individual data items. + # AgentID and ModuleID are both None. + else: + eps_id = key[0] + agent_id = module_id = None + other_lists = [d[key] for d in data_to_process[1:]] + for list_pos, data_tuple in enumerate(zip(d0_list, *other_lists)): + results = func( + data_tuple[0] if single_col else data_tuple, + eps_id, + agent_id, + module_id, + ) + # Tuple'ize results if single_col. + results = (results,) if single_col else results + for col_slot, result in enumerate(results): + data_to_process[col_slot][key][list_pos] = result + + @staticmethod + def switch_batch_from_column_to_module_ids( + batch: Dict[str, Dict[ModuleID, Any]] + ) -> Dict[ModuleID, Dict[str, Any]]: + """Switches the first two levels of a `col_name -> ModuleID -> data` type batch. + + Assuming that the top level consists of column names as keys and the second + level (under these columns) consists of ModuleID keys, the resulting batch + will have these two reversed and thus map ModuleIDs to dicts mapping column + names to data items. + + .. testcode:: + + from ray.rllib.utils.test_utils import check + + batch = { + "obs": {"module_0": [1, 2, 3]}, + "actions": {"module_0": [4, 5, 6], "module_1": [7]}, + } + switched_batch = ConnectorV2.switch_batch_from_column_to_module_ids(batch) + check( + switched_batch, + { + "module_0": {"obs": [1, 2, 3], "actions": [4, 5, 6]}, + "module_1": {"actions": [7]}, + }, + ) + + Args: + batch: The batch to switch from being column name based (then ModuleIDs) + to being ModuleID based (then column names). + + Returns: + A new batch dict mapping ModuleIDs to dicts mapping column names (e.g. + "obs") to data. + """ + module_data = defaultdict(dict) + for column, column_data in batch.items(): + for module_id, data in column_data.items(): + module_data[module_id][column] = data + return dict(module_data) + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + return {} + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + pass + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]: + return ( + (), # *args + self._ctor_kwargs, # **kwargs + ) + + def reset_state(self) -> None: + """Resets the state of this ConnectorV2 to some initial value. + + Note that this may NOT be the exact state that this ConnectorV2 was originally + constructed with. + """ + return + + def merge_states(self, states: List[Dict[str, Any]]) -> Dict[str, Any]: + """Computes a resulting state given self's state and a list of other states. + + Algorithms should use this method for merging states between connectors + running on parallel EnvRunner workers. For example, to synchronize the connector + states of n remote workers and a local worker, one could: + - Gather all remote worker connector states in a list. + - Call `self.merge_states()` on the local worker passing it the states list. + - Broadcast the resulting local worker's connector state back to all remote + workers. After this, all workers (including the local one) hold a + merged/synchronized new connecto state. + + Args: + states: The list of n other ConnectorV2 states to merge with self's state + into a single resulting state. + + Returns: + The resulting state dict. + """ + return {} + + @property + def observation_space(self): + """Getter for our (output) observation space. + + Logic: Use user provided space (if set via `observation_space` setter) + otherwise, use the same as the input space, assuming this connector piece + does not alter the space. + """ + return self._observation_space + + @property + def action_space(self): + """Getter for our (output) action space. + + Logic: Use user provided space (if set via `action_space` setter) + otherwise, use the same as the input space, assuming this connector piece + does not alter the space. + """ + return self._action_space + + @property + def input_observation_space(self): + return self._input_observation_space + + @input_observation_space.setter + def input_observation_space(self, value): + self._input_observation_space = value + if value is not None: + self._observation_space = self.recompute_output_observation_space( + value, self.input_action_space + ) + + @property + def input_action_space(self): + return self._input_action_space + + @input_action_space.setter + def input_action_space(self, value): + self._input_action_space = value + if value is not None: + self._action_space = self.recompute_output_action_space( + self.input_observation_space, value + ) + + def __str__(self, indentation: int = 0): + return " " * indentation + self.__class__.__name__ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2873294ac694e5e426d1dd4d47a59d9b0d87f06c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__init__.py @@ -0,0 +1,36 @@ +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_states_from_episodes_to_batch import ( + AddStatesFromEpisodesToBatch, +) +from ray.rllib.connectors.common.agent_to_module_mapping import AgentToModuleMapping +from ray.rllib.connectors.common.batch_individual_items import BatchIndividualItems +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.connectors.env_to_module.env_to_module_pipeline import ( + EnvToModulePipeline, +) +from ray.rllib.connectors.env_to_module.flatten_observations import ( + FlattenObservations, +) +from ray.rllib.connectors.env_to_module.mean_std_filter import MeanStdFilter +from ray.rllib.connectors.env_to_module.prev_actions_prev_rewards import ( + PrevActionsPrevRewards, +) +from ray.rllib.connectors.env_to_module.write_observations_to_episodes import ( + WriteObservationsToEpisodes, +) + + +__all__ = [ + "AddObservationsFromEpisodesToBatch", + "AddStatesFromEpisodesToBatch", + "AgentToModuleMapping", + "BatchIndividualItems", + "EnvToModulePipeline", + "FlattenObservations", + "MeanStdFilter", + "NumpyToTensor", + "PrevActionsPrevRewards", + "WriteObservationsToEpisodes", +] diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/env_to_module_pipeline.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/env_to_module_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecc228c0366bfd55c50a9a3945dc14cbc803dfc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/env_to_module_pipeline.py @@ -0,0 +1,32 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class EnvToModulePipeline(ConnectorPipelineV2): + @override(ConnectorPipelineV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]] = None, + episodes: List[EpisodeType], + explore: bool, + shared_data: Optional[dict] = None, + **kwargs, + ): + # Make sure user does not necessarily send initial input into this pipeline. + # Might just be empty and to be populated from `episodes`. + return super().__call__( + rl_module=rl_module, + batch=batch if batch is not None else {}, + episodes=episodes, + explore=explore, + shared_data=shared_data if shared_data is not None else {}, + **kwargs, + ) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..120099ffe50b82f74490b71102b942dce1ad7e78 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py @@ -0,0 +1,80 @@ +import abc +from typing import Any, Dict, List, Optional + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ObservationPreprocessor(ConnectorV2, abc.ABC): + """Env-to-module connector performing one preprocessor step on the last observation. + + This is a convenience class that simplifies the writing of few-step preprocessor + connectors. + + Users must implement the `preprocess()` method, which simplifies the usual procedure + of extracting some data from a list of episodes and adding it to the batch to a mere + "old-observation --transform--> return new-observation" step. + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + # Users should override this method only in case the `ObservationPreprocessor` + # changes the observation space of the pipeline. In this case, return the new + # observation space based on the incoming one (`input_observation_space`). + return super().recompute_output_observation_space( + input_observation_space, input_action_space + ) + + @abc.abstractmethod + def preprocess(self, observation): + """Override to implement the preprocessing logic. + + Args: + observation: A single (non-batched) observation item for a single agent to + be processed by this connector. + + Returns: + The new observation after `observation` has been preprocessed. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + persistent_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # We process and then replace observations inside the episodes directly. + # Thus, all following connectors will only see and operate on the already + # processed observation (w/o having access anymore to the original + # observations). + for sa_episode in self.single_agent_episode_iterator(episodes): + observation = sa_episode.get_observations(-1) + + # Process the observation and write the new observation back into the + # episode. + new_observation = self.preprocess(observation=observation) + sa_episode.set_observations(at_indices=-1, new_data=new_observation) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + sa_episode.observation_space = self.observation_space + + # Leave `batch` as is. RLlib's default connector will automatically + # populate the OBS column therein from the episodes' now transformed + # observations. + return batch diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py new file mode 100644 index 0000000000000000000000000000000000000000..0c269348ce2dae4387f2133557c7a05bcbafbaf7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py @@ -0,0 +1,131 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class WriteObservationsToEpisodes(ConnectorV2): + """Writes the observations from the batch into the running episodes. + + Note: This is one of the default env-to-module ConnectorV2 pieces that are added + automatically by RLlib into every env-to-module connector pipelines, unless + `config.add_default_connectors_to_env_to_module_pipeline` is set to False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + This ConnectorV2: + - Operates on a batch that already has observations in it and a list of Episode + objects. + - Writes the observation(s) from the batch to all the given episodes. Thereby + the number of observations in the batch must match the length of the list of + episodes given. + - Does NOT alter any observations (or other data) in the batch. + - Can only be used in an EnvToModule pipeline (writing into Episode objects in a + Learner pipeline does not make a lot of sense as - after the learner update - the + list of episodes is discarded). + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.env_to_module import WriteObservationsToEpisodes + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Assume we have two episodes (vectorized), then our forward batch will carry + # two observation records (batch size = 2). + # The connector in this example will write these two (possibly transformed) + # observations back into the two respective SingleAgentEpisode objects. + batch = { + "obs": [np.array([0.0, 1.0], np.float32), np.array([2.0, 3.0], np.float32)], + } + + # Our two episodes have one observation each (i.e. the reset one). This is the + # one that will be overwritten by the connector in this example. + obs_space = gym.spaces.Box(-10.0, 10.0, (2,), np.float32) + act_space = gym.spaces.Discrete(2) + episodes = [ + SingleAgentEpisode( + observation_space=obs_space, + observations=[np.array([-10, -20], np.float32)], + len_lookback_buffer=0, + ) for _ in range(2) + ] + # Make sure everything is setup correctly. + check(episodes[0].get_observations(0), [-10.0, -20.0]) + check(episodes[1].get_observations(-1), [-10.0, -20.0]) + + # Create our connector piece. + connector = WriteObservationsToEpisodes(obs_space, act_space) + + # Call the connector (and thereby write the transformed observations back + # into the episodes). + output_batch = connector( + rl_module=None, # This particular connector works without an RLModule. + batch=batch, + episodes=episodes, + explore=True, + shared_data={}, + ) + + # The connector does NOT change the data batch being passed through. + check(output_batch, batch) + + # However, the connector has overwritten the last observations in the episodes. + check(episodes[0].get_observations(-1), [0.0, 1.0]) + check(episodes[1].get_observations(0), [2.0, 3.0]) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + observations = batch.get(Columns.OBS) + + if observations is None: + raise ValueError( + f"`batch` must already have a column named {Columns.OBS} in it " + f"for this connector to work!" + ) + + # Note that the following loop works with multi-agent as well as with + # single-agent episode, as long as the following conditions are met (these + # will be validated by `self.single_agent_episode_iterator()`): + # - Per single agent episode, one observation item is expected to exist in + # `data`, either in a list directly under the "obs" key OR for multi-agent: + # in a list sitting under a key `(agent_id, module_id)` of a dict sitting + # under the "obs" key. + for sa_episode, obs in self.single_agent_episode_iterator( + episodes=episodes, zip_with_batch_column=observations + ): + # Make sure episodes are NOT finalized yet (we are expecting to run in an + # env-to-module pipeline). + assert not sa_episode.is_finalized + # Write new information into the episode. + sa_episode.set_observations(at_indices=-1, new_data=obs) + # Change the observation space of the sa_episode. + sa_episode.observation_space = self.observation_space + + # Return the unchanged `batch`. + return batch diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..83685d288dec88efebf789cc3045ec09da2c2417 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__init__.py @@ -0,0 +1,37 @@ +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_states_from_episodes_to_batch import ( + AddStatesFromEpisodesToBatch, +) +from ray.rllib.connectors.common.agent_to_module_mapping import AgentToModuleMapping +from ray.rllib.connectors.common.batch_individual_items import BatchIndividualItems +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.connectors.learner.add_columns_from_episodes_to_train_batch import ( + AddColumnsFromEpisodesToTrainBatch, +) +from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa + AddNextObservationsFromEpisodesToTrainBatch, +) +from ray.rllib.connectors.learner.add_one_ts_to_episodes_and_truncate import ( + AddOneTsToEpisodesAndTruncate, +) +from ray.rllib.connectors.learner.general_advantage_estimation import ( + GeneralAdvantageEstimation, +) +from ray.rllib.connectors.learner.learner_connector_pipeline import ( + LearnerConnectorPipeline, +) + +__all__ = [ + "AddColumnsFromEpisodesToTrainBatch", + "AddNextObservationsFromEpisodesToTrainBatch", + "AddObservationsFromEpisodesToBatch", + "AddOneTsToEpisodesAndTruncate", + "AddStatesFromEpisodesToBatch", + "AgentToModuleMapping", + "BatchIndividualItems", + "GeneralAdvantageEstimation", + "LearnerConnectorPipeline", + "NumpyToTensor", +] diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30cde65ca01fe2bce7ab5a66c93b7c36e79f2f4c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_columns_from_episodes_to_train_batch.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_columns_from_episodes_to_train_batch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..505e76668b6ea094aa448b237272d4f10d9d2bbe Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_columns_from_episodes_to_train_batch.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_next_observations_from_episodes_to_train_batch.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_next_observations_from_episodes_to_train_batch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc9ac4f74efe627c226be3e10e0953e4649621bf Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_next_observations_from_episodes_to_train_batch.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3b1865c37eeb57696c6dec2b7e0602bcfc6a5be Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb34278465f36643caad4a0d064ee2eda0441d8b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65ce2c154eab3e655048d7048beef2e4209fc3ce Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a721bc48a98456ea04344c3fa08b2e0c760df94b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..2669dc49b5f9c33868a5b11727006bfa871e07e0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py @@ -0,0 +1,165 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddColumnsFromEpisodesToTrainBatch(ConnectorV2): + """Adds infos/actions/rewards/terminateds/... to train batch. + + Note: This is one of the default Learner ConnectorV2 pieces that are added + automatically by RLlib into every Learner connector pipeline, unless + `config.add_default_connectors_to_learner_pipeline` is set to False. + + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + Does NOT add observations to train batch (these should have already been added + by another ConnectorV2 piece: `AddObservationsToTrainBatch` in the same pipeline). + + If provided with `episodes` data, this connector piece makes sure that the final + train batch going into the RLModule for updating (`forward_train()` call) contains + at the minimum: + - Observations: From all episodes under the Columns.OBS key. + - Actions, rewards, terminal/truncation flags: From all episodes under the + respective keys. + - All data inside the episodes' `extra_model_outs` property, e.g. action logp and + action probs under the respective keys. + - Internal states: These will NOT be added to the batch by this connector piece + as this functionality is handled by a different default connector piece: + `AddStatesFromEpisodesToBatch`. + + If the user wants to customize their own data under the given keys (e.g. obs, + actions, ...), they can extract from the episodes or recompute from `data` + their own data and store it in `data` under those keys. In this case, the default + connector will not change the data under these keys and simply act as a + pass-through. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Infos. + if Columns.INFOS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.INFOS, + items_to_add=sa_episode.get_infos(slice(0, len(sa_episode))), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + # Actions. + if Columns.ACTIONS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.ACTIONS, + items_to_add=[ + sa_episode.get_actions(indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + # Rewards. + if Columns.REWARDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.REWARDS, + items_to_add=[ + sa_episode.get_rewards(indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + # Terminateds. + if Columns.TERMINATEDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.TERMINATEDS, + items_to_add=( + [False] * (len(sa_episode) - 1) + [sa_episode.is_terminated] + if len(sa_episode) > 0 + else [] + ), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + # Truncateds. + if Columns.TRUNCATEDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.TRUNCATEDS, + items_to_add=( + [False] * (len(sa_episode) - 1) + [sa_episode.is_truncated] + if len(sa_episode) > 0 + else [] + ), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + # Extra model outputs (except for STATE_OUT, which will be handled by another + # default connector piece). Also, like with all the fields above, skip + # those that the user already seemed to have populated via custom connector + # pieces. + skip_columns = set(batch.keys()) | {Columns.STATE_IN, Columns.STATE_OUT} + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + for column in sa_episode.extra_model_outputs.keys(): + if column not in skip_columns: + self.add_n_batch_items( + batch, + column, + items_to_add=[ + sa_episode.get_extra_model_outputs(key=column, indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + return batch diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..6efa3b706bf1f24e61f9791b273e7f11b08b5066 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py @@ -0,0 +1,103 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.core.columns import Columns +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddNextObservationsFromEpisodesToTrainBatch(ConnectorV2): + """Adds the NEXT_OBS column with the correct episode observations to train batch. + + - Operates on a list of Episode objects. + - Gets all observation(s) from all the given episodes (except the very first ones) + and adds them to the batch under construction in the NEXT_OBS column (as a list of + individual observations). + - Does NOT alter any observations (or other data) in the given episodes. + - Can be used in Learner connector pipelines. + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.learner import ( + AddNextObservationsFromEpisodesToTrainBatch + ) + from ray.rllib.core.columns import Columns + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Create two dummy SingleAgentEpisodes, each containing 3 observations, + # 2 actions and 2 rewards (both episodes are length=2). + obs_space = gym.spaces.Box(-1.0, 1.0, (2,), np.float32) + act_space = gym.spaces.Discrete(2) + + episodes = [SingleAgentEpisode( + observations=[obs_space.sample(), obs_space.sample(), obs_space.sample()], + actions=[act_space.sample(), act_space.sample()], + rewards=[1.0, 2.0], + len_lookback_buffer=0, + ) for _ in range(2)] + eps_1_next_obses = episodes[0].get_observations([1, 2]) + eps_2_next_obses = episodes[1].get_observations([1, 2]) + print(f"1st Episode's next obses are {eps_1_next_obses}") + print(f"2nd Episode's next obses are {eps_2_next_obses}") + + # Create an instance of this class. + connector = AddNextObservationsFromEpisodesToTrainBatch() + + # Call the connector with the two created episodes. + # Note that this particular connector works without an RLModule, so we + # simplify here for the sake of this example. + output_data = connector( + rl_module=None, + batch={}, + episodes=episodes, + explore=True, + shared_data={}, + ) + # The output data should now contain the last observations of both episodes, + # in a "per-episode organized" fashion. + check( + output_data, + { + Columns.NEXT_OBS: { + (episodes[0].id_,): eps_1_next_obses, + (episodes[1].id_,): eps_2_next_obses, + }, + }, + ) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # If "obs" already in `batch`, early out. + if Columns.NEXT_OBS in batch: + return batch + + for sa_episode in self.single_agent_episode_iterator( + # This is a Learner-only connector -> Get all episodes (for train batch). + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.NEXT_OBS, + items_to_add=sa_episode.get_observations(slice(1, len(sa_episode) + 1)), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + return batch diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0a6d11bebe6c76966a2fc72fc180f99d97665e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py @@ -0,0 +1,168 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.utils.annotations import override +from ray.rllib.utils.postprocessing.episodes import add_one_ts_to_episodes_and_truncate +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddOneTsToEpisodesAndTruncate(ConnectorV2): + """Adds an artificial timestep to all incoming episodes at the end. + + In detail: The last observations, infos, actions, and all `extra_model_outputs` + will be duplicated and appended to each episode's data. An extra 0.0 reward + will be appended to the episode's rewards. The episode's timestep will be + increased by 1. Also, adds the truncated=True flag to each episode if the + episode is not already done (terminated or truncated). + + Useful for value function bootstrapping, where it is required to compute a + forward pass for the very last timestep within the episode, + i.e. using the following input dict: { + obs=[final obs], + state=[final state output], + prev. reward=[final reward], + etc.. + } + + .. testcode:: + + from ray.rllib.connectors.learner import AddOneTsToEpisodesAndTruncate + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Create 2 episodes (both to be extended by one timestep). + episode1 = SingleAgentEpisode( + observations=[0, 1, 2], + actions=[0, 1], + rewards=[0.0, 1.0], + terminated=False, + truncated=False, + len_lookback_buffer=0, + ).finalize() + check(len(episode1), 2) + check(episode1.is_truncated, False) + + episode2 = SingleAgentEpisode( + observations=[0, 1, 2, 3, 4, 5], + actions=[0, 1, 2, 3, 4], + rewards=[0.0, 1.0, 2.0, 3.0, 4.0], + terminated=True, # a terminated episode + truncated=False, + len_lookback_buffer=0, + ).finalize() + check(len(episode2), 5) + check(episode2.is_truncated, False) + check(episode2.is_terminated, True) + + # Create an instance of this class. + connector = AddOneTsToEpisodesAndTruncate() + + # Call the connector. + shared_data = {} + _ = connector( + rl_module=None, # Connector used here does not require RLModule. + batch={}, + episodes=[episode1, episode2], + shared_data=shared_data, + ) + # Check on the episodes. Both of them should now be 1 timestep longer. + check(len(episode1), 3) + check(episode1.is_truncated, True) + check(len(episode2), 6) + check(episode2.is_truncated, False) + check(episode2.is_terminated, True) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Build the loss mask to make sure the extra added timesteps do not influence + # the final loss and fix the terminateds and truncateds in the batch. + + # For proper v-trace execution, the rules must be as follows: + # Legend: + # T: terminal=True + # R: truncated=True + # B0: bootstrap with value 0 (also: terminal=True) + # Bx: bootstrap with some vf-computed value (also: terminal=True) + + # batch: - - - - - - - T B0- - - - - R Bx- - - - R Bx + # mask : t t t t t t t t f t t t t t t f t t t t t f + + # TODO (sven): Same situation as in TODO below, but for multi-agent episode. + # Maybe add a dedicated connector piece for this task? + # We extend the MultiAgentEpisode's ID by a running number here to make sure + # we treat each MAEpisode chunk as separate (for potentially upcoming v-trace + # and LSTM zero-padding) and don't mix data from different chunks. + if isinstance(episodes[0], MultiAgentEpisode): + for i, ma_episode in enumerate(episodes): + ma_episode.id_ += "_" + str(i) + # Also change the underlying single-agent episode's + # `multi_agent_episode_id` properties. + for sa_episode in ma_episode.agent_episodes.values(): + sa_episode.multi_agent_episode_id = ma_episode.id_ + + for i, sa_episode in enumerate( + self.single_agent_episode_iterator(episodes, agents_that_stepped_only=False) + ): + # TODO (sven): This is a little bit of a hack: By extending the Episode's + # ID, we make sure that each episode chunk in `episodes` is treated as a + # separate episode in the `self.add_n_batch_items` below. Some algos (e.g. + # APPO) may have >1 episode chunks from the same episode (same ID) in the + # training data, thus leading to a malformatted batch in case of + # RNN-triggered zero-padding of the train batch. + # For example, if e1 (id=a len=4) and e2 (id=a len=5) are two chunks of the + # same episode in `episodes`, the resulting batch would have an additional + # timestep in the middle of the episode's "row": + # { "obs": { + # ("a", <- eps ID): [0, 1, 2, 3 <- len=4, [additional 1 ts (bad)], + # 0, 1, 2, 3, 4 <- len=5, [additional 1 ts]] + # }} + sa_episode.id_ += "_" + str(i) + + len_ = len(sa_episode) + + # Extend all episodes by one ts. + add_one_ts_to_episodes_and_truncate([sa_episode]) + + loss_mask = [True for _ in range(len_)] + [False] + self.add_n_batch_items( + batch, + Columns.LOSS_MASK, + loss_mask, + len_ + 1, + sa_episode, + ) + + terminateds = ( + [False for _ in range(len_ - 1)] + + [bool(sa_episode.is_terminated)] + + [True] # extra timestep + ) + self.add_n_batch_items( + batch, + Columns.TERMINATEDS, + terminateds, + len_ + 1, + sa_episode, + ) + + # Signal to following connector pieces that the loss-mask which masks out + # invalid episode ts (for the extra added ts at the end) has already been + # added to `data`. + shared_data["_added_loss_mask_for_valid_episode_ts"] = True + + return batch diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/frame_stacking.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/frame_stacking.py new file mode 100644 index 0000000000000000000000000000000000000000..648c7146fc5f9f8d568065240a34387f04c67f81 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/frame_stacking.py @@ -0,0 +1,6 @@ +from functools import partial + +from ray.rllib.connectors.common.frame_stacking import _FrameStacking + + +FrameStackingLearner = partial(_FrameStacking, as_learner_connector=True) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/general_advantage_estimation.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/general_advantage_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..a92580487a027518923bc5218f126779783417aa --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/general_advantage_estimation.py @@ -0,0 +1,195 @@ +from typing import Any, List, Dict + +import numpy as np + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.evaluation.postprocessing import Postprocessing +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.postprocessing.value_predictions import compute_value_targets +from ray.rllib.utils.postprocessing.zero_padding import ( + split_and_zero_pad_n_episodes, + unpad_data_if_necessary, +) +from ray.rllib.utils.typing import EpisodeType + + +class GeneralAdvantageEstimation(ConnectorV2): + """Learner ConnectorV2 piece computing GAE advantages and value targets on episodes. + + This ConnectorV2: + - Operates on a list of Episode objects (single- or multi-agent). + - Should be used only in the Learner pipeline and as one of the last pieces (due + to the fact that it requires the batch for the value functions to be already + complete). + - Requires the incoming episodes to already be elongated by one artificial timestep + at the end (last obs, actions, states, etc.. repeated, last reward=0.0, etc..), + making it possible to combine the per-timestep value computations with the + necessary "bootstrap" value computations at the episode (chunk) truncation points. + The extra timestep should be added using the `ray.rllib.connectors.learner. + add_one_ts_to_episodes_and_truncate.AddOneTsToEpisodesAndTruncate` connector piece. + + The GAE computation is performed in an efficient way through using the arriving + `batch` as forward batch for the value function, extracting the bootstrap values + (at the artificially added time steos) and all other value predictions (all other + timesteps), performing GAE, and adding the results back into `batch` (under + Postprocessing.ADVANTAGES and Postprocessing.VALUE_TARGETS. + """ + + def __init__( + self, + input_observation_space=None, + input_action_space=None, + *, + gamma, + lambda_, + ): + """Initializes a GeneralAdvantageEstimation instance. + + Args: + gamma: The discount factor gamma. + lambda_: The lambda parameter for General Advantage Estimation (GAE). + Defines the exponential weight used between actually measured rewards + vs value function estimates over multiple time steps. Specifically, + `lambda_` balances short-term, low-variance estimates with longer-term, + high-variance returns. A `lambda_` or 0.0 makes the GAE rely only on + immediate rewards (and vf predictions from there on, reducing variance, + but increasing bias), while a `lambda_` of 1.0 only incorporates vf + predictions at the truncation points of the given episodes or episode + chunks (reducing bias but increasing variance). + """ + super().__init__(input_observation_space, input_action_space) + self.gamma = gamma + self.lambda_ = lambda_ + + # Internal numpy-to-tensor connector to translate GAE results (advantages and + # vf targets) into tensors. + self._numpy_to_tensor_connector = None + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: MultiRLModule, + episodes: List[EpisodeType], + batch: Dict[str, Any], + **kwargs, + ): + # Device to place all GAE result tensors (advantages and value targets) on. + device = None + + # Extract all single-agent episodes. + sa_episodes_list = list( + self.single_agent_episode_iterator(episodes, agents_that_stepped_only=False) + ) + # Perform the value nets' forward passes. + # TODO (sven): We need to check here in the pipeline already, whether a module + # should even be updated or not (which we usually do after(!) the Learner + # pipeline). This is an open TODO to move this filter into a connector as well. + # For now, we'll just check, whether `mid` is in batch and skip if it isn't. + vf_preds = rl_module.foreach_module( + func=lambda mid, module: ( + module.compute_values(batch[mid]) + if mid in batch and isinstance(module, ValueFunctionAPI) + else None + ), + return_dict=True, + ) + # Loop through all modules and perform each one's GAE computation. + for module_id, module_vf_preds in vf_preds.items(): + # Skip those outputs of RLModules that are not implementers of + # `ValueFunctionAPI`. + if module_vf_preds is None: + continue + + module = rl_module[module_id] + device = module_vf_preds.device + # Convert to numpy for the upcoming GAE computations. + module_vf_preds = convert_to_numpy(module_vf_preds) + + # Collect (single-agent) episode lengths for this particular module. + episode_lens = [ + len(e) for e in sa_episodes_list if e.module_id in [None, module_id] + ] + + # Remove all zero-padding again, if applicable, for the upcoming + # GAE computations. + module_vf_preds = unpad_data_if_necessary(episode_lens, module_vf_preds) + # Compute value targets. + module_value_targets = compute_value_targets( + values=module_vf_preds, + rewards=unpad_data_if_necessary( + episode_lens, + convert_to_numpy(batch[module_id][Columns.REWARDS]), + ), + terminateds=unpad_data_if_necessary( + episode_lens, + convert_to_numpy(batch[module_id][Columns.TERMINATEDS]), + ), + truncateds=unpad_data_if_necessary( + episode_lens, + convert_to_numpy(batch[module_id][Columns.TRUNCATEDS]), + ), + gamma=self.gamma, + lambda_=self.lambda_, + ) + assert module_value_targets.shape[0] == sum(episode_lens) + + module_advantages = module_value_targets - module_vf_preds + # Drop vf-preds, not needed in loss. Note that in the PPORLModule, vf-preds + # are recomputed with each `forward_train` call anyway. + # Standardize advantages (used for more stable and better weighted + # policy gradient computations). + module_advantages = (module_advantages - module_advantages.mean()) / max( + 1e-4, module_advantages.std() + ) + + # Zero-pad the new computations, if necessary. + if module.is_stateful(): + module_advantages = np.stack( + split_and_zero_pad_n_episodes( + module_advantages, + episode_lens=episode_lens, + max_seq_len=module.model_config["max_seq_len"], + ), + axis=0, + ) + module_value_targets = np.stack( + split_and_zero_pad_n_episodes( + module_value_targets, + episode_lens=episode_lens, + max_seq_len=module.model_config["max_seq_len"], + ), + axis=0, + ) + batch[module_id][Postprocessing.ADVANTAGES] = module_advantages + batch[module_id][Postprocessing.VALUE_TARGETS] = module_value_targets + + # Convert all GAE results to tensors. + if self._numpy_to_tensor_connector is None: + self._numpy_to_tensor_connector = NumpyToTensor( + as_learner_connector=True, device=device + ) + tensor_results = self._numpy_to_tensor_connector( + rl_module=rl_module, + batch={ + mid: { + Postprocessing.ADVANTAGES: module_batch[Postprocessing.ADVANTAGES], + Postprocessing.VALUE_TARGETS: ( + module_batch[Postprocessing.VALUE_TARGETS] + ), + } + for mid, module_batch in batch.items() + if vf_preds[mid] is not None + }, + episodes=episodes, + ) + # Move converted tensors back to `batch`. + for mid, module_batch in tensor_results.items(): + batch[mid].update(module_batch) + + return batch diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..31740593997259b077f65a5c9ec04f8431fc9af5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py @@ -0,0 +1,7 @@ +from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2 +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class LearnerConnectorPipeline(ConnectorPipelineV2): + pass diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/registry.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..8efe64515eea485a13799330260758a68a11e21b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/registry.py @@ -0,0 +1,46 @@ +"""Registry of connector names for global access.""" +from typing import Any + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.connectors.connector import Connector, ConnectorContext + + +ALL_CONNECTORS = dict() + + +@OldAPIStack +def register_connector(name: str, cls: Connector): + """Register a connector for use with RLlib. + + Args: + name: Name to register. + cls: Callable that creates an env. + """ + if name in ALL_CONNECTORS: + return + + if not issubclass(cls, Connector): + raise TypeError("Can only register Connector type.", cls) + + # Record it in local registry in case we need to register everything + # again in the global registry, for example in the event of cluster + # restarts. + ALL_CONNECTORS[name] = cls + + +@OldAPIStack +def get_connector(name: str, ctx: ConnectorContext, params: Any = None) -> Connector: + # TODO(jungong) : switch the order of parameters man!! + """Get a connector by its name and serialized config. + + Args: + name: name of the connector. + ctx: Connector context. + params: serialized parameters of the connector. + + Returns: + Constructed connector. + """ + if name not in ALL_CONNECTORS: + raise NameError("connector not found.", name) + return ALL_CONNECTORS[name].from_state(ctx, params) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/connectors/util.py b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/util.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ffbcea29d6ca13985303b9a24723c1cd6a23ab --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/connectors/util.py @@ -0,0 +1,170 @@ +import logging +from typing import Any, Tuple, TYPE_CHECKING + +from ray.rllib.connectors.action.clip import ClipActionsConnector +from ray.rllib.connectors.action.immutable import ImmutableActionsConnector +from ray.rllib.connectors.action.lambdas import ConvertToNumpyConnector +from ray.rllib.connectors.action.normalize import NormalizeActionsConnector +from ray.rllib.connectors.action.pipeline import ActionConnectorPipeline +from ray.rllib.connectors.agent.clip_reward import ClipRewardAgentConnector +from ray.rllib.connectors.agent.obs_preproc import ObsPreprocessorConnector +from ray.rllib.connectors.agent.pipeline import AgentConnectorPipeline +from ray.rllib.connectors.agent.state_buffer import StateBufferConnector +from ray.rllib.connectors.agent.view_requirement import ViewRequirementAgentConnector +from ray.rllib.connectors.connector import Connector, ConnectorContext +from ray.rllib.connectors.registry import get_connector +from ray.rllib.connectors.agent.mean_std_filter import ( + MeanStdObservationFilterAgentConnector, + ConcurrentMeanStdObservationFilterAgentConnector, +) +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.connectors.agent.synced_filter import SyncedFilterAgentConnector + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.policy.policy import Policy + +logger = logging.getLogger(__name__) + + +def __preprocessing_enabled(config: "AlgorithmConfig"): + if config._disable_preprocessor_api: + return False + # Same conditions as in RolloutWorker.__init__. + if config.is_atari and config.preprocessor_pref == "deepmind": + return False + if config.preprocessor_pref is None: + return False + return True + + +def __clip_rewards(config: "AlgorithmConfig"): + # Same logic as in RolloutWorker.__init__. + # We always clip rewards for Atari games. + return config.clip_rewards or config.is_atari + + +@OldAPIStack +def get_agent_connectors_from_config( + ctx: ConnectorContext, + config: "AlgorithmConfig", +) -> AgentConnectorPipeline: + connectors = [] + + clip_rewards = __clip_rewards(config) + if clip_rewards is True: + connectors.append(ClipRewardAgentConnector(ctx, sign=True)) + elif type(clip_rewards) == float: + connectors.append(ClipRewardAgentConnector(ctx, limit=abs(clip_rewards))) + + if __preprocessing_enabled(config): + connectors.append(ObsPreprocessorConnector(ctx)) + + # Filters should be after observation preprocessing + filter_connector = get_synced_filter_connector( + ctx, + ) + # Configuration option "NoFilter" results in `filter_connector==None`. + if filter_connector: + connectors.append(filter_connector) + + connectors.extend( + [ + StateBufferConnector(ctx), + ViewRequirementAgentConnector(ctx), + ] + ) + + return AgentConnectorPipeline(ctx, connectors) + + +@OldAPIStack +def get_action_connectors_from_config( + ctx: ConnectorContext, + config: "AlgorithmConfig", +) -> ActionConnectorPipeline: + """Default list of action connectors to use for a new policy. + + Args: + ctx: context used to create connectors. + config: The AlgorithmConfig object. + """ + connectors = [ConvertToNumpyConnector(ctx)] + if config.get("normalize_actions", False): + connectors.append(NormalizeActionsConnector(ctx)) + if config.get("clip_actions", False): + connectors.append(ClipActionsConnector(ctx)) + connectors.append(ImmutableActionsConnector(ctx)) + return ActionConnectorPipeline(ctx, connectors) + + +@OldAPIStack +def create_connectors_for_policy(policy: "Policy", config: "AlgorithmConfig"): + """Util to create agent and action connectors for a Policy. + + Args: + policy: Policy instance. + config: Algorithm config dict. + """ + ctx: ConnectorContext = ConnectorContext.from_policy(policy) + + assert ( + policy.agent_connectors is None and policy.action_connectors is None + ), "Can not create connectors for a policy that already has connectors." + + policy.agent_connectors = get_agent_connectors_from_config(ctx, config) + policy.action_connectors = get_action_connectors_from_config(ctx, config) + + logger.info("Using connectors:") + logger.info(policy.agent_connectors.__str__(indentation=4)) + logger.info(policy.action_connectors.__str__(indentation=4)) + + +@OldAPIStack +def restore_connectors_for_policy( + policy: "Policy", connector_config: Tuple[str, Tuple[Any]] +) -> Connector: + """Util to create connector for a Policy based on serialized config. + + Args: + policy: Policy instance. + connector_config: Serialized connector config. + """ + ctx: ConnectorContext = ConnectorContext.from_policy(policy) + name, params = connector_config + return get_connector(name, ctx, params) + + +# We need this filter selection mechanism temporarily to remain compatible to old API +@OldAPIStack +def get_synced_filter_connector(ctx: ConnectorContext): + filter_specifier = ctx.config.get("observation_filter") + if filter_specifier == "MeanStdFilter": + return MeanStdObservationFilterAgentConnector(ctx, clip=None) + elif filter_specifier == "ConcurrentMeanStdFilter": + return ConcurrentMeanStdObservationFilterAgentConnector(ctx, clip=None) + elif filter_specifier == "NoFilter": + return None + else: + raise Exception("Unknown observation_filter: " + str(filter_specifier)) + + +@OldAPIStack +def maybe_get_filters_for_syncing(rollout_worker, policy_id): + # As long as the historic filter synchronization mechanism is in + # place, we need to put filters into self.filters so that they get + # synchronized + policy = rollout_worker.policy_map[policy_id] + if not policy.agent_connectors: + return + + filter_connectors = policy.agent_connectors[SyncedFilterAgentConnector] + # There can only be one filter at a time + if not filter_connectors: + return + + assert len(filter_connectors) == 1, ( + "ConnectorPipeline has multiple connectors of type " + "SyncedFilterAgentConnector but can only have one." + ) + rollout_worker.filters[policy_id] = filter_connectors[0].filter diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d7b5b537e5e80e39ceb9bc44b79560067f225e4 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e181927e64548c50cf425154c9349861fb28ac65 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee9cc55d4b0ad8897c80d8435389bed7e84ce2cb Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bee972b12b349e397a3fa33bd3a4eae18b7e49ab Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dacbbe18816aee6d70eca33bb2663991839007e3 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/framework.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/framework.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b1ad59445bcba57a7a14a2a22942fcde5df6e0a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/framework.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306e56aa716d9d37e51e656c0fc5d3464069df7f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/images.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/images.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50cd17c5068896305dcc654aad04c3f0bf97092c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/images.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4900b6e93992028242037dadcc82e61d0852f4f5 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/memory.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/memory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ee0eaa37891b3c83c66ff7e2386b52f5896bb3 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/memory.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2ae356d4f2248f1c31e6293238634a58141820e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcf1a5b66ae3bcc81e2c357d8a3ed953e7bd0248 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63297afbdae65667ef9cc5809c2dc334da99bddc Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22b6f953ca8a88e636295391ad662364d3ec5b72 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/typing.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/typing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43c34fb59dfaacac825a2083864b0ce08c23b8a4 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/typing.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58503926968563c0dfcf6f1cf95ed04ca1a92cf1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__init__.py @@ -0,0 +1,15 @@ +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.schedules.constant_schedule import ConstantSchedule +from ray.rllib.utils.schedules.linear_schedule import LinearSchedule +from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule +from ray.rllib.utils.schedules.polynomial_schedule import PolynomialSchedule +from ray.rllib.utils.schedules.exponential_schedule import ExponentialSchedule + +__all__ = [ + "ConstantSchedule", + "ExponentialSchedule", + "LinearSchedule", + "Schedule", + "PiecewiseSchedule", + "PolynomialSchedule", +] diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6a83ae754e27341e3a6b00f5dc592fdc3b9e4ad Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb782ae6c42bbf350be9f3f70297057f16860a90 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52ea45067748c76d86931b6191cb08baeca6464c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..911648d934d2e00aee2be57f743f9b1df48bafbc Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3d5dd9f2c9cac56527bff47153ebd726f1055db Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60289ce9a15b7126a41951689ca4af2d887f8bc7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..708e61a79ec9dabad30909b4f948ae48ff4da998 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2989d263033f3436a7d830e629c01ca7374d745f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/constant_schedule.py b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/constant_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad58e266f8d3e21144daae1c251cd2333b85907 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/constant_schedule.py @@ -0,0 +1,32 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class ConstantSchedule(Schedule): + """A Schedule where the value remains constant over time.""" + + def __init__(self, value: float, framework: Optional[str] = None): + """Initializes a ConstantSchedule instance. + + Args: + value: The constant value to return, independently of time. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + """ + super().__init__(framework=framework) + self._v = value + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + return self._v + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + return tf.constant(self._v) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..4aafac19470baa3081d06a5a3bc4cbd18d76e384 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py @@ -0,0 +1,50 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +torch, _ = try_import_torch() + + +@OldAPIStack +class ExponentialSchedule(Schedule): + """Exponential decay schedule from `initial_p` to `final_p`. + + Reduces output over `schedule_timesteps`. After this many time steps + always returns `final_p`. + """ + + def __init__( + self, + schedule_timesteps: int, + framework: Optional[str] = None, + initial_p: float = 1.0, + decay_rate: float = 0.1, + ): + """Initializes a ExponentialSchedule instance. + + Args: + schedule_timesteps: Number of time steps for which to + linearly anneal initial_p to final_p. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + initial_p: Initial output value. + decay_rate: The percentage of the original value after + 100% of the time has been reached (see formula above). + >0.0: The smaller the decay-rate, the stronger the decay. + 1.0: No decay at all. + """ + super().__init__(framework=framework) + assert schedule_timesteps > 0 + self.schedule_timesteps = schedule_timesteps + self.initial_p = initial_p + self.decay_rate = decay_rate + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + """Returns the result of: initial_p * decay_rate ** (`t`/t_max).""" + if self.framework == "torch" and torch and isinstance(t, torch.Tensor): + t = t.float() + return self.initial_p * self.decay_rate ** (t / self.schedule_timesteps) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/linear_schedule.py b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/linear_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..d23647b9bbebf757f002444bb231a9b78d863a47 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/linear_schedule.py @@ -0,0 +1,18 @@ +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.schedules.polynomial_schedule import PolynomialSchedule + + +@OldAPIStack +class LinearSchedule(PolynomialSchedule): + """Linear interpolation between `initial_p` and `final_p`. + + Uses `PolynomialSchedule` with power=1.0. + + + The formula is: + value = `final_p` + (`initial_p` - `final_p`) * (1 - `t`/t_max) + """ + + def __init__(self, **kwargs): + """Initializes a LinearSchedule instance.""" + super().__init__(power=1.0, **kwargs) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4b15478b3f21bfa8612bdd5e39f952d0801086 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py @@ -0,0 +1,105 @@ +from typing import Callable, List, Optional, Tuple + +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType +from ray.util.annotations import DeveloperAPI + +tf1, tf, tfv = try_import_tf() + + +def _linear_interpolation(left, right, alpha): + return left + alpha * (right - left) + + +@DeveloperAPI +class PiecewiseSchedule(Schedule): + """Implements a Piecewise Scheduler.""" + + def __init__( + self, + endpoints: List[Tuple[int, float]], + framework: Optional[str] = None, + interpolation: Callable[ + [TensorType, TensorType, TensorType], TensorType + ] = _linear_interpolation, + outside_value: Optional[float] = None, + ): + """Initializes a PiecewiseSchedule instance. + + Args: + endpoints: A list of tuples + `(t, value)` such that the output + is an interpolation (given by the `interpolation` callable) + between two values. + E.g. + t=400 and endpoints=[(0, 20.0),(500, 30.0)] + output=20.0 + 0.8 * (30.0 - 20.0) = 28.0 + NOTE: All the values for time must be sorted in an increasing + order. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + interpolation: A function that takes the left-value, + the right-value and an alpha interpolation parameter + (0.0=only left value, 1.0=only right value), which is the + fraction of distance from left endpoint to right endpoint. + outside_value: If t in call to `value` is + outside of all the intervals in `endpoints` this value is + returned. If None then an AssertionError is raised when outside + value is requested. + """ + super().__init__(framework=framework) + + idxes = [e[0] for e in endpoints] + assert idxes == sorted(idxes) + self.interpolation = interpolation + self.outside_value = outside_value + self.endpoints = [(int(e[0]), float(e[1])) for e in endpoints] + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + # Find t in our list of endpoints. + for (l_t, l), (r_t, r) in zip(self.endpoints[:-1], self.endpoints[1:]): + # When found, return an interpolation (default: linear). + if l_t <= t < r_t: + alpha = float(t - l_t) / (r_t - l_t) + return self.interpolation(l, r, alpha) + + # t does not belong to any of the pieces, return `self.outside_value`. + assert self.outside_value is not None + return self.outside_value + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + assert self.outside_value is not None, ( + "tf-version of PiecewiseSchedule requires `outside_value` to be " + "provided!" + ) + + endpoints = tf.cast(tf.stack([e[0] for e in self.endpoints] + [-1]), tf.int64) + + # Create all possible interpolation results. + results_list = [] + for (l_t, l), (r_t, r) in zip(self.endpoints[:-1], self.endpoints[1:]): + alpha = tf.cast(t - l_t, tf.float32) / tf.cast(r_t - l_t, tf.float32) + results_list.append(self.interpolation(l, r, alpha)) + # If t does not belong to any of the pieces, return `outside_value`. + results_list.append(self.outside_value) + results_list = tf.stack(results_list) + + # Return correct results tensor depending on where we find t. + def _cond(i, x): + x = tf.cast(x, tf.int64) + return tf.logical_not( + tf.logical_or( + tf.equal(endpoints[i + 1], -1), + tf.logical_and(endpoints[i] <= x, x < endpoints[i + 1]), + ) + ) + + def _body(i, x): + return (i + 1, t) + + idx_and_t = tf.while_loop(_cond, _body, [tf.constant(0, dtype=tf.int64), t]) + return results_list[idx_and_t[0]] diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..17a2820d9af811d8c647f467501cd906f2bbdd9d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py @@ -0,0 +1,67 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class PolynomialSchedule(Schedule): + """Polynomial interpolation between `initial_p` and `final_p`. + + Over `schedule_timesteps`. After this many time steps, always returns + `final_p`. + """ + + def __init__( + self, + schedule_timesteps: int, + final_p: float, + framework: Optional[str], + initial_p: float = 1.0, + power: float = 2.0, + ): + """Initializes a PolynomialSchedule instance. + + Args: + schedule_timesteps: Number of time steps for which to + linearly anneal initial_p to final_p + final_p: Final output value. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + initial_p: Initial output value. + power: The exponent to use (default: quadratic). + """ + super().__init__(framework=framework) + assert schedule_timesteps > 0 + self.schedule_timesteps = schedule_timesteps + self.final_p = final_p + self.initial_p = initial_p + self.power = power + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + """Returns the result of: + final_p + (initial_p - final_p) * (1 - `t`/t_max) ** power + """ + if self.framework == "torch" and torch and isinstance(t, torch.Tensor): + t = t.float() + t = min(t, self.schedule_timesteps) + return ( + self.final_p + + (self.initial_p - self.final_p) + * (1.0 - (t / self.schedule_timesteps)) ** self.power + ) + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + t = tf.math.minimum(t, self.schedule_timesteps) + return ( + self.final_p + + (self.initial_p - self.final_p) + * (1.0 - (t / self.schedule_timesteps)) ** self.power + ) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/schedule.py b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5b113ff5a9c1d328cdc0db0ec8197d4efa8b0f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/schedule.py @@ -0,0 +1,73 @@ +from abc import ABCMeta, abstractmethod +from typing import Any, Union + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class Schedule(metaclass=ABCMeta): + """Schedule classes implement various time-dependent scheduling schemas. + + - Constant behavior. + - Linear decay. + - Piecewise decay. + - Exponential decay. + + Useful for backend-agnostic rate/weight changes for learning rates, + exploration epsilons, beta parameters for prioritized replay, loss weights + decay, etc.. + + Each schedule can be called directly with the `t` (absolute time step) + value and returns the value dependent on the Schedule and the passed time. + """ + + def __init__(self, framework): + self.framework = framework + + def value(self, t: Union[int, TensorType]) -> Any: + """Generates the value given a timestep (based on schedule's logic). + + Args: + t: The time step. This could be a tf.Tensor. + + Returns: + The calculated value depending on the schedule and `t`. + """ + if self.framework in ["tf2", "tf"]: + return self._tf_value_op(t) + return self._value(t) + + def __call__(self, t: Union[int, TensorType]) -> Any: + """Simply calls self.value(t). Implemented to make Schedules callable.""" + return self.value(t) + + @abstractmethod + def _value(self, t: Union[int, TensorType]) -> Any: + """ + Returns the value based on a time step input. + + Args: + t: The time step. This could be a tf.Tensor. + + Returns: + The calculated value depending on the schedule and `t`. + """ + raise NotImplementedError + + def _tf_value_op(self, t: TensorType) -> TensorType: + """ + Returns the tf-op that calculates the value based on a time step input. + + Args: + t: The time step op (int tf.Tensor). + + Returns: + The calculated value depending on the schedule and `t`. + """ + # By default (most of the time), tf should work with python code. + # Override only if necessary. + return self._value(t) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..231b25c71ea5fd74c889fdc8f501bd1c3f29a786 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py @@ -0,0 +1,167 @@ +from typing import Optional + +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule +from ray.rllib.utils.typing import LearningRateOrSchedule, TensorType +from ray.util.annotations import DeveloperAPI + + +_, tf, _ = try_import_tf() +torch, _ = try_import_torch() + + +@DeveloperAPI +class Scheduler: + """Class to manage a scheduled (framework-dependent) tensor variable. + + Uses the PiecewiseSchedule (for maximum configuration flexibility) + """ + + def __init__( + self, + *, + fixed_value_or_schedule: LearningRateOrSchedule, + framework: str = "torch", + device: Optional[str] = None, + ): + """Initializes a Scheduler instance. + + Args: + fixed_value_or_schedule: A fixed, constant value (in case no schedule should + be used) or a schedule configuration in the format of + [[timestep, value], [timestep, value], ...] + Intermediary timesteps will be assigned to linerarly interpolated + values. A schedule config's first entry must + start with timestep 0, i.e.: [[0, initial_value], [...]]. + framework: The framework string, for which to create the tensor variable + that hold the current value. This is the variable that can be used in + the graph, e.g. in a loss function. + device: Optional device (for torch) to place the tensor variable on. + """ + self.framework = framework + self.device = device + self.use_schedule = isinstance(fixed_value_or_schedule, (list, tuple)) + + if self.use_schedule: + # Custom schedule, based on list of + # ([ts], [value to be reached by ts])-tuples. + self._schedule = PiecewiseSchedule( + fixed_value_or_schedule, + outside_value=fixed_value_or_schedule[-1][-1], + framework=None, + ) + # As initial tensor valie, use the first timestep's (must be 0) value. + self._curr_value = self._create_tensor_variable( + initial_value=fixed_value_or_schedule[0][1] + ) + + # If no schedule, pin (fix) given value. + else: + self._curr_value = fixed_value_or_schedule + + @staticmethod + def validate( + *, + fixed_value_or_schedule: LearningRateOrSchedule, + setting_name: str, + description: str, + ) -> None: + """Performs checking of a certain schedule configuration. + + The first entry in `value_or_schedule` (if it's not a fixed value) must have a + timestep of 0. + + Args: + fixed_value_or_schedule: A fixed, constant value (in case no schedule should + be used) or a schedule configuration in the format of + [[timestep, value], [timestep, value], ...] + Intermediary timesteps will be assigned to linerarly interpolated + values. A schedule config's first entry must + start with timestep 0, i.e.: [[0, initial_value], [...]]. + setting_name: The property name of the schedule setting (within a config), + e.g. `lr` or `entropy_coeff`. + description: A full text description of the property that's being scheduled, + e.g. `learning rate`. + + Raises: + ValueError: In case, errors are found in the schedule's format. + """ + if ( + isinstance(fixed_value_or_schedule, (int, float)) + or fixed_value_or_schedule is None + ): + return + + if not isinstance(fixed_value_or_schedule, (list, tuple)) or ( + len(fixed_value_or_schedule) < 2 + ): + raise ValueError( + f"Invalid `{setting_name}` ({fixed_value_or_schedule}) specified! " + f"Must be a list of at least 2 tuples, each of the form " + f"(`timestep`, `{description} to reach`), e.g. " + "`[(0, 0.001), (1e6, 0.0001), (2e6, 0.00005)]`." + ) + elif fixed_value_or_schedule[0][0] != 0: + raise ValueError( + f"When providing a `{setting_name}`, the first timestep must be 0 " + f"and the corresponding lr value is the initial {description}! You " + f"provided ts={fixed_value_or_schedule[0][0]} {description}=" + f"{fixed_value_or_schedule[0][1]}." + ) + + def get_current_value(self) -> TensorType: + """Returns the current value (as a tensor variable). + + This method should be used in loss functions of other (in-graph) places + where the current value is needed. + + Returns: + The tensor variable (holding the current value to be used). + """ + return self._curr_value + + def update(self, timestep: int) -> float: + """Updates the underlying (framework specific) tensor variable. + + In case of a fixed value, this method does nothing and only returns the fixed + value as-is. + + Args: + timestep: The current timestep that the update might depend on. + + Returns: + The current value of the tensor variable as a python float. + """ + if self.use_schedule: + python_value = self._schedule.value(t=timestep) + if self.framework == "torch": + self._curr_value.data = torch.tensor(python_value) + else: + self._curr_value.assign(python_value) + else: + python_value = self._curr_value + + return python_value + + def _create_tensor_variable(self, initial_value: float) -> TensorType: + """Creates a framework-specific tensor variable to be scheduled. + + Args: + initial_value: The initial (float) value for the variable to hold. + + Returns: + The created framework-specific tensor variable. + """ + if self.framework == "torch": + return torch.tensor( + initial_value, + requires_grad=False, + dtype=torch.float32, + device=self.device, + ) + else: + return tf.Variable( + initial_value, + trainable=False, + dtype=tf.float32, + )