Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/clip_reward.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/env_sampling.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/lambdas.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/mean_std_filter.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/state_buffer.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/synced_filter.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/view_requirement.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/clip_reward.py +56 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/env_sampling.py +30 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/lambdas.py +86 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/mean_std_filter.py +187 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/obs_preproc.py +69 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/pipeline.py +72 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/state_buffer.py +120 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/synced_filter.py +52 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/view_requirement.py +135 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector.py +478 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_pipeline_v2.py +381 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_v2.py +1013 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__init__.py +36 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/env_to_module_pipeline.py +32 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py +80 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py +131 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__init__.py +37 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_columns_from_episodes_to_train_batch.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_next_observations_from_episodes_to_train_batch.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py +165 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py +103 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py +168 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/frame_stacking.py +6 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/general_advantage_estimation.py +195 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py +7 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/registry.py +46 -0
- vllm/lib/python3.10/site-packages/ray/rllib/connectors/util.py +170 -0
- vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/framework.cpython-310.pyc +0 -0
vllm/lib/python3.10/site-packages/ray/rllib/connectors/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (176 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/clip_reward.cpython-310.pyc
ADDED
|
Binary file (1.97 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/env_sampling.cpython-310.pyc
ADDED
|
Binary file (1.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/lambdas.cpython-310.pyc
ADDED
|
Binary file (2.82 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/mean_std_filter.cpython-310.pyc
ADDED
|
Binary file (6.43 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-310.pyc
ADDED
|
Binary file (2.74 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-310.pyc
ADDED
|
Binary file (2.86 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/state_buffer.cpython-310.pyc
ADDED
|
Binary file (4.01 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/synced_filter.cpython-310.pyc
ADDED
|
Binary file (2.25 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/__pycache__/view_requirement.cpython-310.pyc
ADDED
|
Binary file (4.17 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/clip_reward.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from ray.rllib.connectors.connector import (
|
| 6 |
+
AgentConnector,
|
| 7 |
+
ConnectorContext,
|
| 8 |
+
)
|
| 9 |
+
from ray.rllib.connectors.registry import register_connector
|
| 10 |
+
from ray.rllib.policy.sample_batch import SampleBatch
|
| 11 |
+
from ray.rllib.utils.typing import AgentConnectorDataType
|
| 12 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@OldAPIStack
|
| 16 |
+
class ClipRewardAgentConnector(AgentConnector):
|
| 17 |
+
def __init__(self, ctx: ConnectorContext, sign=False, limit=None):
|
| 18 |
+
super().__init__(ctx)
|
| 19 |
+
assert (
|
| 20 |
+
not sign or not limit
|
| 21 |
+
), "should not enable both sign and limit reward clipping."
|
| 22 |
+
self.sign = sign
|
| 23 |
+
self.limit = limit
|
| 24 |
+
|
| 25 |
+
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
|
| 26 |
+
d = ac_data.data
|
| 27 |
+
assert (
|
| 28 |
+
type(d) == dict
|
| 29 |
+
), "Single agent data must be of type Dict[str, TensorStructType]"
|
| 30 |
+
|
| 31 |
+
if SampleBatch.REWARDS not in d:
|
| 32 |
+
# Nothing to clip. May happen for initial obs.
|
| 33 |
+
return ac_data
|
| 34 |
+
|
| 35 |
+
if self.sign:
|
| 36 |
+
d[SampleBatch.REWARDS] = np.sign(d[SampleBatch.REWARDS])
|
| 37 |
+
elif self.limit:
|
| 38 |
+
d[SampleBatch.REWARDS] = np.clip(
|
| 39 |
+
d[SampleBatch.REWARDS],
|
| 40 |
+
a_min=-self.limit,
|
| 41 |
+
a_max=self.limit,
|
| 42 |
+
)
|
| 43 |
+
return ac_data
|
| 44 |
+
|
| 45 |
+
def to_state(self):
|
| 46 |
+
return ClipRewardAgentConnector.__name__, {
|
| 47 |
+
"sign": self.sign,
|
| 48 |
+
"limit": self.limit,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def from_state(ctx: ConnectorContext, params: Any):
|
| 53 |
+
return ClipRewardAgentConnector(ctx, **params)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
register_connector(ClipRewardAgentConnector.__name__, ClipRewardAgentConnector)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/env_sampling.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
from ray.rllib.connectors.connector import (
|
| 4 |
+
AgentConnector,
|
| 5 |
+
ConnectorContext,
|
| 6 |
+
)
|
| 7 |
+
from ray.rllib.connectors.registry import register_connector
|
| 8 |
+
from ray.rllib.utils.typing import AgentConnectorDataType
|
| 9 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@OldAPIStack
|
| 13 |
+
class EnvSamplingAgentConnector(AgentConnector):
|
| 14 |
+
def __init__(self, ctx: ConnectorContext, sign=False, limit=None):
|
| 15 |
+
super().__init__(ctx)
|
| 16 |
+
self.observation_space = ctx.observation_space
|
| 17 |
+
|
| 18 |
+
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
|
| 19 |
+
# EnvSamplingAgentConnector is a no-op connector.
|
| 20 |
+
return ac_data
|
| 21 |
+
|
| 22 |
+
def to_state(self):
|
| 23 |
+
return EnvSamplingAgentConnector.__name__, {}
|
| 24 |
+
|
| 25 |
+
@staticmethod
|
| 26 |
+
def from_state(ctx: ConnectorContext, params: Any):
|
| 27 |
+
return EnvSamplingAgentConnector(ctx, **params)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
register_connector(EnvSamplingAgentConnector.__name__, EnvSamplingAgentConnector)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/lambdas.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, Type
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import tree # dm_tree
|
| 5 |
+
|
| 6 |
+
from ray.rllib.connectors.connector import (
|
| 7 |
+
AgentConnector,
|
| 8 |
+
ConnectorContext,
|
| 9 |
+
)
|
| 10 |
+
from ray.rllib.connectors.registry import register_connector
|
| 11 |
+
from ray.rllib.policy.sample_batch import SampleBatch
|
| 12 |
+
from ray.rllib.utils.typing import (
|
| 13 |
+
AgentConnectorDataType,
|
| 14 |
+
AgentConnectorsOutput,
|
| 15 |
+
)
|
| 16 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@OldAPIStack
|
| 20 |
+
def register_lambda_agent_connector(
|
| 21 |
+
name: str, fn: Callable[[Any], Any]
|
| 22 |
+
) -> Type[AgentConnector]:
|
| 23 |
+
"""A util to register any simple transforming function as an AgentConnector
|
| 24 |
+
|
| 25 |
+
The only requirement is that fn should take a single data object and return
|
| 26 |
+
a single data object.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
name: Name of the resulting actor connector.
|
| 30 |
+
fn: The function that transforms env / agent data.
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
A new AgentConnector class that transforms data using fn.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
class LambdaAgentConnector(AgentConnector):
|
| 37 |
+
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
|
| 38 |
+
return AgentConnectorDataType(
|
| 39 |
+
ac_data.env_id, ac_data.agent_id, fn(ac_data.data)
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
def to_state(self):
|
| 43 |
+
return name, None
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def from_state(ctx: ConnectorContext, params: Any):
|
| 47 |
+
return LambdaAgentConnector(ctx)
|
| 48 |
+
|
| 49 |
+
LambdaAgentConnector.__name__ = name
|
| 50 |
+
LambdaAgentConnector.__qualname__ = name
|
| 51 |
+
|
| 52 |
+
register_connector(name, LambdaAgentConnector)
|
| 53 |
+
|
| 54 |
+
return LambdaAgentConnector
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@OldAPIStack
|
| 58 |
+
def flatten_data(data: AgentConnectorsOutput):
|
| 59 |
+
assert isinstance(
|
| 60 |
+
data, AgentConnectorsOutput
|
| 61 |
+
), "Single agent data must be of type AgentConnectorsOutput"
|
| 62 |
+
|
| 63 |
+
raw_dict = data.raw_dict
|
| 64 |
+
sample_batch = data.sample_batch
|
| 65 |
+
|
| 66 |
+
flattened = {}
|
| 67 |
+
for k, v in sample_batch.items():
|
| 68 |
+
if k in [SampleBatch.INFOS, SampleBatch.ACTIONS] or k.startswith("state_out_"):
|
| 69 |
+
# Do not flatten infos, actions, and state_out_ columns.
|
| 70 |
+
flattened[k] = v
|
| 71 |
+
continue
|
| 72 |
+
if v is None:
|
| 73 |
+
# Keep the same column shape.
|
| 74 |
+
flattened[k] = None
|
| 75 |
+
continue
|
| 76 |
+
flattened[k] = np.array(tree.flatten(v))
|
| 77 |
+
flattened = SampleBatch(flattened, is_training=False)
|
| 78 |
+
|
| 79 |
+
return AgentConnectorsOutput(raw_dict, flattened)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# Agent connector to build and return a flattened observation SampleBatch
|
| 83 |
+
# in addition to the original input dict.
|
| 84 |
+
FlattenDataAgentConnector = OldAPIStack(
|
| 85 |
+
register_lambda_agent_connector("FlattenDataAgentConnector", flatten_data)
|
| 86 |
+
)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/mean_std_filter.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, List
|
| 2 |
+
from gymnasium.spaces import Discrete, MultiDiscrete
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import tree
|
| 6 |
+
|
| 7 |
+
from ray.rllib.connectors.agent.synced_filter import SyncedFilterAgentConnector
|
| 8 |
+
from ray.rllib.connectors.connector import AgentConnector
|
| 9 |
+
from ray.rllib.connectors.connector import (
|
| 10 |
+
ConnectorContext,
|
| 11 |
+
)
|
| 12 |
+
from ray.rllib.connectors.registry import register_connector
|
| 13 |
+
from ray.rllib.policy.sample_batch import SampleBatch
|
| 14 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 15 |
+
from ray.rllib.utils.filter import Filter
|
| 16 |
+
from ray.rllib.utils.filter import MeanStdFilter, ConcurrentMeanStdFilter
|
| 17 |
+
from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space
|
| 18 |
+
from ray.rllib.utils.typing import AgentConnectorDataType
|
| 19 |
+
from ray.rllib.utils.filter import RunningStat
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@OldAPIStack
|
| 23 |
+
class MeanStdObservationFilterAgentConnector(SyncedFilterAgentConnector):
|
| 24 |
+
"""A connector used to mean-std-filter observations.
|
| 25 |
+
|
| 26 |
+
Incoming observations are filtered such that the output of this filter is on
|
| 27 |
+
average zero and has a standard deviation of 1. This filtering is applied
|
| 28 |
+
separately per element of the observation space.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
ctx: ConnectorContext,
|
| 34 |
+
demean: bool = True,
|
| 35 |
+
destd: bool = True,
|
| 36 |
+
clip: float = 10.0,
|
| 37 |
+
):
|
| 38 |
+
SyncedFilterAgentConnector.__init__(self, ctx)
|
| 39 |
+
# We simply use the old MeanStdFilter until non-connector env_runner is fully
|
| 40 |
+
# deprecated to avoid duplicate code
|
| 41 |
+
|
| 42 |
+
filter_shape = tree.map_structure(
|
| 43 |
+
lambda s: (
|
| 44 |
+
None
|
| 45 |
+
if isinstance(s, (Discrete, MultiDiscrete)) # noqa
|
| 46 |
+
else np.array(s.shape)
|
| 47 |
+
),
|
| 48 |
+
get_base_struct_from_space(ctx.observation_space),
|
| 49 |
+
)
|
| 50 |
+
self.filter = MeanStdFilter(filter_shape, demean=demean, destd=destd, clip=clip)
|
| 51 |
+
|
| 52 |
+
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
|
| 53 |
+
d = ac_data.data
|
| 54 |
+
assert (
|
| 55 |
+
type(d) == dict
|
| 56 |
+
), "Single agent data must be of type Dict[str, TensorStructType]"
|
| 57 |
+
if SampleBatch.OBS in d:
|
| 58 |
+
d[SampleBatch.OBS] = self.filter(
|
| 59 |
+
d[SampleBatch.OBS], update=self._is_training
|
| 60 |
+
)
|
| 61 |
+
if SampleBatch.NEXT_OBS in d:
|
| 62 |
+
d[SampleBatch.NEXT_OBS] = self.filter(
|
| 63 |
+
d[SampleBatch.NEXT_OBS], update=self._is_training
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
return ac_data
|
| 67 |
+
|
| 68 |
+
def to_state(self):
|
| 69 |
+
# Flattening is deterministic
|
| 70 |
+
flattened_rs = tree.flatten(self.filter.running_stats)
|
| 71 |
+
flattened_buffer = tree.flatten(self.filter.buffer)
|
| 72 |
+
return MeanStdObservationFilterAgentConnector.__name__, {
|
| 73 |
+
"shape": self.filter.shape,
|
| 74 |
+
"no_preprocessor": self.filter.no_preprocessor,
|
| 75 |
+
"demean": self.filter.demean,
|
| 76 |
+
"destd": self.filter.destd,
|
| 77 |
+
"clip": self.filter.clip,
|
| 78 |
+
"running_stats": [s.to_state() for s in flattened_rs],
|
| 79 |
+
"buffer": [s.to_state() for s in flattened_buffer],
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
# demean, destd, clip, and a state dict
|
| 83 |
+
@staticmethod
|
| 84 |
+
def from_state(
|
| 85 |
+
ctx: ConnectorContext,
|
| 86 |
+
params: List[Any] = None,
|
| 87 |
+
demean: bool = True,
|
| 88 |
+
destd: bool = True,
|
| 89 |
+
clip: float = 10.0,
|
| 90 |
+
):
|
| 91 |
+
connector = MeanStdObservationFilterAgentConnector(ctx, demean, destd, clip)
|
| 92 |
+
if params:
|
| 93 |
+
connector.filter.shape = params["shape"]
|
| 94 |
+
connector.filter.no_preprocessor = params["no_preprocessor"]
|
| 95 |
+
connector.filter.demean = params["demean"]
|
| 96 |
+
connector.filter.destd = params["destd"]
|
| 97 |
+
connector.filter.clip = params["clip"]
|
| 98 |
+
|
| 99 |
+
# Unflattening is deterministic
|
| 100 |
+
running_stats = [RunningStat.from_state(s) for s in params["running_stats"]]
|
| 101 |
+
connector.filter.running_stats = tree.unflatten_as(
|
| 102 |
+
connector.filter.shape, running_stats
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# Unflattening is deterministic
|
| 106 |
+
buffer = [RunningStat.from_state(s) for s in params["buffer"]]
|
| 107 |
+
connector.filter.buffer = tree.unflatten_as(connector.filter.shape, buffer)
|
| 108 |
+
|
| 109 |
+
return connector
|
| 110 |
+
|
| 111 |
+
def reset_state(self) -> None:
|
| 112 |
+
"""Creates copy of current state and resets accumulated state"""
|
| 113 |
+
if not self._is_training:
|
| 114 |
+
raise ValueError(
|
| 115 |
+
"State of {} can only be changed when trainin.".format(self.__name__)
|
| 116 |
+
)
|
| 117 |
+
self.filter.reset_buffer()
|
| 118 |
+
|
| 119 |
+
def apply_changes(self, other: "Filter", *args, **kwargs) -> None:
|
| 120 |
+
"""Updates self with state from other filter."""
|
| 121 |
+
# inline this as soon as we deprecate ordinary filter with non-connector
|
| 122 |
+
# env_runner
|
| 123 |
+
if not self._is_training:
|
| 124 |
+
raise ValueError(
|
| 125 |
+
"Changes can only be applied to {} when trainin.".format(self.__name__)
|
| 126 |
+
)
|
| 127 |
+
return self.filter.apply_changes(other, *args, **kwargs)
|
| 128 |
+
|
| 129 |
+
def copy(self) -> "Filter":
|
| 130 |
+
"""Creates a new object with same state as self.
|
| 131 |
+
|
| 132 |
+
This is a legacy Filter method that we need to keep around for now
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
A copy of self.
|
| 136 |
+
"""
|
| 137 |
+
# inline this as soon as we deprecate ordinary filter with non-connector
|
| 138 |
+
# env_runner
|
| 139 |
+
return self.filter.copy()
|
| 140 |
+
|
| 141 |
+
def sync(self, other: "AgentConnector") -> None:
|
| 142 |
+
"""Copies all state from other filter to self."""
|
| 143 |
+
# inline this as soon as we deprecate ordinary filter with non-connector
|
| 144 |
+
# env_runner
|
| 145 |
+
if not self._is_training:
|
| 146 |
+
raise ValueError(
|
| 147 |
+
"{} can only be synced when trainin.".format(self.__name__)
|
| 148 |
+
)
|
| 149 |
+
return self.filter.sync(other.filter)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@OldAPIStack
|
| 153 |
+
class ConcurrentMeanStdObservationFilterAgentConnector(
|
| 154 |
+
MeanStdObservationFilterAgentConnector
|
| 155 |
+
):
|
| 156 |
+
"""A concurrent version of the MeanStdObservationFilterAgentConnector.
|
| 157 |
+
|
| 158 |
+
This version's filter has all operations wrapped by a threading.RLock.
|
| 159 |
+
It can therefore be safely used by multiple threads.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def __init__(self, ctx: ConnectorContext, demean=True, destd=True, clip=10.0):
|
| 163 |
+
SyncedFilterAgentConnector.__init__(self, ctx)
|
| 164 |
+
# We simply use the old MeanStdFilter until non-connector env_runner is fully
|
| 165 |
+
# deprecated to avoid duplicate code
|
| 166 |
+
|
| 167 |
+
filter_shape = tree.map_structure(
|
| 168 |
+
lambda s: (
|
| 169 |
+
None
|
| 170 |
+
if isinstance(s, (Discrete, MultiDiscrete)) # noqa
|
| 171 |
+
else np.array(s.shape)
|
| 172 |
+
),
|
| 173 |
+
get_base_struct_from_space(ctx.observation_space),
|
| 174 |
+
)
|
| 175 |
+
self.filter = ConcurrentMeanStdFilter(
|
| 176 |
+
filter_shape, demean=True, destd=True, clip=10.0
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
register_connector(
|
| 181 |
+
MeanStdObservationFilterAgentConnector.__name__,
|
| 182 |
+
MeanStdObservationFilterAgentConnector,
|
| 183 |
+
)
|
| 184 |
+
register_connector(
|
| 185 |
+
ConcurrentMeanStdObservationFilterAgentConnector.__name__,
|
| 186 |
+
ConcurrentMeanStdObservationFilterAgentConnector,
|
| 187 |
+
)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/obs_preproc.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
from ray.rllib.connectors.connector import (
|
| 4 |
+
AgentConnector,
|
| 5 |
+
ConnectorContext,
|
| 6 |
+
)
|
| 7 |
+
from ray.rllib.connectors.registry import register_connector
|
| 8 |
+
from ray.rllib.models.preprocessors import get_preprocessor, NoPreprocessor
|
| 9 |
+
from ray.rllib.policy.sample_batch import SampleBatch
|
| 10 |
+
from ray.rllib.utils.typing import AgentConnectorDataType
|
| 11 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@OldAPIStack
|
| 15 |
+
class ObsPreprocessorConnector(AgentConnector):
|
| 16 |
+
"""A connector that wraps around existing RLlib observation preprocessors.
|
| 17 |
+
|
| 18 |
+
This includes:
|
| 19 |
+
- OneHotPreprocessor for Discrete and Multi-Discrete spaces.
|
| 20 |
+
- GenericPixelPreprocessor and AtariRamPreprocessor for Atari spaces.
|
| 21 |
+
- TupleFlatteningPreprocessor and DictFlatteningPreprocessor for flattening
|
| 22 |
+
arbitrary nested input observations.
|
| 23 |
+
- RepeatedValuesPreprocessor for padding observations from RLlib Repeated
|
| 24 |
+
observation space.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, ctx: ConnectorContext):
|
| 28 |
+
super().__init__(ctx)
|
| 29 |
+
|
| 30 |
+
if hasattr(ctx.observation_space, "original_space"):
|
| 31 |
+
# ctx.observation_space is the space this Policy deals with.
|
| 32 |
+
# We need to preprocess data from the original observation space here.
|
| 33 |
+
obs_space = ctx.observation_space.original_space
|
| 34 |
+
else:
|
| 35 |
+
obs_space = ctx.observation_space
|
| 36 |
+
|
| 37 |
+
self._preprocessor = get_preprocessor(obs_space)(
|
| 38 |
+
obs_space, ctx.config.get("model", {})
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def is_identity(self):
|
| 42 |
+
"""Returns whether this preprocessor connector is a no-op preprocessor."""
|
| 43 |
+
return isinstance(self._preprocessor, NoPreprocessor)
|
| 44 |
+
|
| 45 |
+
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
|
| 46 |
+
d = ac_data.data
|
| 47 |
+
assert type(d) == dict, (
|
| 48 |
+
"Single agent data must be of type Dict[str, TensorStructType] but is of "
|
| 49 |
+
"type {}".format(type(d))
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
if SampleBatch.OBS in d:
|
| 53 |
+
d[SampleBatch.OBS] = self._preprocessor.transform(d[SampleBatch.OBS])
|
| 54 |
+
if SampleBatch.NEXT_OBS in d:
|
| 55 |
+
d[SampleBatch.NEXT_OBS] = self._preprocessor.transform(
|
| 56 |
+
d[SampleBatch.NEXT_OBS]
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
return ac_data
|
| 60 |
+
|
| 61 |
+
def to_state(self):
|
| 62 |
+
return ObsPreprocessorConnector.__name__, None
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def from_state(ctx: ConnectorContext, params: Any):
|
| 66 |
+
return ObsPreprocessorConnector(ctx)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
register_connector(ObsPreprocessorConnector.__name__, ObsPreprocessorConnector)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/pipeline.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Any, List
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
|
| 5 |
+
from ray.rllib.connectors.connector import (
|
| 6 |
+
AgentConnector,
|
| 7 |
+
Connector,
|
| 8 |
+
ConnectorContext,
|
| 9 |
+
ConnectorPipeline,
|
| 10 |
+
)
|
| 11 |
+
from ray.rllib.connectors.registry import get_connector, register_connector
|
| 12 |
+
from ray.rllib.utils.typing import ActionConnectorDataType, AgentConnectorDataType
|
| 13 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 14 |
+
from ray.util.timer import _Timer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@OldAPIStack
|
| 21 |
+
class AgentConnectorPipeline(ConnectorPipeline, AgentConnector):
|
| 22 |
+
def __init__(self, ctx: ConnectorContext, connectors: List[Connector]):
|
| 23 |
+
super().__init__(ctx, connectors)
|
| 24 |
+
self.timers = defaultdict(_Timer)
|
| 25 |
+
|
| 26 |
+
def reset(self, env_id: str):
|
| 27 |
+
for c in self.connectors:
|
| 28 |
+
c.reset(env_id)
|
| 29 |
+
|
| 30 |
+
def on_policy_output(self, output: ActionConnectorDataType):
|
| 31 |
+
for c in self.connectors:
|
| 32 |
+
c.on_policy_output(output)
|
| 33 |
+
|
| 34 |
+
def __call__(
|
| 35 |
+
self, acd_list: List[AgentConnectorDataType]
|
| 36 |
+
) -> List[AgentConnectorDataType]:
|
| 37 |
+
ret = acd_list
|
| 38 |
+
for c in self.connectors:
|
| 39 |
+
timer = self.timers[str(c)]
|
| 40 |
+
with timer:
|
| 41 |
+
ret = c(ret)
|
| 42 |
+
return ret
|
| 43 |
+
|
| 44 |
+
def to_state(self):
|
| 45 |
+
children = []
|
| 46 |
+
for c in self.connectors:
|
| 47 |
+
state = c.to_state()
|
| 48 |
+
assert isinstance(state, tuple) and len(state) == 2, (
|
| 49 |
+
"Serialized connector state must be in the format of "
|
| 50 |
+
f"Tuple[name: str, params: Any]. Instead we got {state}"
|
| 51 |
+
f"for connector {c.__name__}."
|
| 52 |
+
)
|
| 53 |
+
children.append(state)
|
| 54 |
+
return AgentConnectorPipeline.__name__, children
|
| 55 |
+
|
| 56 |
+
@staticmethod
|
| 57 |
+
def from_state(ctx: ConnectorContext, params: List[Any]):
|
| 58 |
+
assert (
|
| 59 |
+
type(params) == list
|
| 60 |
+
), "AgentConnectorPipeline takes a list of connector params."
|
| 61 |
+
connectors = []
|
| 62 |
+
for state in params:
|
| 63 |
+
try:
|
| 64 |
+
name, subparams = state
|
| 65 |
+
connectors.append(get_connector(name, ctx, subparams))
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logger.error(f"Failed to de-serialize connector state: {state}")
|
| 68 |
+
raise e
|
| 69 |
+
return AgentConnectorPipeline(ctx, connectors)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
register_connector(AgentConnectorPipeline.__name__, AgentConnectorPipeline)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/state_buffer.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
import logging
|
| 3 |
+
import pickle
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from ray.rllib.utils.annotations import override
|
| 8 |
+
import tree # dm_tree
|
| 9 |
+
|
| 10 |
+
from ray.rllib.connectors.connector import (
|
| 11 |
+
AgentConnector,
|
| 12 |
+
Connector,
|
| 13 |
+
ConnectorContext,
|
| 14 |
+
)
|
| 15 |
+
from ray import cloudpickle
|
| 16 |
+
from ray.rllib.connectors.registry import register_connector
|
| 17 |
+
from ray.rllib.core.columns import Columns
|
| 18 |
+
from ray.rllib.policy.sample_batch import SampleBatch
|
| 19 |
+
from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space
|
| 20 |
+
from ray.rllib.utils.typing import ActionConnectorDataType, AgentConnectorDataType
|
| 21 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@OldAPIStack
|
| 28 |
+
class StateBufferConnector(AgentConnector):
|
| 29 |
+
def __init__(self, ctx: ConnectorContext, states: Any = None):
|
| 30 |
+
super().__init__(ctx)
|
| 31 |
+
|
| 32 |
+
self._initial_states = ctx.initial_states
|
| 33 |
+
self._action_space_struct = get_base_struct_from_space(ctx.action_space)
|
| 34 |
+
|
| 35 |
+
self._states = defaultdict(lambda: defaultdict(lambda: (None, None, None)))
|
| 36 |
+
self._enable_new_api_stack = False
|
| 37 |
+
# TODO(jungong) : we would not need this if policies are never stashed
|
| 38 |
+
# during the rollout of a single episode.
|
| 39 |
+
if states:
|
| 40 |
+
try:
|
| 41 |
+
self._states = cloudpickle.loads(states)
|
| 42 |
+
except pickle.UnpicklingError:
|
| 43 |
+
# StateBufferConnector states are only needed for rare cases
|
| 44 |
+
# like stashing then restoring a policy during the rollout of
|
| 45 |
+
# a single episode.
|
| 46 |
+
# It is ok to ignore the error for most of the cases here.
|
| 47 |
+
logger.info(
|
| 48 |
+
"Can not restore StateBufferConnector states. This warning can "
|
| 49 |
+
"usually be ignore, unless it is from restoring a stashed policy."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
@override(Connector)
|
| 53 |
+
def in_eval(self):
|
| 54 |
+
super().in_eval()
|
| 55 |
+
|
| 56 |
+
def reset(self, env_id: str):
|
| 57 |
+
# States should not be carried over between episodes.
|
| 58 |
+
if env_id in self._states:
|
| 59 |
+
del self._states[env_id]
|
| 60 |
+
|
| 61 |
+
def on_policy_output(self, ac_data: ActionConnectorDataType):
|
| 62 |
+
# Buffer latest output states for next input __call__.
|
| 63 |
+
self._states[ac_data.env_id][ac_data.agent_id] = ac_data.output
|
| 64 |
+
|
| 65 |
+
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
|
| 66 |
+
d = ac_data.data
|
| 67 |
+
assert (
|
| 68 |
+
type(d) is dict
|
| 69 |
+
), "Single agent data must be of type Dict[str, TensorStructType]"
|
| 70 |
+
|
| 71 |
+
env_id = ac_data.env_id
|
| 72 |
+
agent_id = ac_data.agent_id
|
| 73 |
+
assert (
|
| 74 |
+
env_id is not None and agent_id is not None
|
| 75 |
+
), f"StateBufferConnector requires env_id(f{env_id}) and agent_id(f{agent_id})"
|
| 76 |
+
|
| 77 |
+
action, states, fetches = self._states[env_id][agent_id]
|
| 78 |
+
|
| 79 |
+
if action is not None:
|
| 80 |
+
d[SampleBatch.ACTIONS] = action # Last action
|
| 81 |
+
else:
|
| 82 |
+
# Default zero action.
|
| 83 |
+
d[SampleBatch.ACTIONS] = tree.map_structure(
|
| 84 |
+
lambda s: np.zeros_like(s.sample(), s.dtype)
|
| 85 |
+
if hasattr(s, "dtype")
|
| 86 |
+
else np.zeros_like(s.sample()),
|
| 87 |
+
self._action_space_struct,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if states is None:
|
| 91 |
+
states = self._initial_states
|
| 92 |
+
if self._enable_new_api_stack:
|
| 93 |
+
if states:
|
| 94 |
+
d[Columns.STATE_OUT] = states
|
| 95 |
+
else:
|
| 96 |
+
for i, v in enumerate(states):
|
| 97 |
+
d["state_out_{}".format(i)] = v
|
| 98 |
+
|
| 99 |
+
# Also add extra fetches if available.
|
| 100 |
+
if fetches:
|
| 101 |
+
d.update(fetches)
|
| 102 |
+
|
| 103 |
+
return ac_data
|
| 104 |
+
|
| 105 |
+
def to_state(self):
|
| 106 |
+
# Note(jungong) : it is ok to use cloudpickle here for stats because:
|
| 107 |
+
# 1. self._states may contain arbitary data objects, and will be hard
|
| 108 |
+
# to serialize otherwise.
|
| 109 |
+
# 2. seriazlized states are only useful if a policy is stashed and
|
| 110 |
+
# restored during the rollout of a single episode. So it is ok to
|
| 111 |
+
# use cloudpickle for such non-persistent data bits.
|
| 112 |
+
states = cloudpickle.dumps(self._states)
|
| 113 |
+
return StateBufferConnector.__name__, states
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
def from_state(ctx: ConnectorContext, params: Any):
|
| 117 |
+
return StateBufferConnector(ctx, params)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
register_connector(StateBufferConnector.__name__, StateBufferConnector)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/synced_filter.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ray.rllib.connectors.connector import (
|
| 2 |
+
AgentConnector,
|
| 3 |
+
ConnectorContext,
|
| 4 |
+
)
|
| 5 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 6 |
+
from ray.rllib.utils.filter import Filter
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@OldAPIStack
|
| 10 |
+
class SyncedFilterAgentConnector(AgentConnector):
|
| 11 |
+
"""An agent connector that filters with synchronized parameters."""
|
| 12 |
+
|
| 13 |
+
def __init__(self, ctx: ConnectorContext, *args, **kwargs):
|
| 14 |
+
super().__init__(ctx)
|
| 15 |
+
if args or kwargs:
|
| 16 |
+
raise ValueError(
|
| 17 |
+
"SyncedFilterAgentConnector does not take any additional arguments, "
|
| 18 |
+
"but got args=`{}` and kwargs={}.".format(args, kwargs)
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
def apply_changes(self, other: "Filter", *args, **kwargs) -> None:
|
| 22 |
+
"""Updates self with state from other filter."""
|
| 23 |
+
# TODO: (artur) inline this as soon as we deprecate ordinary filter with
|
| 24 |
+
# non-connecto env_runner
|
| 25 |
+
return self.filter.apply_changes(other, *args, **kwargs)
|
| 26 |
+
|
| 27 |
+
def copy(self) -> "Filter":
|
| 28 |
+
"""Creates a new object with same state as self.
|
| 29 |
+
|
| 30 |
+
This is a legacy Filter method that we need to keep around for now
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
A copy of self.
|
| 34 |
+
"""
|
| 35 |
+
# inline this as soon as we deprecate ordinary filter with non-connector
|
| 36 |
+
# env_runner
|
| 37 |
+
return self.filter.copy()
|
| 38 |
+
|
| 39 |
+
def sync(self, other: "AgentConnector") -> None:
|
| 40 |
+
"""Copies all state from other filter to self."""
|
| 41 |
+
# TODO: (artur) inline this as soon as we deprecate ordinary filter with
|
| 42 |
+
# non-connector env_runner
|
| 43 |
+
return self.filter.sync(other.filter)
|
| 44 |
+
|
| 45 |
+
def reset_state(self) -> None:
|
| 46 |
+
"""Creates copy of current state and resets accumulated state"""
|
| 47 |
+
raise NotImplementedError
|
| 48 |
+
|
| 49 |
+
def as_serializable(self) -> "Filter":
|
| 50 |
+
# TODO: (artur) inline this as soon as we deprecate ordinary filter with
|
| 51 |
+
# non-connector env_runner
|
| 52 |
+
return self.filter.as_serializable()
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/agent/view_requirement.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from ray.rllib.connectors.connector import (
|
| 5 |
+
AgentConnector,
|
| 6 |
+
ConnectorContext,
|
| 7 |
+
)
|
| 8 |
+
from ray.rllib.connectors.registry import register_connector
|
| 9 |
+
from ray.rllib.policy.sample_batch import SampleBatch
|
| 10 |
+
from ray.rllib.utils.typing import (
|
| 11 |
+
AgentConnectorDataType,
|
| 12 |
+
AgentConnectorsOutput,
|
| 13 |
+
)
|
| 14 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 15 |
+
from ray.rllib.evaluation.collectors.agent_collector import AgentCollector
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@OldAPIStack
|
| 19 |
+
class ViewRequirementAgentConnector(AgentConnector):
|
| 20 |
+
"""This connector does 2 things:
|
| 21 |
+
1. It filters data columns based on view_requirements for training and inference.
|
| 22 |
+
2. It buffers the right amount of history for computing the sample batch for
|
| 23 |
+
action computation.
|
| 24 |
+
The output of this connector is AgentConnectorsOut, which basically is
|
| 25 |
+
a tuple of 2 things:
|
| 26 |
+
{
|
| 27 |
+
"raw_dict": {"obs": ...}
|
| 28 |
+
"sample_batch": SampleBatch
|
| 29 |
+
}
|
| 30 |
+
raw_dict, which contains raw data for the latest time slice,
|
| 31 |
+
can be used to construct a complete episode by Sampler for training purpose.
|
| 32 |
+
The "for_action" SampleBatch can be used to directly call the policy.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(self, ctx: ConnectorContext):
|
| 36 |
+
super().__init__(ctx)
|
| 37 |
+
|
| 38 |
+
self._view_requirements = ctx.view_requirements
|
| 39 |
+
_enable_new_api_stack = False
|
| 40 |
+
|
| 41 |
+
# a dict of env_id to a dict of agent_id to a list of agent_collector objects
|
| 42 |
+
self.agent_collectors = defaultdict(
|
| 43 |
+
lambda: defaultdict(
|
| 44 |
+
lambda: AgentCollector(
|
| 45 |
+
self._view_requirements,
|
| 46 |
+
max_seq_len=ctx.config["model"]["max_seq_len"],
|
| 47 |
+
intial_states=ctx.initial_states,
|
| 48 |
+
disable_action_flattening=ctx.config.get(
|
| 49 |
+
"_disable_action_flattening", False
|
| 50 |
+
),
|
| 51 |
+
is_policy_recurrent=ctx.is_policy_recurrent,
|
| 52 |
+
# Note(jungong): We only leverage AgentCollector for building sample
|
| 53 |
+
# batches for computing actions.
|
| 54 |
+
# So regardless of whether this ViewRequirement connector is in
|
| 55 |
+
# training or inference mode, we should tell these AgentCollectors
|
| 56 |
+
# to behave in inference mode, so they don't accumulate episode data
|
| 57 |
+
# that is not useful for inference.
|
| 58 |
+
is_training=False,
|
| 59 |
+
_enable_new_api_stack=_enable_new_api_stack,
|
| 60 |
+
)
|
| 61 |
+
)
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def reset(self, env_id: str):
|
| 65 |
+
if env_id in self.agent_collectors:
|
| 66 |
+
del self.agent_collectors[env_id]
|
| 67 |
+
|
| 68 |
+
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
|
| 69 |
+
d = ac_data.data
|
| 70 |
+
assert (
|
| 71 |
+
type(d) is dict
|
| 72 |
+
), "Single agent data must be of type Dict[str, TensorStructType]"
|
| 73 |
+
|
| 74 |
+
env_id = ac_data.env_id
|
| 75 |
+
agent_id = ac_data.agent_id
|
| 76 |
+
# TODO: we don't keep episode_id around so use env_id as episode_id ?
|
| 77 |
+
episode_id = env_id if SampleBatch.EPS_ID not in d else d[SampleBatch.EPS_ID]
|
| 78 |
+
|
| 79 |
+
assert env_id is not None and agent_id is not None, (
|
| 80 |
+
f"ViewRequirementAgentConnector requires env_id({env_id}) "
|
| 81 |
+
"and agent_id({agent_id})"
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
assert (
|
| 85 |
+
self._view_requirements
|
| 86 |
+
), "ViewRequirements required by ViewRequirementAgentConnector"
|
| 87 |
+
|
| 88 |
+
# Note(jungong) : we need to keep the entire input dict here.
|
| 89 |
+
# A column may be used by postprocessing (GAE) even if its
|
| 90 |
+
# view_requirement.used_for_training is False.
|
| 91 |
+
training_dict = d
|
| 92 |
+
|
| 93 |
+
agent_collector = self.agent_collectors[env_id][agent_id]
|
| 94 |
+
|
| 95 |
+
if SampleBatch.NEXT_OBS not in d:
|
| 96 |
+
raise ValueError(f"connector data {d} should contain next_obs.")
|
| 97 |
+
# TODO(avnishn; kourosh) Unsure how agent_index is necessary downstream
|
| 98 |
+
# since there is no mapping from agent_index to agent_id that exists.
|
| 99 |
+
# need to remove this from the SampleBatch later.
|
| 100 |
+
# fall back to using dummy index if no index is available
|
| 101 |
+
if SampleBatch.AGENT_INDEX in d:
|
| 102 |
+
agent_index = d[SampleBatch.AGENT_INDEX]
|
| 103 |
+
else:
|
| 104 |
+
try:
|
| 105 |
+
agent_index = float(agent_id)
|
| 106 |
+
except ValueError:
|
| 107 |
+
agent_index = -1
|
| 108 |
+
if agent_collector.is_empty():
|
| 109 |
+
agent_collector.add_init_obs(
|
| 110 |
+
episode_id=episode_id,
|
| 111 |
+
agent_index=agent_index,
|
| 112 |
+
env_id=env_id,
|
| 113 |
+
init_obs=d[SampleBatch.NEXT_OBS],
|
| 114 |
+
init_infos=d.get(SampleBatch.INFOS),
|
| 115 |
+
)
|
| 116 |
+
else:
|
| 117 |
+
agent_collector.add_action_reward_next_obs(d)
|
| 118 |
+
sample_batch = agent_collector.build_for_inference()
|
| 119 |
+
|
| 120 |
+
return_data = AgentConnectorDataType(
|
| 121 |
+
env_id, agent_id, AgentConnectorsOutput(training_dict, sample_batch)
|
| 122 |
+
)
|
| 123 |
+
return return_data
|
| 124 |
+
|
| 125 |
+
def to_state(self):
|
| 126 |
+
return ViewRequirementAgentConnector.__name__, None
|
| 127 |
+
|
| 128 |
+
@staticmethod
|
| 129 |
+
def from_state(ctx: ConnectorContext, params: Any):
|
| 130 |
+
return ViewRequirementAgentConnector(ctx)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
register_connector(
|
| 134 |
+
ViewRequirementAgentConnector.__name__, ViewRequirementAgentConnector
|
| 135 |
+
)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector.py
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This file defines base types and common structures for RLlib connectors.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
import abc
|
| 5 |
+
import logging
|
| 6 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
|
| 7 |
+
|
| 8 |
+
import gymnasium as gym
|
| 9 |
+
|
| 10 |
+
from ray.rllib.policy.view_requirement import ViewRequirement
|
| 11 |
+
from ray.rllib.utils.typing import (
|
| 12 |
+
ActionConnectorDataType,
|
| 13 |
+
AgentConnectorDataType,
|
| 14 |
+
AlgorithmConfigDict,
|
| 15 |
+
TensorType,
|
| 16 |
+
)
|
| 17 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from ray.rllib.policy.policy import Policy
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@OldAPIStack
|
| 26 |
+
class ConnectorContext:
|
| 27 |
+
"""Data bits that may be needed for running connectors.
|
| 28 |
+
|
| 29 |
+
Note(jungong) : we need to be really careful with the data fields here.
|
| 30 |
+
E.g., everything needs to be serializable, in case we need to fetch them
|
| 31 |
+
in a remote setting.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
# TODO(jungong) : figure out how to fetch these in a remote setting.
|
| 35 |
+
# Probably from a policy server when initializing a policy client.
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
config: AlgorithmConfigDict = None,
|
| 40 |
+
initial_states: List[TensorType] = None,
|
| 41 |
+
observation_space: gym.Space = None,
|
| 42 |
+
action_space: gym.Space = None,
|
| 43 |
+
view_requirements: Dict[str, ViewRequirement] = None,
|
| 44 |
+
is_policy_recurrent: bool = False,
|
| 45 |
+
):
|
| 46 |
+
"""Construct a ConnectorContext instance.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
initial_states: States that are used for constructing
|
| 50 |
+
the initial input dict for RNN models. [] if a model is not recurrent.
|
| 51 |
+
action_space_struct: a policy's action space, in python
|
| 52 |
+
data format. E.g., python dict instead of DictSpace, python tuple
|
| 53 |
+
instead of TupleSpace.
|
| 54 |
+
"""
|
| 55 |
+
self.config = config or {}
|
| 56 |
+
self.initial_states = initial_states or []
|
| 57 |
+
self.observation_space = observation_space
|
| 58 |
+
self.action_space = action_space
|
| 59 |
+
self.view_requirements = view_requirements
|
| 60 |
+
self.is_policy_recurrent = is_policy_recurrent
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def from_policy(policy: "Policy") -> "ConnectorContext":
|
| 64 |
+
"""Build ConnectorContext from a given policy.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
policy: Policy
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
A ConnectorContext instance.
|
| 71 |
+
"""
|
| 72 |
+
return ConnectorContext(
|
| 73 |
+
config=policy.config,
|
| 74 |
+
initial_states=policy.get_initial_state(),
|
| 75 |
+
observation_space=policy.observation_space,
|
| 76 |
+
action_space=policy.action_space,
|
| 77 |
+
view_requirements=policy.view_requirements,
|
| 78 |
+
is_policy_recurrent=policy.is_recurrent(),
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@OldAPIStack
|
| 83 |
+
class Connector(abc.ABC):
|
| 84 |
+
"""Connector base class.
|
| 85 |
+
|
| 86 |
+
A connector is a step of transformation, of either envrionment data before they
|
| 87 |
+
get to a policy, or policy output before it is sent back to the environment.
|
| 88 |
+
|
| 89 |
+
Connectors may be training-aware, for example, behave slightly differently
|
| 90 |
+
during training and inference.
|
| 91 |
+
|
| 92 |
+
All connectors are required to be serializable and implement to_state().
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(self, ctx: ConnectorContext):
|
| 96 |
+
# Default is training mode.
|
| 97 |
+
self._is_training = True
|
| 98 |
+
|
| 99 |
+
def in_training(self):
|
| 100 |
+
self._is_training = True
|
| 101 |
+
|
| 102 |
+
def in_eval(self):
|
| 103 |
+
self._is_training = False
|
| 104 |
+
|
| 105 |
+
def __str__(self, indentation: int = 0):
|
| 106 |
+
return " " * indentation + self.__class__.__name__
|
| 107 |
+
|
| 108 |
+
def to_state(self) -> Tuple[str, Any]:
|
| 109 |
+
"""Serialize a connector into a JSON serializable Tuple.
|
| 110 |
+
|
| 111 |
+
to_state is required, so that all Connectors are serializable.
|
| 112 |
+
|
| 113 |
+
Returns:
|
| 114 |
+
A tuple of connector's name and its serialized states.
|
| 115 |
+
String should match the name used to register the connector,
|
| 116 |
+
while state can be any single data structure that contains the
|
| 117 |
+
serialized state of the connector. If a connector is stateless,
|
| 118 |
+
state can simply be None.
|
| 119 |
+
"""
|
| 120 |
+
# Must implement by each connector.
|
| 121 |
+
return NotImplementedError
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def from_state(self, ctx: ConnectorContext, params: Any) -> "Connector":
|
| 125 |
+
"""De-serialize a JSON params back into a Connector.
|
| 126 |
+
|
| 127 |
+
from_state is required, so that all Connectors are serializable.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
ctx: Context for constructing this connector.
|
| 131 |
+
params: Serialized states of the connector to be recovered.
|
| 132 |
+
|
| 133 |
+
Returns:
|
| 134 |
+
De-serialized connector.
|
| 135 |
+
"""
|
| 136 |
+
# Must implement by each connector.
|
| 137 |
+
return NotImplementedError
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@OldAPIStack
|
| 141 |
+
class AgentConnector(Connector):
|
| 142 |
+
"""Connector connecting user environments to RLlib policies.
|
| 143 |
+
|
| 144 |
+
An agent connector transforms a list of agent data in AgentConnectorDataType
|
| 145 |
+
format into a new list in the same AgentConnectorDataTypes format.
|
| 146 |
+
The input API is designed so agent connectors can have access to all the
|
| 147 |
+
agents assigned to a particular policy.
|
| 148 |
+
|
| 149 |
+
AgentConnectorDataTypes can be used to specify arbitrary type of env data,
|
| 150 |
+
|
| 151 |
+
Example:
|
| 152 |
+
|
| 153 |
+
Represent a list of agent data from one env step() call.
|
| 154 |
+
|
| 155 |
+
.. testcode::
|
| 156 |
+
|
| 157 |
+
import numpy as np
|
| 158 |
+
ac = AgentConnectorDataType(
|
| 159 |
+
env_id="env_1",
|
| 160 |
+
agent_id=None,
|
| 161 |
+
data={
|
| 162 |
+
"agent_1": np.array([1, 2, 3]),
|
| 163 |
+
"agent_2": np.array([4, 5, 6]),
|
| 164 |
+
}
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
Or a single agent data ready to be preprocessed.
|
| 168 |
+
|
| 169 |
+
.. testcode::
|
| 170 |
+
|
| 171 |
+
ac = AgentConnectorDataType(
|
| 172 |
+
env_id="env_1",
|
| 173 |
+
agent_id="agent_1",
|
| 174 |
+
data=np.array([1, 2, 3]),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
We can also adapt a simple stateless function into an agent connector by
|
| 178 |
+
using register_lambda_agent_connector:
|
| 179 |
+
|
| 180 |
+
.. testcode::
|
| 181 |
+
|
| 182 |
+
import numpy as np
|
| 183 |
+
from ray.rllib.connectors.agent.lambdas import (
|
| 184 |
+
register_lambda_agent_connector
|
| 185 |
+
)
|
| 186 |
+
TimesTwoAgentConnector = register_lambda_agent_connector(
|
| 187 |
+
"TimesTwoAgentConnector", lambda data: data * 2
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
# More complicated agent connectors can be implemented by extending this
|
| 191 |
+
# AgentConnector class:
|
| 192 |
+
|
| 193 |
+
class FrameSkippingAgentConnector(AgentConnector):
|
| 194 |
+
def __init__(self, n):
|
| 195 |
+
self._n = n
|
| 196 |
+
self._frame_count = default_dict(str, default_dict(str, int))
|
| 197 |
+
|
| 198 |
+
def reset(self, env_id: str):
|
| 199 |
+
del self._frame_count[env_id]
|
| 200 |
+
|
| 201 |
+
def __call__(
|
| 202 |
+
self, ac_data: List[AgentConnectorDataType]
|
| 203 |
+
) -> List[AgentConnectorDataType]:
|
| 204 |
+
ret = []
|
| 205 |
+
for d in ac_data:
|
| 206 |
+
assert d.env_id and d.agent_id, "Skipping works per agent!"
|
| 207 |
+
|
| 208 |
+
count = self._frame_count[ac_data.env_id][ac_data.agent_id]
|
| 209 |
+
self._frame_count[ac_data.env_id][ac_data.agent_id] = (
|
| 210 |
+
count + 1
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
if count % self._n == 0:
|
| 214 |
+
ret.append(d)
|
| 215 |
+
return ret
|
| 216 |
+
|
| 217 |
+
As shown, an agent connector may choose to emit an empty list to stop input
|
| 218 |
+
observations from being further prosessed.
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
def reset(self, env_id: str):
|
| 222 |
+
"""Reset connector state for a specific environment.
|
| 223 |
+
|
| 224 |
+
For example, at the end of an episode.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
env_id: required. ID of a user environment. Required.
|
| 228 |
+
"""
|
| 229 |
+
pass
|
| 230 |
+
|
| 231 |
+
def on_policy_output(self, output: ActionConnectorDataType):
|
| 232 |
+
"""Callback on agent connector of policy output.
|
| 233 |
+
|
| 234 |
+
This is useful for certain connectors, for example RNN state buffering,
|
| 235 |
+
where the agent connect needs to be aware of the output of a policy
|
| 236 |
+
forward pass.
|
| 237 |
+
|
| 238 |
+
Args:
|
| 239 |
+
ctx: Context for running this connector call.
|
| 240 |
+
output: Env and agent IDs, plus data output from policy forward pass.
|
| 241 |
+
"""
|
| 242 |
+
pass
|
| 243 |
+
|
| 244 |
+
def __call__(
|
| 245 |
+
self, acd_list: List[AgentConnectorDataType]
|
| 246 |
+
) -> List[AgentConnectorDataType]:
|
| 247 |
+
"""Transform a list of data items from env before they reach policy.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
ac_data: List of env and agent IDs, plus arbitrary data items from
|
| 251 |
+
an environment or upstream agent connectors.
|
| 252 |
+
|
| 253 |
+
Returns:
|
| 254 |
+
A list of transformed data items in AgentConnectorDataType format.
|
| 255 |
+
The shape of a returned list does not have to match that of the input list.
|
| 256 |
+
An AgentConnector may choose to derive multiple outputs for a single piece
|
| 257 |
+
of input data, for example multi-agent obs -> multiple single agent obs.
|
| 258 |
+
Agent connectors may also choose to skip emitting certain inputs,
|
| 259 |
+
useful for connectors such as frame skipping.
|
| 260 |
+
"""
|
| 261 |
+
assert isinstance(
|
| 262 |
+
acd_list, (list, tuple)
|
| 263 |
+
), "Input to agent connectors are list of AgentConnectorDataType."
|
| 264 |
+
# Default implementation. Simply call transform on each agent connector data.
|
| 265 |
+
return [self.transform(d) for d in acd_list]
|
| 266 |
+
|
| 267 |
+
def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType:
|
| 268 |
+
"""Transform a single agent connector data item.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
data: Env and agent IDs, plus arbitrary data item from a single agent
|
| 272 |
+
of an environment.
|
| 273 |
+
|
| 274 |
+
Returns:
|
| 275 |
+
A transformed piece of agent connector data.
|
| 276 |
+
"""
|
| 277 |
+
raise NotImplementedError
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
@OldAPIStack
|
| 281 |
+
class ActionConnector(Connector):
|
| 282 |
+
"""Action connector connects policy outputs including actions,
|
| 283 |
+
to user environments.
|
| 284 |
+
|
| 285 |
+
An action connector transforms a single piece of policy output in
|
| 286 |
+
ActionConnectorDataType format, which is basically PolicyOutputType plus env and
|
| 287 |
+
agent IDs.
|
| 288 |
+
|
| 289 |
+
Any functions that operate directly on PolicyOutputType can be easily adapted
|
| 290 |
+
into an ActionConnector by using register_lambda_action_connector.
|
| 291 |
+
|
| 292 |
+
Example:
|
| 293 |
+
|
| 294 |
+
.. testcode::
|
| 295 |
+
|
| 296 |
+
from ray.rllib.connectors.action.lambdas import (
|
| 297 |
+
register_lambda_action_connector
|
| 298 |
+
)
|
| 299 |
+
ZeroActionConnector = register_lambda_action_connector(
|
| 300 |
+
"ZeroActionsConnector",
|
| 301 |
+
lambda actions, states, fetches: (
|
| 302 |
+
np.zeros_like(actions), states, fetches
|
| 303 |
+
)
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
More complicated action connectors can also be implemented by sub-classing
|
| 307 |
+
this ActionConnector class.
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
def __call__(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType:
|
| 311 |
+
"""Transform policy output before they are sent to a user environment.
|
| 312 |
+
|
| 313 |
+
Args:
|
| 314 |
+
ac_data: Env and agent IDs, plus policy output.
|
| 315 |
+
|
| 316 |
+
Returns:
|
| 317 |
+
The processed action connector data.
|
| 318 |
+
"""
|
| 319 |
+
return self.transform(ac_data)
|
| 320 |
+
|
| 321 |
+
def transform(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType:
|
| 322 |
+
"""Implementation of the actual transform.
|
| 323 |
+
|
| 324 |
+
Users should override transform instead of __call__ directly.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
ac_data: Env and agent IDs, plus policy output.
|
| 328 |
+
|
| 329 |
+
Returns:
|
| 330 |
+
The processed action connector data.
|
| 331 |
+
"""
|
| 332 |
+
raise NotImplementedError
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
@OldAPIStack
|
| 336 |
+
class ConnectorPipeline(abc.ABC):
|
| 337 |
+
"""Utility class for quick manipulation of a connector pipeline."""
|
| 338 |
+
|
| 339 |
+
def __init__(self, ctx: ConnectorContext, connectors: List[Connector]):
|
| 340 |
+
self.connectors = connectors
|
| 341 |
+
|
| 342 |
+
def in_training(self):
|
| 343 |
+
for c in self.connectors:
|
| 344 |
+
c.in_training()
|
| 345 |
+
|
| 346 |
+
def in_eval(self):
|
| 347 |
+
for c in self.connectors:
|
| 348 |
+
c.in_eval()
|
| 349 |
+
|
| 350 |
+
def remove(self, name: str):
|
| 351 |
+
"""Remove a connector by <name>
|
| 352 |
+
|
| 353 |
+
Args:
|
| 354 |
+
name: name of the connector to be removed.
|
| 355 |
+
"""
|
| 356 |
+
idx = -1
|
| 357 |
+
for i, c in enumerate(self.connectors):
|
| 358 |
+
if c.__class__.__name__ == name:
|
| 359 |
+
idx = i
|
| 360 |
+
break
|
| 361 |
+
if idx >= 0:
|
| 362 |
+
del self.connectors[idx]
|
| 363 |
+
logger.info(f"Removed connector {name} from {self.__class__.__name__}.")
|
| 364 |
+
else:
|
| 365 |
+
logger.warning(f"Trying to remove a non-existent connector {name}.")
|
| 366 |
+
|
| 367 |
+
def insert_before(self, name: str, connector: Connector):
|
| 368 |
+
"""Insert a new connector before connector <name>
|
| 369 |
+
|
| 370 |
+
Args:
|
| 371 |
+
name: name of the connector before which a new connector
|
| 372 |
+
will get inserted.
|
| 373 |
+
connector: a new connector to be inserted.
|
| 374 |
+
"""
|
| 375 |
+
idx = -1
|
| 376 |
+
for idx, c in enumerate(self.connectors):
|
| 377 |
+
if c.__class__.__name__ == name:
|
| 378 |
+
break
|
| 379 |
+
if idx < 0:
|
| 380 |
+
raise ValueError(f"Can not find connector {name}")
|
| 381 |
+
self.connectors.insert(idx, connector)
|
| 382 |
+
|
| 383 |
+
logger.info(
|
| 384 |
+
f"Inserted {connector.__class__.__name__} before {name} "
|
| 385 |
+
f"to {self.__class__.__name__}."
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
def insert_after(self, name: str, connector: Connector):
|
| 389 |
+
"""Insert a new connector after connector <name>
|
| 390 |
+
|
| 391 |
+
Args:
|
| 392 |
+
name: name of the connector after which a new connector
|
| 393 |
+
will get inserted.
|
| 394 |
+
connector: a new connector to be inserted.
|
| 395 |
+
"""
|
| 396 |
+
idx = -1
|
| 397 |
+
for idx, c in enumerate(self.connectors):
|
| 398 |
+
if c.__class__.__name__ == name:
|
| 399 |
+
break
|
| 400 |
+
if idx < 0:
|
| 401 |
+
raise ValueError(f"Can not find connector {name}")
|
| 402 |
+
self.connectors.insert(idx + 1, connector)
|
| 403 |
+
|
| 404 |
+
logger.info(
|
| 405 |
+
f"Inserted {connector.__class__.__name__} after {name} "
|
| 406 |
+
f"to {self.__class__.__name__}."
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
def prepend(self, connector: Connector):
|
| 410 |
+
"""Append a new connector at the beginning of a connector pipeline.
|
| 411 |
+
|
| 412 |
+
Args:
|
| 413 |
+
connector: a new connector to be appended.
|
| 414 |
+
"""
|
| 415 |
+
self.connectors.insert(0, connector)
|
| 416 |
+
|
| 417 |
+
logger.info(
|
| 418 |
+
f"Added {connector.__class__.__name__} to the beginning of "
|
| 419 |
+
f"{self.__class__.__name__}."
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
def append(self, connector: Connector):
|
| 423 |
+
"""Append a new connector at the end of a connector pipeline.
|
| 424 |
+
|
| 425 |
+
Args:
|
| 426 |
+
connector: a new connector to be appended.
|
| 427 |
+
"""
|
| 428 |
+
self.connectors.append(connector)
|
| 429 |
+
|
| 430 |
+
logger.info(
|
| 431 |
+
f"Added {connector.__class__.__name__} to the end of "
|
| 432 |
+
f"{self.__class__.__name__}."
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
def __str__(self, indentation: int = 0):
|
| 436 |
+
return "\n".join(
|
| 437 |
+
[" " * indentation + self.__class__.__name__]
|
| 438 |
+
+ [c.__str__(indentation + 4) for c in self.connectors]
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
def __getitem__(self, key: Union[str, int, type]):
|
| 442 |
+
"""Returns a list of connectors that fit 'key'.
|
| 443 |
+
|
| 444 |
+
If key is a number n, we return a list with the nth element of this pipeline.
|
| 445 |
+
If key is a Connector class or a string matching the class name of a
|
| 446 |
+
Connector class, we return a list of all connectors in this pipeline matching
|
| 447 |
+
the specified class.
|
| 448 |
+
|
| 449 |
+
Args:
|
| 450 |
+
key: The key to index by
|
| 451 |
+
|
| 452 |
+
Returns: The Connector at index `key`.
|
| 453 |
+
"""
|
| 454 |
+
# In case key is a class
|
| 455 |
+
if not isinstance(key, str):
|
| 456 |
+
if isinstance(key, slice):
|
| 457 |
+
raise NotImplementedError(
|
| 458 |
+
"Slicing of ConnectorPipeline is currently not supported."
|
| 459 |
+
)
|
| 460 |
+
elif isinstance(key, int):
|
| 461 |
+
return [self.connectors[key]]
|
| 462 |
+
elif isinstance(key, type):
|
| 463 |
+
results = []
|
| 464 |
+
for c in self.connectors:
|
| 465 |
+
if issubclass(c.__class__, key):
|
| 466 |
+
results.append(c)
|
| 467 |
+
return results
|
| 468 |
+
else:
|
| 469 |
+
raise NotImplementedError(
|
| 470 |
+
"Indexing by {} is currently not supported.".format(type(key))
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
results = []
|
| 474 |
+
for c in self.connectors:
|
| 475 |
+
if c.__class__.__name__ == key:
|
| 476 |
+
results.append(c)
|
| 477 |
+
|
| 478 |
+
return results
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_pipeline_v2.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
import logging
|
| 3 |
+
from typing import Any, Collection, Dict, List, Optional, Tuple, Type, Union
|
| 4 |
+
|
| 5 |
+
import gymnasium as gym
|
| 6 |
+
|
| 7 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 8 |
+
from ray.rllib.core.rl_module.rl_module import RLModule
|
| 9 |
+
from ray.rllib.utils.annotations import override
|
| 10 |
+
from ray.rllib.utils.checkpoints import Checkpointable
|
| 11 |
+
from ray.rllib.utils.typing import EpisodeType, StateDict
|
| 12 |
+
from ray.util.annotations import PublicAPI
|
| 13 |
+
from ray.util.timer import _Timer
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@PublicAPI(stability="alpha")
|
| 19 |
+
class ConnectorPipelineV2(ConnectorV2):
|
| 20 |
+
"""Utility class for quick manipulation of a connector pipeline."""
|
| 21 |
+
|
| 22 |
+
@override(ConnectorV2)
|
| 23 |
+
def recompute_output_observation_space(
|
| 24 |
+
self,
|
| 25 |
+
input_observation_space: gym.Space,
|
| 26 |
+
input_action_space: gym.Space,
|
| 27 |
+
) -> gym.Space:
|
| 28 |
+
self._fix_spaces(input_observation_space, input_action_space)
|
| 29 |
+
return self.observation_space
|
| 30 |
+
|
| 31 |
+
@override(ConnectorV2)
|
| 32 |
+
def recompute_output_action_space(
|
| 33 |
+
self,
|
| 34 |
+
input_observation_space: gym.Space,
|
| 35 |
+
input_action_space: gym.Space,
|
| 36 |
+
) -> gym.Space:
|
| 37 |
+
self._fix_spaces(input_observation_space, input_action_space)
|
| 38 |
+
return self.action_space
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
input_observation_space: Optional[gym.Space] = None,
|
| 43 |
+
input_action_space: Optional[gym.Space] = None,
|
| 44 |
+
*,
|
| 45 |
+
connectors: Optional[List[ConnectorV2]] = None,
|
| 46 |
+
**kwargs,
|
| 47 |
+
):
|
| 48 |
+
"""Initializes a ConnectorPipelineV2 instance.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
input_observation_space: The (optional) input observation space for this
|
| 52 |
+
connector piece. This is the space coming from a previous connector
|
| 53 |
+
piece in the (env-to-module or learner) pipeline or is directly
|
| 54 |
+
defined within the gym.Env.
|
| 55 |
+
input_action_space: The (optional) input action space for this connector
|
| 56 |
+
piece. This is the space coming from a previous connector piece in the
|
| 57 |
+
(module-to-env) pipeline or is directly defined within the gym.Env.
|
| 58 |
+
connectors: A list of individual ConnectorV2 pieces to be added to this
|
| 59 |
+
pipeline during construction. Note that you can always add (or remove)
|
| 60 |
+
more ConnectorV2 pieces later on the fly.
|
| 61 |
+
"""
|
| 62 |
+
self.connectors = []
|
| 63 |
+
|
| 64 |
+
for conn in connectors:
|
| 65 |
+
# If we have a `ConnectorV2` instance just append.
|
| 66 |
+
if isinstance(conn, ConnectorV2):
|
| 67 |
+
self.connectors.append(conn)
|
| 68 |
+
# If, we have a class with `args` and `kwargs`, build the instance.
|
| 69 |
+
# Note that this way of constructing a pipeline should only be
|
| 70 |
+
# used internally when restoring the pipeline state from a
|
| 71 |
+
# checkpoint.
|
| 72 |
+
elif isinstance(conn, tuple) and len(conn) == 3:
|
| 73 |
+
self.connectors.append(conn[0](*conn[1], **conn[2]))
|
| 74 |
+
|
| 75 |
+
super().__init__(input_observation_space, input_action_space, **kwargs)
|
| 76 |
+
|
| 77 |
+
self.timers = defaultdict(_Timer)
|
| 78 |
+
|
| 79 |
+
def __len__(self):
|
| 80 |
+
return len(self.connectors)
|
| 81 |
+
|
| 82 |
+
@override(ConnectorV2)
|
| 83 |
+
def __call__(
|
| 84 |
+
self,
|
| 85 |
+
*,
|
| 86 |
+
rl_module: RLModule,
|
| 87 |
+
batch: Dict[str, Any],
|
| 88 |
+
episodes: List[EpisodeType],
|
| 89 |
+
explore: Optional[bool] = None,
|
| 90 |
+
shared_data: Optional[dict] = None,
|
| 91 |
+
**kwargs,
|
| 92 |
+
) -> Any:
|
| 93 |
+
"""In a pipeline, we simply call each of our connector pieces after each other.
|
| 94 |
+
|
| 95 |
+
Each connector piece receives as input the output of the previous connector
|
| 96 |
+
piece in the pipeline.
|
| 97 |
+
"""
|
| 98 |
+
shared_data = shared_data if shared_data is not None else {}
|
| 99 |
+
# Loop through connector pieces and call each one with the output of the
|
| 100 |
+
# previous one. Thereby, time each connector piece's call.
|
| 101 |
+
for connector in self.connectors:
|
| 102 |
+
timer = self.timers[str(connector)]
|
| 103 |
+
with timer:
|
| 104 |
+
batch = connector(
|
| 105 |
+
rl_module=rl_module,
|
| 106 |
+
batch=batch,
|
| 107 |
+
episodes=episodes,
|
| 108 |
+
explore=explore,
|
| 109 |
+
shared_data=shared_data,
|
| 110 |
+
# Deprecated arg.
|
| 111 |
+
data=batch,
|
| 112 |
+
**kwargs,
|
| 113 |
+
)
|
| 114 |
+
if not isinstance(batch, dict):
|
| 115 |
+
raise ValueError(
|
| 116 |
+
f"`data` returned by ConnectorV2 {connector} must be a dict! "
|
| 117 |
+
f"You returned {batch}. Check your (custom) connectors' "
|
| 118 |
+
f"`__call__()` method's return value and make sure you return "
|
| 119 |
+
f"the `data` arg passed in (either altered or unchanged)."
|
| 120 |
+
)
|
| 121 |
+
return batch
|
| 122 |
+
|
| 123 |
+
def remove(self, name_or_class: Union[str, Type]):
|
| 124 |
+
"""Remove a single connector piece in this pipeline by its name or class.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
name: The name of the connector piece to be removed from the pipeline.
|
| 128 |
+
"""
|
| 129 |
+
idx = -1
|
| 130 |
+
for i, c in enumerate(self.connectors):
|
| 131 |
+
if c.__class__.__name__ == name_or_class:
|
| 132 |
+
idx = i
|
| 133 |
+
break
|
| 134 |
+
if idx >= 0:
|
| 135 |
+
del self.connectors[idx]
|
| 136 |
+
self._fix_spaces(self.input_observation_space, self.input_action_space)
|
| 137 |
+
logger.info(
|
| 138 |
+
f"Removed connector {name_or_class} from {self.__class__.__name__}."
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
logger.warning(
|
| 142 |
+
f"Trying to remove a non-existent connector {name_or_class}."
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def insert_before(
|
| 146 |
+
self,
|
| 147 |
+
name_or_class: Union[str, type],
|
| 148 |
+
connector: ConnectorV2,
|
| 149 |
+
) -> ConnectorV2:
|
| 150 |
+
"""Insert a new connector piece before an existing piece (by name or class).
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
name_or_class: Name or class of the connector piece before which `connector`
|
| 154 |
+
will get inserted.
|
| 155 |
+
connector: The new connector piece to be inserted.
|
| 156 |
+
|
| 157 |
+
Returns:
|
| 158 |
+
The ConnectorV2 before which `connector` has been inserted.
|
| 159 |
+
"""
|
| 160 |
+
idx = -1
|
| 161 |
+
for idx, c in enumerate(self.connectors):
|
| 162 |
+
if (
|
| 163 |
+
isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class
|
| 164 |
+
) or (isinstance(name_or_class, type) and c.__class__ is name_or_class):
|
| 165 |
+
break
|
| 166 |
+
if idx < 0:
|
| 167 |
+
raise ValueError(
|
| 168 |
+
f"Can not find connector with name or type '{name_or_class}'!"
|
| 169 |
+
)
|
| 170 |
+
next_connector = self.connectors[idx]
|
| 171 |
+
|
| 172 |
+
self.connectors.insert(idx, connector)
|
| 173 |
+
self._fix_spaces(self.input_observation_space, self.input_action_space)
|
| 174 |
+
|
| 175 |
+
logger.info(
|
| 176 |
+
f"Inserted {connector.__class__.__name__} before {name_or_class} "
|
| 177 |
+
f"to {self.__class__.__name__}."
|
| 178 |
+
)
|
| 179 |
+
return next_connector
|
| 180 |
+
|
| 181 |
+
def insert_after(
|
| 182 |
+
self,
|
| 183 |
+
name_or_class: Union[str, Type],
|
| 184 |
+
connector: ConnectorV2,
|
| 185 |
+
) -> ConnectorV2:
|
| 186 |
+
"""Insert a new connector piece after an existing piece (by name or class).
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
name_or_class: Name or class of the connector piece after which `connector`
|
| 190 |
+
will get inserted.
|
| 191 |
+
connector: The new connector piece to be inserted.
|
| 192 |
+
|
| 193 |
+
Returns:
|
| 194 |
+
The ConnectorV2 after which `connector` has been inserted.
|
| 195 |
+
"""
|
| 196 |
+
idx = -1
|
| 197 |
+
for idx, c in enumerate(self.connectors):
|
| 198 |
+
if (
|
| 199 |
+
isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class
|
| 200 |
+
) or (isinstance(name_or_class, type) and c.__class__ is name_or_class):
|
| 201 |
+
break
|
| 202 |
+
if idx < 0:
|
| 203 |
+
raise ValueError(
|
| 204 |
+
f"Can not find connector with name or type '{name_or_class}'!"
|
| 205 |
+
)
|
| 206 |
+
prev_connector = self.connectors[idx]
|
| 207 |
+
|
| 208 |
+
self.connectors.insert(idx + 1, connector)
|
| 209 |
+
self._fix_spaces(self.input_observation_space, self.input_action_space)
|
| 210 |
+
|
| 211 |
+
logger.info(
|
| 212 |
+
f"Inserted {connector.__class__.__name__} after {name_or_class} "
|
| 213 |
+
f"to {self.__class__.__name__}."
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
return prev_connector
|
| 217 |
+
|
| 218 |
+
def prepend(self, connector: ConnectorV2) -> None:
|
| 219 |
+
"""Prepend a new connector at the beginning of a connector pipeline.
|
| 220 |
+
|
| 221 |
+
Args:
|
| 222 |
+
connector: The new connector piece to be prepended to this pipeline.
|
| 223 |
+
"""
|
| 224 |
+
self.connectors.insert(0, connector)
|
| 225 |
+
self._fix_spaces(self.input_observation_space, self.input_action_space)
|
| 226 |
+
|
| 227 |
+
logger.info(
|
| 228 |
+
f"Added {connector.__class__.__name__} to the beginning of "
|
| 229 |
+
f"{self.__class__.__name__}."
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def append(self, connector: ConnectorV2) -> None:
|
| 233 |
+
"""Append a new connector at the end of a connector pipeline.
|
| 234 |
+
|
| 235 |
+
Args:
|
| 236 |
+
connector: The new connector piece to be appended to this pipeline.
|
| 237 |
+
"""
|
| 238 |
+
self.connectors.append(connector)
|
| 239 |
+
self._fix_spaces(self.input_observation_space, self.input_action_space)
|
| 240 |
+
|
| 241 |
+
logger.info(
|
| 242 |
+
f"Added {connector.__class__.__name__} to the end of "
|
| 243 |
+
f"{self.__class__.__name__}."
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
@override(ConnectorV2)
|
| 247 |
+
def get_state(
|
| 248 |
+
self,
|
| 249 |
+
components: Optional[Union[str, Collection[str]]] = None,
|
| 250 |
+
*,
|
| 251 |
+
not_components: Optional[Union[str, Collection[str]]] = None,
|
| 252 |
+
**kwargs,
|
| 253 |
+
) -> StateDict:
|
| 254 |
+
state = {}
|
| 255 |
+
for conn in self.connectors:
|
| 256 |
+
conn_name = type(conn).__name__
|
| 257 |
+
if self._check_component(conn_name, components, not_components):
|
| 258 |
+
state[conn_name] = conn.get_state(
|
| 259 |
+
components=self._get_subcomponents(conn_name, components),
|
| 260 |
+
not_components=self._get_subcomponents(conn_name, not_components),
|
| 261 |
+
**kwargs,
|
| 262 |
+
)
|
| 263 |
+
return state
|
| 264 |
+
|
| 265 |
+
@override(ConnectorV2)
|
| 266 |
+
def set_state(self, state: Dict[str, Any]) -> None:
|
| 267 |
+
for conn in self.connectors:
|
| 268 |
+
conn_name = type(conn).__name__
|
| 269 |
+
if conn_name in state:
|
| 270 |
+
conn.set_state(state[conn_name])
|
| 271 |
+
|
| 272 |
+
@override(Checkpointable)
|
| 273 |
+
def get_checkpointable_components(self) -> List[Tuple[str, "Checkpointable"]]:
|
| 274 |
+
return [(type(conn).__name__, conn) for conn in self.connectors]
|
| 275 |
+
|
| 276 |
+
# Note that we don't have to override Checkpointable.get_ctor_args_and_kwargs and
|
| 277 |
+
# don't have to return the `connectors` c'tor kwarg from there. This is b/c all
|
| 278 |
+
# connector pieces in this pipeline are themselves Checkpointable components,
|
| 279 |
+
# so they will be properly written into this pipeline's checkpoint.
|
| 280 |
+
@override(Checkpointable)
|
| 281 |
+
def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]:
|
| 282 |
+
return (
|
| 283 |
+
(self.input_observation_space, self.input_action_space), # *args
|
| 284 |
+
{
|
| 285 |
+
"connectors": [
|
| 286 |
+
(type(conn), *conn.get_ctor_args_and_kwargs())
|
| 287 |
+
for conn in self.connectors
|
| 288 |
+
]
|
| 289 |
+
},
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
@override(ConnectorV2)
|
| 293 |
+
def reset_state(self) -> None:
|
| 294 |
+
for conn in self.connectors:
|
| 295 |
+
conn.reset_state()
|
| 296 |
+
|
| 297 |
+
@override(ConnectorV2)
|
| 298 |
+
def merge_states(self, states: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 299 |
+
merged_states = {}
|
| 300 |
+
if not states:
|
| 301 |
+
return merged_states
|
| 302 |
+
for i, (key, item) in enumerate(states[0].items()):
|
| 303 |
+
state_list = [state[key] for state in states]
|
| 304 |
+
conn = self.connectors[i]
|
| 305 |
+
merged_states[key] = conn.merge_states(state_list)
|
| 306 |
+
return merged_states
|
| 307 |
+
|
| 308 |
+
def __repr__(self, indentation: int = 0):
|
| 309 |
+
return "\n".join(
|
| 310 |
+
[" " * indentation + self.__class__.__name__]
|
| 311 |
+
+ [c.__str__(indentation + 4) for c in self.connectors]
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
def __getitem__(
|
| 315 |
+
self,
|
| 316 |
+
key: Union[str, int, Type],
|
| 317 |
+
) -> Union[ConnectorV2, List[ConnectorV2]]:
|
| 318 |
+
"""Returns a single ConnectorV2 or list of ConnectorV2s that fit `key`.
|
| 319 |
+
|
| 320 |
+
If key is an int, we return a single ConnectorV2 at that index in this pipeline.
|
| 321 |
+
If key is a ConnectorV2 type or a string matching the class name of a
|
| 322 |
+
ConnectorV2 in this pipeline, we return a list of all ConnectorV2s in this
|
| 323 |
+
pipeline matching the specified class.
|
| 324 |
+
|
| 325 |
+
Args:
|
| 326 |
+
key: The key to find or to index by.
|
| 327 |
+
|
| 328 |
+
Returns:
|
| 329 |
+
A single ConnectorV2 or a list of ConnectorV2s matching `key`.
|
| 330 |
+
"""
|
| 331 |
+
# Key is an int -> Index into pipeline and return.
|
| 332 |
+
if isinstance(key, int):
|
| 333 |
+
return self.connectors[key]
|
| 334 |
+
# Key is a class.
|
| 335 |
+
elif isinstance(key, type):
|
| 336 |
+
results = []
|
| 337 |
+
for c in self.connectors:
|
| 338 |
+
if issubclass(c.__class__, key):
|
| 339 |
+
results.append(c)
|
| 340 |
+
return results
|
| 341 |
+
# Key is a string -> Find connector(s) by name.
|
| 342 |
+
elif isinstance(key, str):
|
| 343 |
+
results = []
|
| 344 |
+
for c in self.connectors:
|
| 345 |
+
if c.name == key:
|
| 346 |
+
results.append(c)
|
| 347 |
+
return results
|
| 348 |
+
# Slicing not supported (yet).
|
| 349 |
+
elif isinstance(key, slice):
|
| 350 |
+
raise NotImplementedError(
|
| 351 |
+
"Slicing of ConnectorPipelineV2 is currently not supported!"
|
| 352 |
+
)
|
| 353 |
+
else:
|
| 354 |
+
raise NotImplementedError(
|
| 355 |
+
f"Indexing ConnectorPipelineV2 by {type(key)} is currently not "
|
| 356 |
+
f"supported!"
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
@property
|
| 360 |
+
def observation_space(self):
|
| 361 |
+
if len(self) > 0:
|
| 362 |
+
return self.connectors[-1].observation_space
|
| 363 |
+
return self._observation_space
|
| 364 |
+
|
| 365 |
+
@property
|
| 366 |
+
def action_space(self):
|
| 367 |
+
if len(self) > 0:
|
| 368 |
+
return self.connectors[-1].action_space
|
| 369 |
+
return self._action_space
|
| 370 |
+
|
| 371 |
+
def _fix_spaces(self, input_observation_space, input_action_space):
|
| 372 |
+
if len(self) > 0:
|
| 373 |
+
# Fix each connector's input_observation- and input_action space in
|
| 374 |
+
# the pipeline.
|
| 375 |
+
obs_space = input_observation_space
|
| 376 |
+
act_space = input_action_space
|
| 377 |
+
for con in self.connectors:
|
| 378 |
+
con.input_action_space = act_space
|
| 379 |
+
con.input_observation_space = obs_space
|
| 380 |
+
obs_space = con.observation_space
|
| 381 |
+
act_space = con.action_space
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/connector_v2.py
ADDED
|
@@ -0,0 +1,1013 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
import inspect
|
| 4 |
+
from typing import (
|
| 5 |
+
Any,
|
| 6 |
+
Callable,
|
| 7 |
+
Collection,
|
| 8 |
+
Dict,
|
| 9 |
+
Iterator,
|
| 10 |
+
List,
|
| 11 |
+
Optional,
|
| 12 |
+
Tuple,
|
| 13 |
+
Union,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
import gymnasium as gym
|
| 17 |
+
import tree
|
| 18 |
+
|
| 19 |
+
from ray.rllib.core.rl_module.rl_module import RLModule
|
| 20 |
+
from ray.rllib.env.single_agent_episode import SingleAgentEpisode
|
| 21 |
+
from ray.rllib.utils import force_list
|
| 22 |
+
from ray.rllib.utils.annotations import override, OverrideToImplementCustomLogic
|
| 23 |
+
from ray.rllib.utils.checkpoints import Checkpointable
|
| 24 |
+
from ray.rllib.utils.spaces.space_utils import BatchedNdArray
|
| 25 |
+
from ray.rllib.utils.typing import AgentID, EpisodeType, ModuleID, StateDict
|
| 26 |
+
from ray.util.annotations import PublicAPI
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@PublicAPI(stability="alpha")
|
| 30 |
+
class ConnectorV2(Checkpointable, abc.ABC):
|
| 31 |
+
"""Base class defining the API for an individual "connector piece".
|
| 32 |
+
|
| 33 |
+
A ConnectorV2 ("connector piece") is usually part of a whole series of connector
|
| 34 |
+
pieces within a so-called connector pipeline, which in itself also abides to this
|
| 35 |
+
very API.
|
| 36 |
+
For example, you might have a connector pipeline consisting of two connector pieces,
|
| 37 |
+
A and B, both instances of subclasses of ConnectorV2 and each one performing a
|
| 38 |
+
particular transformation on their input data. The resulting connector pipeline
|
| 39 |
+
(A->B) itself also abides to this very ConnectorV2 API and could thus be part of yet
|
| 40 |
+
another, higher-level connector pipeline, e.g. (A->B)->C->D.
|
| 41 |
+
|
| 42 |
+
Any ConnectorV2 instance (individual pieces or several connector pieces in a
|
| 43 |
+
pipeline) is a callable and users should override the `__call__()` method.
|
| 44 |
+
When called, they take the outputs of a previous connector piece (or an empty dict
|
| 45 |
+
if there are no previous pieces) and all the data collected thus far in the
|
| 46 |
+
ongoing episode(s) (only applies to connectors used in EnvRunners) or retrieved
|
| 47 |
+
from a replay buffer or from an environment sampling step (only applies to
|
| 48 |
+
connectors used in Learner pipelines). From this input data, a ConnectorV2 then
|
| 49 |
+
performs a transformation step.
|
| 50 |
+
|
| 51 |
+
There are 3 types of pipelines any ConnectorV2 piece can belong to:
|
| 52 |
+
1) EnvToModulePipeline: The connector transforms environment data before it gets to
|
| 53 |
+
the RLModule. This type of pipeline is used by an EnvRunner for transforming
|
| 54 |
+
env output data into RLModule readable data (for the next RLModule forward pass).
|
| 55 |
+
For example, such a pipeline would include observation postprocessors, -filters,
|
| 56 |
+
or any RNN preparation code related to time-sequences and zero-padding.
|
| 57 |
+
2) ModuleToEnvPipeline: This type of pipeline is used by an
|
| 58 |
+
EnvRunner to transform RLModule output data to env readable actions (for the next
|
| 59 |
+
`env.step()` call). For example, in case the RLModule only outputs action
|
| 60 |
+
distribution parameters (but not actual actions), the ModuleToEnvPipeline would
|
| 61 |
+
take care of sampling the actions to be sent back to the end from the
|
| 62 |
+
resulting distribution (made deterministic if exploration is off).
|
| 63 |
+
3) LearnerConnectorPipeline: This connector pipeline type transforms data coming
|
| 64 |
+
from an `EnvRunner.sample()` call or a replay buffer and will then be sent into the
|
| 65 |
+
RLModule's `forward_train()` method in order to compute loss function inputs.
|
| 66 |
+
This type of pipeline is used by a Learner worker to transform raw training data
|
| 67 |
+
(a batch or a list of episodes) to RLModule readable training data (for the next
|
| 68 |
+
RLModule `forward_train()` call).
|
| 69 |
+
|
| 70 |
+
Some connectors might be stateful, for example for keeping track of observation
|
| 71 |
+
filtering stats (mean and stddev values). Any Algorithm, which uses connectors is
|
| 72 |
+
responsible for frequently synchronizing the states of all connectors and connector
|
| 73 |
+
pipelines between the EnvRunners (owning the env-to-module and module-to-env
|
| 74 |
+
pipelines) and the Learners (owning the Learner pipelines).
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
input_observation_space: Optional[gym.Space] = None,
|
| 80 |
+
input_action_space: Optional[gym.Space] = None,
|
| 81 |
+
**kwargs,
|
| 82 |
+
):
|
| 83 |
+
"""Initializes a ConnectorV2 instance.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
input_observation_space: The (optional) input observation space for this
|
| 87 |
+
connector piece. This is the space coming from a previous connector
|
| 88 |
+
piece in the (env-to-module or learner) pipeline or is directly
|
| 89 |
+
defined within the gym.Env.
|
| 90 |
+
input_action_space: The (optional) input action space for this connector
|
| 91 |
+
piece. This is the space coming from a previous connector piece in the
|
| 92 |
+
(module-to-env) pipeline or is directly defined within the gym.Env.
|
| 93 |
+
**kwargs: Forward API-compatibility kwargs.
|
| 94 |
+
"""
|
| 95 |
+
self._observation_space = None
|
| 96 |
+
self._action_space = None
|
| 97 |
+
self._input_observation_space = None
|
| 98 |
+
self._input_action_space = None
|
| 99 |
+
|
| 100 |
+
self.input_action_space = input_action_space
|
| 101 |
+
self.input_observation_space = input_observation_space
|
| 102 |
+
|
| 103 |
+
# Store child's constructor args and kwargs for the default
|
| 104 |
+
# `get_ctor_args_and_kwargs` implementation (to be able to restore from a
|
| 105 |
+
# checkpoint).
|
| 106 |
+
if self.__class__.__dict__.get("__init__") is not None:
|
| 107 |
+
caller_frame = inspect.stack()[1].frame
|
| 108 |
+
arg_info = inspect.getargvalues(caller_frame)
|
| 109 |
+
# Separate positional arguments and keyword arguments.
|
| 110 |
+
caller_locals = (
|
| 111 |
+
arg_info.locals
|
| 112 |
+
) # Dictionary of all local variables in the caller
|
| 113 |
+
self._ctor_kwargs = {
|
| 114 |
+
arg: caller_locals[arg] for arg in arg_info.args if arg != "self"
|
| 115 |
+
}
|
| 116 |
+
else:
|
| 117 |
+
self._ctor_kwargs = {
|
| 118 |
+
"input_observation_space": self.input_observation_space,
|
| 119 |
+
"input_action_space": self.input_action_space,
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
@OverrideToImplementCustomLogic
|
| 123 |
+
def recompute_output_observation_space(
|
| 124 |
+
self,
|
| 125 |
+
input_observation_space: gym.Space,
|
| 126 |
+
input_action_space: gym.Space,
|
| 127 |
+
) -> gym.Space:
|
| 128 |
+
"""Re-computes a new (output) observation space based on the input spaces.
|
| 129 |
+
|
| 130 |
+
This method should be overridden by users to make sure a ConnectorPipelineV2
|
| 131 |
+
knows how the input spaces through its individual ConnectorV2 pieces are being
|
| 132 |
+
transformed.
|
| 133 |
+
|
| 134 |
+
.. testcode::
|
| 135 |
+
|
| 136 |
+
from gymnasium.spaces import Box, Discrete
|
| 137 |
+
import numpy as np
|
| 138 |
+
|
| 139 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 140 |
+
from ray.rllib.utils.numpy import one_hot
|
| 141 |
+
from ray.rllib.utils.test_utils import check
|
| 142 |
+
|
| 143 |
+
class OneHotConnector(ConnectorV2):
|
| 144 |
+
def recompute_output_observation_space(
|
| 145 |
+
self,
|
| 146 |
+
input_observation_space,
|
| 147 |
+
input_action_space,
|
| 148 |
+
):
|
| 149 |
+
return Box(0.0, 1.0, (input_observation_space.n,), np.float32)
|
| 150 |
+
|
| 151 |
+
def __call__(
|
| 152 |
+
self,
|
| 153 |
+
*,
|
| 154 |
+
rl_module,
|
| 155 |
+
batch,
|
| 156 |
+
episodes,
|
| 157 |
+
explore=None,
|
| 158 |
+
shared_data=None,
|
| 159 |
+
**kwargs,
|
| 160 |
+
):
|
| 161 |
+
assert "obs" in batch
|
| 162 |
+
batch["obs"] = one_hot(batch["obs"])
|
| 163 |
+
return batch
|
| 164 |
+
|
| 165 |
+
connector = OneHotConnector(input_observation_space=Discrete(2))
|
| 166 |
+
batch = {"obs": np.array([1, 0, 0], np.int32)}
|
| 167 |
+
output = connector(rl_module=None, batch=batch, episodes=None)
|
| 168 |
+
|
| 169 |
+
check(output, {"obs": np.array([[0.0, 1.0], [1.0, 0.0], [1.0, 0.0]])})
|
| 170 |
+
|
| 171 |
+
If this ConnectorV2 does not change the observation space in any way, leave
|
| 172 |
+
this parent method implementation untouched.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
input_observation_space: The input observation space (either coming from the
|
| 176 |
+
environment if `self` is the first connector piece in the pipeline or
|
| 177 |
+
from the previous connector piece in the pipeline).
|
| 178 |
+
input_action_space: The input action space (either coming from the
|
| 179 |
+
environment if `self is the first connector piece in the pipeline or
|
| 180 |
+
from the previous connector piece in the pipeline).
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
The new observation space (after data has passed through this ConnectorV2
|
| 184 |
+
piece).
|
| 185 |
+
"""
|
| 186 |
+
return self.input_observation_space
|
| 187 |
+
|
| 188 |
+
@OverrideToImplementCustomLogic
|
| 189 |
+
def recompute_output_action_space(
|
| 190 |
+
self,
|
| 191 |
+
input_observation_space: gym.Space,
|
| 192 |
+
input_action_space: gym.Space,
|
| 193 |
+
) -> gym.Space:
|
| 194 |
+
"""Re-computes a new (output) action space based on the input space.
|
| 195 |
+
|
| 196 |
+
This method should be overridden by users to make sure a ConnectorPipelineV2
|
| 197 |
+
knows how the input spaces through its individual ConnectorV2 pieces are being
|
| 198 |
+
transformed.
|
| 199 |
+
|
| 200 |
+
If this ConnectorV2 does not change the action space in any way, leave
|
| 201 |
+
this parent method implementation untouched.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
input_observation_space: The input observation space (either coming from the
|
| 205 |
+
environment if `self` is the first connector piece in the pipeline or
|
| 206 |
+
from the previous connector piece in the pipeline).
|
| 207 |
+
input_action_space: The input action space (either coming from the
|
| 208 |
+
environment if `self is the first connector piece in the pipeline or
|
| 209 |
+
from the previous connector piece in the pipeline).
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
The new action space (after data has passed through this ConenctorV2
|
| 213 |
+
piece).
|
| 214 |
+
"""
|
| 215 |
+
return self.input_action_space
|
| 216 |
+
|
| 217 |
+
@abc.abstractmethod
|
| 218 |
+
def __call__(
|
| 219 |
+
self,
|
| 220 |
+
*,
|
| 221 |
+
rl_module: RLModule,
|
| 222 |
+
batch: Dict[str, Any],
|
| 223 |
+
episodes: List[EpisodeType],
|
| 224 |
+
explore: Optional[bool] = None,
|
| 225 |
+
shared_data: Optional[dict] = None,
|
| 226 |
+
**kwargs,
|
| 227 |
+
) -> Any:
|
| 228 |
+
"""Method for transforming an input `batch` into an output `batch`.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
rl_module: The RLModule object that the connector connects to or from.
|
| 232 |
+
batch: The input data to be transformed by this connector. Transformations
|
| 233 |
+
might either be done in-place or a new structure may be returned.
|
| 234 |
+
Note that the information in `batch` will eventually either become the
|
| 235 |
+
forward batch for the RLModule (env-to-module and learner connectors)
|
| 236 |
+
or the input to the `env.step()` call (module-to-env connectors). Note
|
| 237 |
+
that in the first case (`batch` is a forward batch for RLModule), the
|
| 238 |
+
information in `batch` will be discarded after that RLModule forward
|
| 239 |
+
pass. Any transformation of information (e.g. observation preprocessing)
|
| 240 |
+
that you have only done inside `batch` will be lost, unless you have
|
| 241 |
+
written it back into the corresponding `episodes` during the connector
|
| 242 |
+
pass.
|
| 243 |
+
episodes: The list of SingleAgentEpisode or MultiAgentEpisode objects,
|
| 244 |
+
each corresponding to one slot in the vector env. Note that episodes
|
| 245 |
+
can be read from (e.g. to place information into `batch`), but also
|
| 246 |
+
written to. You should only write back (changed, transformed)
|
| 247 |
+
information into the episodes, if you want these changes to be
|
| 248 |
+
"permanent". For example if you sample from an environment, pick up
|
| 249 |
+
observations from the episodes and place them into `batch`, then
|
| 250 |
+
transform these observations, and would like to make these
|
| 251 |
+
transformations permanent (note that `batch` gets discarded after the
|
| 252 |
+
RLModule forward pass), then you have to write the transformed
|
| 253 |
+
observations back into the episode to make sure you do not have to
|
| 254 |
+
perform the same transformation again on the learner (or replay buffer)
|
| 255 |
+
side. The Learner will hence work on the already changed episodes (and
|
| 256 |
+
compile the train batch using the Learner connector).
|
| 257 |
+
explore: Whether `explore` is currently on. Per convention, if True, the
|
| 258 |
+
RLModule's `forward_exploration` method should be called, if False, the
|
| 259 |
+
EnvRunner should call `forward_inference` instead.
|
| 260 |
+
shared_data: Optional additional context data that needs to be exchanged
|
| 261 |
+
between different ConnectorV2 pieces (in the same pipeline) or across
|
| 262 |
+
ConnectorV2 pipelines (meaning between env-to-module and module-to-env).
|
| 263 |
+
kwargs: Forward API-compatibility kwargs.
|
| 264 |
+
|
| 265 |
+
Returns:
|
| 266 |
+
The transformed connector output.
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
@staticmethod
|
| 270 |
+
def single_agent_episode_iterator(
|
| 271 |
+
episodes: List[EpisodeType],
|
| 272 |
+
agents_that_stepped_only: bool = True,
|
| 273 |
+
zip_with_batch_column: Optional[Union[List[Any], Dict[Tuple, Any]]] = None,
|
| 274 |
+
) -> Iterator[SingleAgentEpisode]:
|
| 275 |
+
"""An iterator over a list of episodes yielding always SingleAgentEpisodes.
|
| 276 |
+
|
| 277 |
+
In case items in the list are MultiAgentEpisodes, these are broken down
|
| 278 |
+
into their individual agents' SingleAgentEpisodes and those are then yielded
|
| 279 |
+
one after the other.
|
| 280 |
+
|
| 281 |
+
Useful for connectors that operate on both single-agent and multi-agent
|
| 282 |
+
episodes.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
episodes: The list of SingleAgent- or MultiAgentEpisode objects.
|
| 286 |
+
agents_that_stepped_only: If True (and multi-agent setup), will only place
|
| 287 |
+
items of those agents into the batch that have just stepped in the
|
| 288 |
+
actual MultiAgentEpisode (this is checked via a
|
| 289 |
+
`MultiAgentEpside.episode.get_agents_to_act()`). Note that this setting
|
| 290 |
+
is ignored in a single-agent setups b/c the agent steps at each timestep
|
| 291 |
+
regardless.
|
| 292 |
+
zip_with_batch_column: If provided, must be a list of batch items
|
| 293 |
+
corresponding to the given `episodes` (single agent case) or a dict
|
| 294 |
+
mapping (AgentID, ModuleID) tuples to lists of individual batch items
|
| 295 |
+
corresponding to this agent/module combination. The iterator will then
|
| 296 |
+
yield tuples of SingleAgentEpisode objects (1st item) along with the
|
| 297 |
+
data item (2nd item) that this episode was responsible for generating
|
| 298 |
+
originally.
|
| 299 |
+
|
| 300 |
+
Yields:
|
| 301 |
+
All SingleAgentEpisodes in the input list, whereby MultiAgentEpisodes will
|
| 302 |
+
be broken down into their individual SingleAgentEpisode components.
|
| 303 |
+
"""
|
| 304 |
+
list_indices = defaultdict(int)
|
| 305 |
+
|
| 306 |
+
# Single-agent case.
|
| 307 |
+
if episodes and isinstance(episodes[0], SingleAgentEpisode):
|
| 308 |
+
if zip_with_batch_column is not None:
|
| 309 |
+
if len(zip_with_batch_column) != len(episodes):
|
| 310 |
+
raise ValueError(
|
| 311 |
+
"Invalid `zip_with_batch_column` data: Must have the same "
|
| 312 |
+
f"length as the list of episodes ({len(episodes)}), but has "
|
| 313 |
+
f"length {len(zip_with_batch_column)}!"
|
| 314 |
+
)
|
| 315 |
+
# Simple case: Items are stored in lists directly under the column (str)
|
| 316 |
+
# key.
|
| 317 |
+
if isinstance(zip_with_batch_column, list):
|
| 318 |
+
for episode, data in zip(episodes, zip_with_batch_column):
|
| 319 |
+
yield episode, data
|
| 320 |
+
# Normal single-agent case: Items are stored in dicts under the column
|
| 321 |
+
# (str) key. These dicts map (eps_id,)-tuples to lists of individual
|
| 322 |
+
# items.
|
| 323 |
+
else:
|
| 324 |
+
for episode, (eps_id_tuple, data) in zip(
|
| 325 |
+
episodes,
|
| 326 |
+
zip_with_batch_column.items(),
|
| 327 |
+
):
|
| 328 |
+
assert episode.id_ == eps_id_tuple[0]
|
| 329 |
+
d = data[list_indices[eps_id_tuple]]
|
| 330 |
+
list_indices[eps_id_tuple] += 1
|
| 331 |
+
yield episode, d
|
| 332 |
+
else:
|
| 333 |
+
for episode in episodes:
|
| 334 |
+
yield episode
|
| 335 |
+
return
|
| 336 |
+
|
| 337 |
+
# Multi-agent case.
|
| 338 |
+
for episode in episodes:
|
| 339 |
+
for agent_id in (
|
| 340 |
+
episode.get_agents_that_stepped()
|
| 341 |
+
if agents_that_stepped_only
|
| 342 |
+
else episode.agent_ids
|
| 343 |
+
):
|
| 344 |
+
sa_episode = episode.agent_episodes[agent_id]
|
| 345 |
+
# for sa_episode in episode.agent_episodes.values():
|
| 346 |
+
if zip_with_batch_column is not None:
|
| 347 |
+
key = (
|
| 348 |
+
sa_episode.multi_agent_episode_id,
|
| 349 |
+
sa_episode.agent_id,
|
| 350 |
+
sa_episode.module_id,
|
| 351 |
+
)
|
| 352 |
+
if len(zip_with_batch_column[key]) <= list_indices[key]:
|
| 353 |
+
raise ValueError(
|
| 354 |
+
"Invalid `zip_with_batch_column` data: Must structurally "
|
| 355 |
+
"match the single-agent contents in the given list of "
|
| 356 |
+
"(multi-agent) episodes!"
|
| 357 |
+
)
|
| 358 |
+
d = zip_with_batch_column[key][list_indices[key]]
|
| 359 |
+
list_indices[key] += 1
|
| 360 |
+
yield sa_episode, d
|
| 361 |
+
else:
|
| 362 |
+
yield sa_episode
|
| 363 |
+
|
| 364 |
+
@staticmethod
|
| 365 |
+
def add_batch_item(
|
| 366 |
+
batch: Dict[str, Any],
|
| 367 |
+
column: str,
|
| 368 |
+
item_to_add: Any,
|
| 369 |
+
single_agent_episode: Optional[SingleAgentEpisode] = None,
|
| 370 |
+
) -> None:
|
| 371 |
+
"""Adds a data item under `column` to the given `batch`.
|
| 372 |
+
|
| 373 |
+
The `item_to_add` is stored in the `batch` in the following manner:
|
| 374 |
+
1) If `single_agent_episode` is not provided (None), will store the item in a
|
| 375 |
+
list directly under `column`:
|
| 376 |
+
`column` -> [item, item, ...]
|
| 377 |
+
2) If `single_agent_episode`'s `agent_id` and `module_id` properties are None
|
| 378 |
+
(`single_agent_episode` is not part of a multi-agent episode), will append
|
| 379 |
+
`item_to_add` to a list under a `(<episodeID>,)` key under `column`:
|
| 380 |
+
`column` -> `(<episodeID>,)` -> [item, item, ...]
|
| 381 |
+
3) If `single_agent_episode`'s `agent_id` and `module_id` are NOT None
|
| 382 |
+
(`single_agent_episode` is part of a multi-agent episode), will append
|
| 383 |
+
`item_to_add` to a list under a `(<episodeID>,<AgentID>,<ModuleID>)` key
|
| 384 |
+
under `column`:
|
| 385 |
+
`column` -> `(<episodeID>,<AgentID>,<ModuleID>)` -> [item, item, ...]
|
| 386 |
+
|
| 387 |
+
See the these examples here for clarification of these three cases:
|
| 388 |
+
|
| 389 |
+
.. testcode::
|
| 390 |
+
|
| 391 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 392 |
+
from ray.rllib.env.multi_agent_episode import MultiAgentEpisode
|
| 393 |
+
from ray.rllib.env.single_agent_episode import SingleAgentEpisode
|
| 394 |
+
from ray.rllib.utils.test_utils import check
|
| 395 |
+
|
| 396 |
+
# 1) Simple case (no episodes provided) -> Store data in a list directly
|
| 397 |
+
# under `column`:
|
| 398 |
+
batch = {}
|
| 399 |
+
ConnectorV2.add_batch_item(batch, "test_col", item_to_add=5)
|
| 400 |
+
ConnectorV2.add_batch_item(batch, "test_col", item_to_add=6)
|
| 401 |
+
check(batch, {"test_col": [5, 6]})
|
| 402 |
+
ConnectorV2.add_batch_item(batch, "test_col_2", item_to_add=-10)
|
| 403 |
+
check(batch, {
|
| 404 |
+
"test_col": [5, 6],
|
| 405 |
+
"test_col_2": [-10],
|
| 406 |
+
})
|
| 407 |
+
|
| 408 |
+
# 2) Single-agent case (SingleAgentEpisode provided) -> Store data in a list
|
| 409 |
+
# under the keys: `column` -> `(<eps_id>,)` -> [...]:
|
| 410 |
+
batch = {}
|
| 411 |
+
episode = SingleAgentEpisode(
|
| 412 |
+
id_="SA-EPS0",
|
| 413 |
+
observations=[0, 1, 2, 3],
|
| 414 |
+
actions=[1, 2, 3],
|
| 415 |
+
rewards=[1.0, 2.0, 3.0],
|
| 416 |
+
)
|
| 417 |
+
ConnectorV2.add_batch_item(batch, "test_col", 5, episode)
|
| 418 |
+
ConnectorV2.add_batch_item(batch, "test_col", 6, episode)
|
| 419 |
+
ConnectorV2.add_batch_item(batch, "test_col_2", -10, episode)
|
| 420 |
+
check(batch, {
|
| 421 |
+
"test_col": {("SA-EPS0",): [5, 6]},
|
| 422 |
+
"test_col_2": {("SA-EPS0",): [-10]},
|
| 423 |
+
})
|
| 424 |
+
|
| 425 |
+
# 3) Multi-agent case (SingleAgentEpisode provided that has `agent_id` and
|
| 426 |
+
# `module_id` information) -> Store data in a list under the keys:
|
| 427 |
+
# `column` -> `(<episodeID>,<AgentID>,<ModuleID>)` -> [...]:
|
| 428 |
+
batch = {}
|
| 429 |
+
ma_episode = MultiAgentEpisode(
|
| 430 |
+
id_="MA-EPS1",
|
| 431 |
+
observations=[
|
| 432 |
+
{"ag0": 0, "ag1": 1}, {"ag0": 2, "ag1": 4}
|
| 433 |
+
],
|
| 434 |
+
actions=[{"ag0": 0, "ag1": 1}],
|
| 435 |
+
rewards=[{"ag0": -0.1, "ag1": -0.2}],
|
| 436 |
+
# ag0 maps to mod0, ag1 maps to mod1, etc..
|
| 437 |
+
agent_to_module_mapping_fn=lambda aid, eps: f"mod{aid[2:]}",
|
| 438 |
+
)
|
| 439 |
+
ConnectorV2.add_batch_item(
|
| 440 |
+
batch,
|
| 441 |
+
"test_col",
|
| 442 |
+
item_to_add=5,
|
| 443 |
+
single_agent_episode=ma_episode.agent_episodes["ag0"],
|
| 444 |
+
)
|
| 445 |
+
ConnectorV2.add_batch_item(
|
| 446 |
+
batch,
|
| 447 |
+
"test_col",
|
| 448 |
+
item_to_add=6,
|
| 449 |
+
single_agent_episode=ma_episode.agent_episodes["ag0"],
|
| 450 |
+
)
|
| 451 |
+
ConnectorV2.add_batch_item(
|
| 452 |
+
batch,
|
| 453 |
+
"test_col_2",
|
| 454 |
+
item_to_add=10,
|
| 455 |
+
single_agent_episode=ma_episode.agent_episodes["ag1"],
|
| 456 |
+
)
|
| 457 |
+
check(
|
| 458 |
+
batch,
|
| 459 |
+
{
|
| 460 |
+
"test_col": {("MA-EPS1", "ag0", "mod0"): [5, 6]},
|
| 461 |
+
"test_col_2": {("MA-EPS1", "ag1", "mod1"): [10]},
|
| 462 |
+
},
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
Args:
|
| 466 |
+
batch: The batch to store `item_to_add` in.
|
| 467 |
+
column: The column name (str) within the `batch` to store `item_to_add`
|
| 468 |
+
under.
|
| 469 |
+
item_to_add: The data item to store in the batch.
|
| 470 |
+
single_agent_episode: An optional SingleAgentEpisode.
|
| 471 |
+
If provided and its `agent_id` and `module_id` properties are None,
|
| 472 |
+
creates a further sub dictionary under `column`, mapping from
|
| 473 |
+
`(<episodeID>,)` to a list of data items (to which `item_to_add` will
|
| 474 |
+
be appended in this call).
|
| 475 |
+
If provided and its `agent_id` and `module_id` properties are NOT None,
|
| 476 |
+
creates a further sub dictionary under `column`, mapping from
|
| 477 |
+
`(<episodeID>,,<AgentID>,<ModuleID>)` to a list of data items (to which
|
| 478 |
+
`item_to_add` will be appended in this call).
|
| 479 |
+
If not provided, will append `item_to_add` to a list directly under
|
| 480 |
+
`column`.
|
| 481 |
+
"""
|
| 482 |
+
sub_key = None
|
| 483 |
+
# SAEpisode is provided ...
|
| 484 |
+
if single_agent_episode is not None:
|
| 485 |
+
module_id = single_agent_episode.module_id
|
| 486 |
+
# ... and has `module_id` AND that `module_id` is already a top-level key in
|
| 487 |
+
# `batch` (`batch` is already in module-major form, mapping ModuleID to
|
| 488 |
+
# columns mapping to data).
|
| 489 |
+
if module_id is not None and module_id in batch:
|
| 490 |
+
raise ValueError(
|
| 491 |
+
"Can't call `add_batch_item` on a `batch` that is already "
|
| 492 |
+
"module-major (meaning ModuleID is top-level with column names on "
|
| 493 |
+
"the level thereunder)! Make sure to only call `add_batch_items` "
|
| 494 |
+
"before the `AgentToModuleMapping` ConnectorV2 piece is applied."
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
# ... and has `agent_id` -> Use `single_agent_episode`'s agent ID and
|
| 498 |
+
# module ID.
|
| 499 |
+
elif single_agent_episode.agent_id is not None:
|
| 500 |
+
sub_key = (
|
| 501 |
+
single_agent_episode.multi_agent_episode_id,
|
| 502 |
+
single_agent_episode.agent_id,
|
| 503 |
+
single_agent_episode.module_id,
|
| 504 |
+
)
|
| 505 |
+
# Otherwise, just use episode's ID.
|
| 506 |
+
else:
|
| 507 |
+
sub_key = (single_agent_episode.id_,)
|
| 508 |
+
|
| 509 |
+
if column not in batch:
|
| 510 |
+
batch[column] = [] if sub_key is None else {sub_key: []}
|
| 511 |
+
if sub_key is not None:
|
| 512 |
+
if sub_key not in batch[column]:
|
| 513 |
+
batch[column][sub_key] = []
|
| 514 |
+
batch[column][sub_key].append(item_to_add)
|
| 515 |
+
else:
|
| 516 |
+
batch[column].append(item_to_add)
|
| 517 |
+
|
| 518 |
+
@staticmethod
|
| 519 |
+
def add_n_batch_items(
|
| 520 |
+
batch: Dict[str, Any],
|
| 521 |
+
column: str,
|
| 522 |
+
items_to_add: Any,
|
| 523 |
+
num_items: int,
|
| 524 |
+
single_agent_episode: Optional[SingleAgentEpisode] = None,
|
| 525 |
+
) -> None:
|
| 526 |
+
"""Adds a list of items (or batched item) under `column` to the given `batch`.
|
| 527 |
+
|
| 528 |
+
If `items_to_add` is not a list, but an already batched struct (of np.ndarray
|
| 529 |
+
leafs), the `items_to_add` will be appended to possibly existing data under the
|
| 530 |
+
same `column` as-is. A subsequent `BatchIndividualItems` ConnectorV2 piece will
|
| 531 |
+
recognize this and batch the data properly into a single (batched) item.
|
| 532 |
+
This is much faster than first splitting up `items_to_add` and then adding each
|
| 533 |
+
item individually.
|
| 534 |
+
|
| 535 |
+
If `single_agent_episode` is provided and its `agent_id` and `module_id`
|
| 536 |
+
properties are None, creates a further sub dictionary under `column`, mapping
|
| 537 |
+
from `(<episodeID>,)` to a list of data items (to which `items_to_add` will
|
| 538 |
+
be appended in this call).
|
| 539 |
+
If `single_agent_episode` is provided and its `agent_id` and `module_id`
|
| 540 |
+
properties are NOT None, creates a further sub dictionary under `column`,
|
| 541 |
+
mapping from `(<episodeID>,,<AgentID>,<ModuleID>)` to a list of data items (to
|
| 542 |
+
which `items_to_add` will be appended in this call).
|
| 543 |
+
If `single_agent_episode` is not provided, will append `items_to_add` to a list
|
| 544 |
+
directly under `column`.
|
| 545 |
+
|
| 546 |
+
.. testcode::
|
| 547 |
+
|
| 548 |
+
import numpy as np
|
| 549 |
+
|
| 550 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 551 |
+
from ray.rllib.env.multi_agent_episode import MultiAgentEpisode
|
| 552 |
+
from ray.rllib.env.single_agent_episode import SingleAgentEpisode
|
| 553 |
+
from ray.rllib.utils.test_utils import check
|
| 554 |
+
|
| 555 |
+
# Simple case (no episodes provided) -> Store data in a list directly under
|
| 556 |
+
# `column`:
|
| 557 |
+
batch = {}
|
| 558 |
+
ConnectorV2.add_n_batch_items(
|
| 559 |
+
batch,
|
| 560 |
+
"test_col",
|
| 561 |
+
# List of (complex) structs.
|
| 562 |
+
[{"a": np.array(3), "b": 4}, {"a": np.array(5), "b": 6}],
|
| 563 |
+
num_items=2,
|
| 564 |
+
)
|
| 565 |
+
check(
|
| 566 |
+
batch["test_col"],
|
| 567 |
+
[{"a": np.array(3), "b": 4}, {"a": np.array(5), "b": 6}],
|
| 568 |
+
)
|
| 569 |
+
# In a new column (test_col_2), store some already batched items.
|
| 570 |
+
# This way, you may avoid having to disassemble an already batched item
|
| 571 |
+
# (e.g. a numpy array of shape (10, 2)) into its individual items (e.g.
|
| 572 |
+
# split the array into a list of len=10) and then adding these individually.
|
| 573 |
+
# The performance gains may be quite large when providing already batched
|
| 574 |
+
# items (such as numpy arrays with a batch dim):
|
| 575 |
+
ConnectorV2.add_n_batch_items(
|
| 576 |
+
batch,
|
| 577 |
+
"test_col_2",
|
| 578 |
+
# One (complex) already batched struct.
|
| 579 |
+
{"a": np.array([3, 5]), "b": np.array([4, 6])},
|
| 580 |
+
num_items=2,
|
| 581 |
+
)
|
| 582 |
+
# Add more already batched items (this time with a different batch size)
|
| 583 |
+
ConnectorV2.add_n_batch_items(
|
| 584 |
+
batch,
|
| 585 |
+
"test_col_2",
|
| 586 |
+
{"a": np.array([7, 7, 7]), "b": np.array([8, 8, 8])},
|
| 587 |
+
num_items=3, # <- in this case, this must be the batch size
|
| 588 |
+
)
|
| 589 |
+
check(
|
| 590 |
+
batch["test_col_2"],
|
| 591 |
+
[
|
| 592 |
+
{"a": np.array([3, 5]), "b": np.array([4, 6])},
|
| 593 |
+
{"a": np.array([7, 7, 7]), "b": np.array([8, 8, 8])},
|
| 594 |
+
],
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
# Single-agent case (SingleAgentEpisode provided) -> Store data in a list
|
| 598 |
+
# under the keys: `column` -> `(<eps_id>,)`:
|
| 599 |
+
batch = {}
|
| 600 |
+
episode = SingleAgentEpisode(
|
| 601 |
+
id_="SA-EPS0",
|
| 602 |
+
observations=[0, 1, 2, 3],
|
| 603 |
+
actions=[1, 2, 3],
|
| 604 |
+
rewards=[1.0, 2.0, 3.0],
|
| 605 |
+
)
|
| 606 |
+
ConnectorV2.add_n_batch_items(
|
| 607 |
+
batch=batch,
|
| 608 |
+
column="test_col",
|
| 609 |
+
items_to_add=[5, 6, 7],
|
| 610 |
+
num_items=3,
|
| 611 |
+
single_agent_episode=episode,
|
| 612 |
+
)
|
| 613 |
+
check(batch, {
|
| 614 |
+
"test_col": {("SA-EPS0",): [5, 6, 7]},
|
| 615 |
+
})
|
| 616 |
+
|
| 617 |
+
# Multi-agent case (SingleAgentEpisode provided that has `agent_id` and
|
| 618 |
+
# `module_id` information) -> Store data in a list under the keys:
|
| 619 |
+
# `column` -> `(<episodeID>,<AgentID>,<ModuleID>)`:
|
| 620 |
+
batch = {}
|
| 621 |
+
ma_episode = MultiAgentEpisode(
|
| 622 |
+
id_="MA-EPS1",
|
| 623 |
+
observations=[
|
| 624 |
+
{"ag0": 0, "ag1": 1}, {"ag0": 2, "ag1": 4}
|
| 625 |
+
],
|
| 626 |
+
actions=[{"ag0": 0, "ag1": 1}],
|
| 627 |
+
rewards=[{"ag0": -0.1, "ag1": -0.2}],
|
| 628 |
+
# ag0 maps to mod0, ag1 maps to mod1, etc..
|
| 629 |
+
agent_to_module_mapping_fn=lambda aid, eps: f"mod{aid[2:]}",
|
| 630 |
+
)
|
| 631 |
+
ConnectorV2.add_batch_item(
|
| 632 |
+
batch,
|
| 633 |
+
"test_col",
|
| 634 |
+
item_to_add=5,
|
| 635 |
+
single_agent_episode=ma_episode.agent_episodes["ag0"],
|
| 636 |
+
)
|
| 637 |
+
ConnectorV2.add_batch_item(
|
| 638 |
+
batch,
|
| 639 |
+
"test_col",
|
| 640 |
+
item_to_add=6,
|
| 641 |
+
single_agent_episode=ma_episode.agent_episodes["ag0"],
|
| 642 |
+
)
|
| 643 |
+
ConnectorV2.add_batch_item(
|
| 644 |
+
batch,
|
| 645 |
+
"test_col_2",
|
| 646 |
+
item_to_add=10,
|
| 647 |
+
single_agent_episode=ma_episode.agent_episodes["ag1"],
|
| 648 |
+
)
|
| 649 |
+
check(
|
| 650 |
+
batch,
|
| 651 |
+
{
|
| 652 |
+
"test_col": {("MA-EPS1", "ag0", "mod0"): [5, 6]},
|
| 653 |
+
"test_col_2": {("MA-EPS1", "ag1", "mod1"): [10]},
|
| 654 |
+
},
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
Args:
|
| 658 |
+
batch: The batch to store n `items_to_add` in.
|
| 659 |
+
column: The column name (str) within the `batch` to store `item_to_add`
|
| 660 |
+
under.
|
| 661 |
+
items_to_add: The list of data items to store in the batch OR an already
|
| 662 |
+
batched (possibly nested) struct. In the latter case, the `items_to_add`
|
| 663 |
+
will be appended to possibly existing data under the same `column`
|
| 664 |
+
as-is. A subsequent `BatchIndividualItems` ConnectorV2 piece will
|
| 665 |
+
recognize this and batch the data properly into a single (batched) item.
|
| 666 |
+
This is much faster than first splitting up `items_to_add` and then
|
| 667 |
+
adding each item individually.
|
| 668 |
+
num_items: The number of items in `items_to_add`. This arg is mostly for
|
| 669 |
+
asserting the correct usage of this method by checking, whether the
|
| 670 |
+
given data in `items_to_add` really has the right amount of individual
|
| 671 |
+
items.
|
| 672 |
+
single_agent_episode: An optional SingleAgentEpisode.
|
| 673 |
+
If provided and its `agent_id` and `module_id` properties are None,
|
| 674 |
+
creates a further sub dictionary under `column`, mapping from
|
| 675 |
+
`(<episodeID>,)` to a list of data items (to which `items_to_add` will
|
| 676 |
+
be appended in this call).
|
| 677 |
+
If provided and its `agent_id` and `module_id` properties are NOT None,
|
| 678 |
+
creates a further sub dictionary under `column`, mapping from
|
| 679 |
+
`(<episodeID>,,<AgentID>,<ModuleID>)` to a list of data items (to which
|
| 680 |
+
`items_to_add` will be appended in this call).
|
| 681 |
+
If not provided, will append `items_to_add` to a list directly under
|
| 682 |
+
`column`.
|
| 683 |
+
"""
|
| 684 |
+
# Process n list items by calling `add_batch_item` on each of them individually.
|
| 685 |
+
if isinstance(items_to_add, list):
|
| 686 |
+
if len(items_to_add) != num_items:
|
| 687 |
+
raise ValueError(
|
| 688 |
+
f"Mismatch breteen `num_items` ({num_items}) and the length "
|
| 689 |
+
f"of the provided list ({len(items_to_add)}) in "
|
| 690 |
+
f"{ConnectorV2.__name__}.add_n_batch_items()!"
|
| 691 |
+
)
|
| 692 |
+
for item in items_to_add:
|
| 693 |
+
ConnectorV2.add_batch_item(
|
| 694 |
+
batch=batch,
|
| 695 |
+
column=column,
|
| 696 |
+
item_to_add=item,
|
| 697 |
+
single_agent_episode=single_agent_episode,
|
| 698 |
+
)
|
| 699 |
+
return
|
| 700 |
+
|
| 701 |
+
# Process a batched (possibly complex) struct.
|
| 702 |
+
# We could just unbatch the item (split it into a list) and then add each
|
| 703 |
+
# individual item to our `batch`. However, this comes with a heavy performance
|
| 704 |
+
# penalty. Instead, we tag the thus added array(s) here as "_has_batch_dim=True"
|
| 705 |
+
# and then know that when batching the entire list under the respective
|
| 706 |
+
# (eps_id, agent_id, module_id)-tuple key, we need to concatenate, not stack
|
| 707 |
+
# the items in there.
|
| 708 |
+
def _tag(s):
|
| 709 |
+
return BatchedNdArray(s)
|
| 710 |
+
|
| 711 |
+
ConnectorV2.add_batch_item(
|
| 712 |
+
batch=batch,
|
| 713 |
+
column=column,
|
| 714 |
+
# Convert given input into BatchedNdArray(s) such that the `batch` utility
|
| 715 |
+
# knows that it'll have to concat, not stack.
|
| 716 |
+
item_to_add=tree.map_structure(_tag, items_to_add),
|
| 717 |
+
single_agent_episode=single_agent_episode,
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
@staticmethod
|
| 721 |
+
def foreach_batch_item_change_in_place(
|
| 722 |
+
batch: Dict[str, Any],
|
| 723 |
+
column: Union[str, List[str], Tuple[str]],
|
| 724 |
+
func: Callable[
|
| 725 |
+
[Any, Optional[int], Optional[AgentID], Optional[ModuleID]], Any
|
| 726 |
+
],
|
| 727 |
+
) -> None:
|
| 728 |
+
"""Runs the provided `func` on all items under one or more columns in the batch.
|
| 729 |
+
|
| 730 |
+
Use this method to conveniently loop through all items in a batch
|
| 731 |
+
and transform them in place.
|
| 732 |
+
|
| 733 |
+
`func` takes the following as arguments:
|
| 734 |
+
- The item itself. If column is a list of column names, this argument is a tuple
|
| 735 |
+
of items.
|
| 736 |
+
- The EpisodeID. This value might be None.
|
| 737 |
+
- The AgentID. This value might be None in the single-agent case.
|
| 738 |
+
- The ModuleID. This value might be None in the single-agent case.
|
| 739 |
+
|
| 740 |
+
The return value(s) of `func` are used to directly override the values in the
|
| 741 |
+
given `batch`.
|
| 742 |
+
|
| 743 |
+
Args:
|
| 744 |
+
batch: The batch to process in-place.
|
| 745 |
+
column: A single column name (str) or a list thereof. If a list is provided,
|
| 746 |
+
the first argument to `func` is a tuple of items. If a single
|
| 747 |
+
str is provided, the first argument to `func` is an individual
|
| 748 |
+
item.
|
| 749 |
+
func: The function to call on each item or tuple of item(s).
|
| 750 |
+
|
| 751 |
+
.. testcode::
|
| 752 |
+
|
| 753 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 754 |
+
from ray.rllib.utils.test_utils import check
|
| 755 |
+
|
| 756 |
+
# Simple case: Batch items are in lists directly under their column names.
|
| 757 |
+
batch = {
|
| 758 |
+
"col1": [0, 1, 2, 3],
|
| 759 |
+
"col2": [0, -1, -2, -3],
|
| 760 |
+
}
|
| 761 |
+
# Increase all ints by 1.
|
| 762 |
+
ConnectorV2.foreach_batch_item_change_in_place(
|
| 763 |
+
batch=batch,
|
| 764 |
+
column="col1",
|
| 765 |
+
func=lambda item, *args: item + 1,
|
| 766 |
+
)
|
| 767 |
+
check(batch["col1"], [1, 2, 3, 4])
|
| 768 |
+
|
| 769 |
+
# Further increase all ints by 1 in col1 and flip sign in col2.
|
| 770 |
+
ConnectorV2.foreach_batch_item_change_in_place(
|
| 771 |
+
batch=batch,
|
| 772 |
+
column=["col1", "col2"],
|
| 773 |
+
func=(lambda items, *args: (items[0] + 1, -items[1])),
|
| 774 |
+
)
|
| 775 |
+
check(batch["col1"], [2, 3, 4, 5])
|
| 776 |
+
check(batch["col2"], [0, 1, 2, 3])
|
| 777 |
+
|
| 778 |
+
# Single-agent case: Batch items are in lists under (eps_id,)-keys in a dict
|
| 779 |
+
# under their column names.
|
| 780 |
+
batch = {
|
| 781 |
+
"col1": {
|
| 782 |
+
("eps1",): [0, 1, 2, 3],
|
| 783 |
+
("eps2",): [400, 500, 600],
|
| 784 |
+
},
|
| 785 |
+
}
|
| 786 |
+
# Increase all ints of eps1 by 1 and divide all ints of eps2 by 100.
|
| 787 |
+
ConnectorV2.foreach_batch_item_change_in_place(
|
| 788 |
+
batch=batch,
|
| 789 |
+
column="col1",
|
| 790 |
+
func=lambda item, eps_id, *args: (
|
| 791 |
+
item + 1 if eps_id == "eps1" else item / 100
|
| 792 |
+
),
|
| 793 |
+
)
|
| 794 |
+
check(batch["col1"], {
|
| 795 |
+
("eps1",): [1, 2, 3, 4],
|
| 796 |
+
("eps2",): [4, 5, 6],
|
| 797 |
+
})
|
| 798 |
+
|
| 799 |
+
# Multi-agent case: Batch items are in lists under
|
| 800 |
+
# (eps_id, agent_id, module_id)-keys in a dict
|
| 801 |
+
# under their column names.
|
| 802 |
+
batch = {
|
| 803 |
+
"col1": {
|
| 804 |
+
("eps1", "ag1", "mod1"): [1, 2, 3, 4],
|
| 805 |
+
("eps2", "ag1", "mod2"): [400, 500, 600],
|
| 806 |
+
("eps2", "ag2", "mod3"): [-1, -2, -3, -4, -5],
|
| 807 |
+
},
|
| 808 |
+
}
|
| 809 |
+
# Decrease all ints of "eps1" by 1, divide all ints of "mod2" by 100, and
|
| 810 |
+
# flip sign of all ints of "ag2".
|
| 811 |
+
ConnectorV2.foreach_batch_item_change_in_place(
|
| 812 |
+
batch=batch,
|
| 813 |
+
column="col1",
|
| 814 |
+
func=lambda item, eps_id, ag_id, mod_id: (
|
| 815 |
+
item - 1
|
| 816 |
+
if eps_id == "eps1"
|
| 817 |
+
else item / 100
|
| 818 |
+
if mod_id == "mod2"
|
| 819 |
+
else -item
|
| 820 |
+
),
|
| 821 |
+
)
|
| 822 |
+
check(batch["col1"], {
|
| 823 |
+
("eps1", "ag1", "mod1"): [0, 1, 2, 3],
|
| 824 |
+
("eps2", "ag1", "mod2"): [4, 5, 6],
|
| 825 |
+
("eps2", "ag2", "mod3"): [1, 2, 3, 4, 5],
|
| 826 |
+
})
|
| 827 |
+
"""
|
| 828 |
+
data_to_process = [batch.get(c) for c in force_list(column)]
|
| 829 |
+
single_col = isinstance(column, str)
|
| 830 |
+
if any(d is None for d in data_to_process):
|
| 831 |
+
raise ValueError(
|
| 832 |
+
f"Invalid column name(s) ({column})! One or more not found in "
|
| 833 |
+
f"given batch. Found columns {list(batch.keys())}."
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
# Simple case: Data items are stored in a list directly under the column
|
| 837 |
+
# name(s).
|
| 838 |
+
if isinstance(data_to_process[0], list):
|
| 839 |
+
for list_pos, data_tuple in enumerate(zip(*data_to_process)):
|
| 840 |
+
results = func(
|
| 841 |
+
data_tuple[0] if single_col else data_tuple,
|
| 842 |
+
None, # episode_id
|
| 843 |
+
None, # agent_id
|
| 844 |
+
None, # module_id
|
| 845 |
+
)
|
| 846 |
+
# Tuple'ize results if single_col.
|
| 847 |
+
results = (results,) if single_col else results
|
| 848 |
+
for col_slot, result in enumerate(force_list(results)):
|
| 849 |
+
data_to_process[col_slot][list_pos] = result
|
| 850 |
+
# Single-agent/multi-agent cases.
|
| 851 |
+
else:
|
| 852 |
+
for key, d0_list in data_to_process[0].items():
|
| 853 |
+
# Multi-agent case: There is a dict mapping from a
|
| 854 |
+
# (eps id, AgentID, ModuleID)-tuples to lists of individual data items.
|
| 855 |
+
if len(key) == 3:
|
| 856 |
+
eps_id, agent_id, module_id = key
|
| 857 |
+
# Single-agent case: There is a dict mapping from a (eps_id,)-tuple
|
| 858 |
+
# to lists of individual data items.
|
| 859 |
+
# AgentID and ModuleID are both None.
|
| 860 |
+
else:
|
| 861 |
+
eps_id = key[0]
|
| 862 |
+
agent_id = module_id = None
|
| 863 |
+
other_lists = [d[key] for d in data_to_process[1:]]
|
| 864 |
+
for list_pos, data_tuple in enumerate(zip(d0_list, *other_lists)):
|
| 865 |
+
results = func(
|
| 866 |
+
data_tuple[0] if single_col else data_tuple,
|
| 867 |
+
eps_id,
|
| 868 |
+
agent_id,
|
| 869 |
+
module_id,
|
| 870 |
+
)
|
| 871 |
+
# Tuple'ize results if single_col.
|
| 872 |
+
results = (results,) if single_col else results
|
| 873 |
+
for col_slot, result in enumerate(results):
|
| 874 |
+
data_to_process[col_slot][key][list_pos] = result
|
| 875 |
+
|
| 876 |
+
@staticmethod
|
| 877 |
+
def switch_batch_from_column_to_module_ids(
|
| 878 |
+
batch: Dict[str, Dict[ModuleID, Any]]
|
| 879 |
+
) -> Dict[ModuleID, Dict[str, Any]]:
|
| 880 |
+
"""Switches the first two levels of a `col_name -> ModuleID -> data` type batch.
|
| 881 |
+
|
| 882 |
+
Assuming that the top level consists of column names as keys and the second
|
| 883 |
+
level (under these columns) consists of ModuleID keys, the resulting batch
|
| 884 |
+
will have these two reversed and thus map ModuleIDs to dicts mapping column
|
| 885 |
+
names to data items.
|
| 886 |
+
|
| 887 |
+
.. testcode::
|
| 888 |
+
|
| 889 |
+
from ray.rllib.utils.test_utils import check
|
| 890 |
+
|
| 891 |
+
batch = {
|
| 892 |
+
"obs": {"module_0": [1, 2, 3]},
|
| 893 |
+
"actions": {"module_0": [4, 5, 6], "module_1": [7]},
|
| 894 |
+
}
|
| 895 |
+
switched_batch = ConnectorV2.switch_batch_from_column_to_module_ids(batch)
|
| 896 |
+
check(
|
| 897 |
+
switched_batch,
|
| 898 |
+
{
|
| 899 |
+
"module_0": {"obs": [1, 2, 3], "actions": [4, 5, 6]},
|
| 900 |
+
"module_1": {"actions": [7]},
|
| 901 |
+
},
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
Args:
|
| 905 |
+
batch: The batch to switch from being column name based (then ModuleIDs)
|
| 906 |
+
to being ModuleID based (then column names).
|
| 907 |
+
|
| 908 |
+
Returns:
|
| 909 |
+
A new batch dict mapping ModuleIDs to dicts mapping column names (e.g.
|
| 910 |
+
"obs") to data.
|
| 911 |
+
"""
|
| 912 |
+
module_data = defaultdict(dict)
|
| 913 |
+
for column, column_data in batch.items():
|
| 914 |
+
for module_id, data in column_data.items():
|
| 915 |
+
module_data[module_id][column] = data
|
| 916 |
+
return dict(module_data)
|
| 917 |
+
|
| 918 |
+
@override(Checkpointable)
|
| 919 |
+
def get_state(
|
| 920 |
+
self,
|
| 921 |
+
components: Optional[Union[str, Collection[str]]] = None,
|
| 922 |
+
*,
|
| 923 |
+
not_components: Optional[Union[str, Collection[str]]] = None,
|
| 924 |
+
**kwargs,
|
| 925 |
+
) -> StateDict:
|
| 926 |
+
return {}
|
| 927 |
+
|
| 928 |
+
@override(Checkpointable)
|
| 929 |
+
def set_state(self, state: StateDict) -> None:
|
| 930 |
+
pass
|
| 931 |
+
|
| 932 |
+
@override(Checkpointable)
|
| 933 |
+
def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]:
|
| 934 |
+
return (
|
| 935 |
+
(), # *args
|
| 936 |
+
self._ctor_kwargs, # **kwargs
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
def reset_state(self) -> None:
|
| 940 |
+
"""Resets the state of this ConnectorV2 to some initial value.
|
| 941 |
+
|
| 942 |
+
Note that this may NOT be the exact state that this ConnectorV2 was originally
|
| 943 |
+
constructed with.
|
| 944 |
+
"""
|
| 945 |
+
return
|
| 946 |
+
|
| 947 |
+
def merge_states(self, states: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 948 |
+
"""Computes a resulting state given self's state and a list of other states.
|
| 949 |
+
|
| 950 |
+
Algorithms should use this method for merging states between connectors
|
| 951 |
+
running on parallel EnvRunner workers. For example, to synchronize the connector
|
| 952 |
+
states of n remote workers and a local worker, one could:
|
| 953 |
+
- Gather all remote worker connector states in a list.
|
| 954 |
+
- Call `self.merge_states()` on the local worker passing it the states list.
|
| 955 |
+
- Broadcast the resulting local worker's connector state back to all remote
|
| 956 |
+
workers. After this, all workers (including the local one) hold a
|
| 957 |
+
merged/synchronized new connecto state.
|
| 958 |
+
|
| 959 |
+
Args:
|
| 960 |
+
states: The list of n other ConnectorV2 states to merge with self's state
|
| 961 |
+
into a single resulting state.
|
| 962 |
+
|
| 963 |
+
Returns:
|
| 964 |
+
The resulting state dict.
|
| 965 |
+
"""
|
| 966 |
+
return {}
|
| 967 |
+
|
| 968 |
+
@property
|
| 969 |
+
def observation_space(self):
|
| 970 |
+
"""Getter for our (output) observation space.
|
| 971 |
+
|
| 972 |
+
Logic: Use user provided space (if set via `observation_space` setter)
|
| 973 |
+
otherwise, use the same as the input space, assuming this connector piece
|
| 974 |
+
does not alter the space.
|
| 975 |
+
"""
|
| 976 |
+
return self._observation_space
|
| 977 |
+
|
| 978 |
+
@property
|
| 979 |
+
def action_space(self):
|
| 980 |
+
"""Getter for our (output) action space.
|
| 981 |
+
|
| 982 |
+
Logic: Use user provided space (if set via `action_space` setter)
|
| 983 |
+
otherwise, use the same as the input space, assuming this connector piece
|
| 984 |
+
does not alter the space.
|
| 985 |
+
"""
|
| 986 |
+
return self._action_space
|
| 987 |
+
|
| 988 |
+
@property
|
| 989 |
+
def input_observation_space(self):
|
| 990 |
+
return self._input_observation_space
|
| 991 |
+
|
| 992 |
+
@input_observation_space.setter
|
| 993 |
+
def input_observation_space(self, value):
|
| 994 |
+
self._input_observation_space = value
|
| 995 |
+
if value is not None:
|
| 996 |
+
self._observation_space = self.recompute_output_observation_space(
|
| 997 |
+
value, self.input_action_space
|
| 998 |
+
)
|
| 999 |
+
|
| 1000 |
+
@property
|
| 1001 |
+
def input_action_space(self):
|
| 1002 |
+
return self._input_action_space
|
| 1003 |
+
|
| 1004 |
+
@input_action_space.setter
|
| 1005 |
+
def input_action_space(self, value):
|
| 1006 |
+
self._input_action_space = value
|
| 1007 |
+
if value is not None:
|
| 1008 |
+
self._action_space = self.recompute_output_action_space(
|
| 1009 |
+
self.input_observation_space, value
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
def __str__(self, indentation: int = 0):
|
| 1013 |
+
return " " * indentation + self.__class__.__name__
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import (
|
| 2 |
+
AddObservationsFromEpisodesToBatch,
|
| 3 |
+
)
|
| 4 |
+
from ray.rllib.connectors.common.add_states_from_episodes_to_batch import (
|
| 5 |
+
AddStatesFromEpisodesToBatch,
|
| 6 |
+
)
|
| 7 |
+
from ray.rllib.connectors.common.agent_to_module_mapping import AgentToModuleMapping
|
| 8 |
+
from ray.rllib.connectors.common.batch_individual_items import BatchIndividualItems
|
| 9 |
+
from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor
|
| 10 |
+
from ray.rllib.connectors.env_to_module.env_to_module_pipeline import (
|
| 11 |
+
EnvToModulePipeline,
|
| 12 |
+
)
|
| 13 |
+
from ray.rllib.connectors.env_to_module.flatten_observations import (
|
| 14 |
+
FlattenObservations,
|
| 15 |
+
)
|
| 16 |
+
from ray.rllib.connectors.env_to_module.mean_std_filter import MeanStdFilter
|
| 17 |
+
from ray.rllib.connectors.env_to_module.prev_actions_prev_rewards import (
|
| 18 |
+
PrevActionsPrevRewards,
|
| 19 |
+
)
|
| 20 |
+
from ray.rllib.connectors.env_to_module.write_observations_to_episodes import (
|
| 21 |
+
WriteObservationsToEpisodes,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
"AddObservationsFromEpisodesToBatch",
|
| 27 |
+
"AddStatesFromEpisodesToBatch",
|
| 28 |
+
"AgentToModuleMapping",
|
| 29 |
+
"BatchIndividualItems",
|
| 30 |
+
"EnvToModulePipeline",
|
| 31 |
+
"FlattenObservations",
|
| 32 |
+
"MeanStdFilter",
|
| 33 |
+
"NumpyToTensor",
|
| 34 |
+
"PrevActionsPrevRewards",
|
| 35 |
+
"WriteObservationsToEpisodes",
|
| 36 |
+
]
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/env_to_module_pipeline.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
|
| 3 |
+
from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2
|
| 4 |
+
from ray.rllib.core.rl_module.rl_module import RLModule
|
| 5 |
+
from ray.rllib.utils.annotations import override
|
| 6 |
+
from ray.rllib.utils.typing import EpisodeType
|
| 7 |
+
from ray.util.annotations import PublicAPI
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@PublicAPI(stability="alpha")
|
| 11 |
+
class EnvToModulePipeline(ConnectorPipelineV2):
|
| 12 |
+
@override(ConnectorPipelineV2)
|
| 13 |
+
def __call__(
|
| 14 |
+
self,
|
| 15 |
+
*,
|
| 16 |
+
rl_module: RLModule,
|
| 17 |
+
batch: Optional[Dict[str, Any]] = None,
|
| 18 |
+
episodes: List[EpisodeType],
|
| 19 |
+
explore: bool,
|
| 20 |
+
shared_data: Optional[dict] = None,
|
| 21 |
+
**kwargs,
|
| 22 |
+
):
|
| 23 |
+
# Make sure user does not necessarily send initial input into this pipeline.
|
| 24 |
+
# Might just be empty and to be populated from `episodes`.
|
| 25 |
+
return super().__call__(
|
| 26 |
+
rl_module=rl_module,
|
| 27 |
+
batch=batch if batch is not None else {},
|
| 28 |
+
episodes=episodes,
|
| 29 |
+
explore=explore,
|
| 30 |
+
shared_data=shared_data if shared_data is not None else {},
|
| 31 |
+
**kwargs,
|
| 32 |
+
)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
from typing import Any, Dict, List, Optional
|
| 3 |
+
|
| 4 |
+
import gymnasium as gym
|
| 5 |
+
|
| 6 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 7 |
+
from ray.rllib.core.rl_module.rl_module import RLModule
|
| 8 |
+
from ray.rllib.utils.annotations import override
|
| 9 |
+
from ray.rllib.utils.typing import EpisodeType
|
| 10 |
+
from ray.util.annotations import PublicAPI
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@PublicAPI(stability="alpha")
|
| 14 |
+
class ObservationPreprocessor(ConnectorV2, abc.ABC):
|
| 15 |
+
"""Env-to-module connector performing one preprocessor step on the last observation.
|
| 16 |
+
|
| 17 |
+
This is a convenience class that simplifies the writing of few-step preprocessor
|
| 18 |
+
connectors.
|
| 19 |
+
|
| 20 |
+
Users must implement the `preprocess()` method, which simplifies the usual procedure
|
| 21 |
+
of extracting some data from a list of episodes and adding it to the batch to a mere
|
| 22 |
+
"old-observation --transform--> return new-observation" step.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
@override(ConnectorV2)
|
| 26 |
+
def recompute_output_observation_space(
|
| 27 |
+
self,
|
| 28 |
+
input_observation_space: gym.Space,
|
| 29 |
+
input_action_space: gym.Space,
|
| 30 |
+
) -> gym.Space:
|
| 31 |
+
# Users should override this method only in case the `ObservationPreprocessor`
|
| 32 |
+
# changes the observation space of the pipeline. In this case, return the new
|
| 33 |
+
# observation space based on the incoming one (`input_observation_space`).
|
| 34 |
+
return super().recompute_output_observation_space(
|
| 35 |
+
input_observation_space, input_action_space
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
@abc.abstractmethod
|
| 39 |
+
def preprocess(self, observation):
|
| 40 |
+
"""Override to implement the preprocessing logic.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
observation: A single (non-batched) observation item for a single agent to
|
| 44 |
+
be processed by this connector.
|
| 45 |
+
|
| 46 |
+
Returns:
|
| 47 |
+
The new observation after `observation` has been preprocessed.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
@override(ConnectorV2)
|
| 51 |
+
def __call__(
|
| 52 |
+
self,
|
| 53 |
+
*,
|
| 54 |
+
rl_module: RLModule,
|
| 55 |
+
batch: Dict[str, Any],
|
| 56 |
+
episodes: List[EpisodeType],
|
| 57 |
+
explore: Optional[bool] = None,
|
| 58 |
+
persistent_data: Optional[dict] = None,
|
| 59 |
+
**kwargs,
|
| 60 |
+
) -> Any:
|
| 61 |
+
# We process and then replace observations inside the episodes directly.
|
| 62 |
+
# Thus, all following connectors will only see and operate on the already
|
| 63 |
+
# processed observation (w/o having access anymore to the original
|
| 64 |
+
# observations).
|
| 65 |
+
for sa_episode in self.single_agent_episode_iterator(episodes):
|
| 66 |
+
observation = sa_episode.get_observations(-1)
|
| 67 |
+
|
| 68 |
+
# Process the observation and write the new observation back into the
|
| 69 |
+
# episode.
|
| 70 |
+
new_observation = self.preprocess(observation=observation)
|
| 71 |
+
sa_episode.set_observations(at_indices=-1, new_data=new_observation)
|
| 72 |
+
# We set the Episode's observation space to ours so that we can safely
|
| 73 |
+
# set the last obs to the new value (without causing a space mismatch
|
| 74 |
+
# error).
|
| 75 |
+
sa_episode.observation_space = self.observation_space
|
| 76 |
+
|
| 77 |
+
# Leave `batch` as is. RLlib's default connector will automatically
|
| 78 |
+
# populate the OBS column therein from the episodes' now transformed
|
| 79 |
+
# observations.
|
| 80 |
+
return batch
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
|
| 3 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 4 |
+
from ray.rllib.core.columns import Columns
|
| 5 |
+
from ray.rllib.core.rl_module.rl_module import RLModule
|
| 6 |
+
from ray.rllib.utils.annotations import override
|
| 7 |
+
from ray.rllib.utils.typing import EpisodeType
|
| 8 |
+
from ray.util.annotations import PublicAPI
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@PublicAPI(stability="alpha")
|
| 12 |
+
class WriteObservationsToEpisodes(ConnectorV2):
|
| 13 |
+
"""Writes the observations from the batch into the running episodes.
|
| 14 |
+
|
| 15 |
+
Note: This is one of the default env-to-module ConnectorV2 pieces that are added
|
| 16 |
+
automatically by RLlib into every env-to-module connector pipelines, unless
|
| 17 |
+
`config.add_default_connectors_to_env_to_module_pipeline` is set to False.
|
| 18 |
+
|
| 19 |
+
The default env-to-module connector pipeline is:
|
| 20 |
+
[
|
| 21 |
+
[0 or more user defined ConnectorV2 pieces],
|
| 22 |
+
AddObservationsFromEpisodesToBatch,
|
| 23 |
+
AddStatesFromEpisodesToBatch,
|
| 24 |
+
AgentToModuleMapping, # only in multi-agent setups!
|
| 25 |
+
BatchIndividualItems,
|
| 26 |
+
NumpyToTensor,
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
This ConnectorV2:
|
| 30 |
+
- Operates on a batch that already has observations in it and a list of Episode
|
| 31 |
+
objects.
|
| 32 |
+
- Writes the observation(s) from the batch to all the given episodes. Thereby
|
| 33 |
+
the number of observations in the batch must match the length of the list of
|
| 34 |
+
episodes given.
|
| 35 |
+
- Does NOT alter any observations (or other data) in the batch.
|
| 36 |
+
- Can only be used in an EnvToModule pipeline (writing into Episode objects in a
|
| 37 |
+
Learner pipeline does not make a lot of sense as - after the learner update - the
|
| 38 |
+
list of episodes is discarded).
|
| 39 |
+
|
| 40 |
+
.. testcode::
|
| 41 |
+
|
| 42 |
+
import gymnasium as gym
|
| 43 |
+
import numpy as np
|
| 44 |
+
|
| 45 |
+
from ray.rllib.connectors.env_to_module import WriteObservationsToEpisodes
|
| 46 |
+
from ray.rllib.env.single_agent_episode import SingleAgentEpisode
|
| 47 |
+
from ray.rllib.utils.test_utils import check
|
| 48 |
+
|
| 49 |
+
# Assume we have two episodes (vectorized), then our forward batch will carry
|
| 50 |
+
# two observation records (batch size = 2).
|
| 51 |
+
# The connector in this example will write these two (possibly transformed)
|
| 52 |
+
# observations back into the two respective SingleAgentEpisode objects.
|
| 53 |
+
batch = {
|
| 54 |
+
"obs": [np.array([0.0, 1.0], np.float32), np.array([2.0, 3.0], np.float32)],
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
# Our two episodes have one observation each (i.e. the reset one). This is the
|
| 58 |
+
# one that will be overwritten by the connector in this example.
|
| 59 |
+
obs_space = gym.spaces.Box(-10.0, 10.0, (2,), np.float32)
|
| 60 |
+
act_space = gym.spaces.Discrete(2)
|
| 61 |
+
episodes = [
|
| 62 |
+
SingleAgentEpisode(
|
| 63 |
+
observation_space=obs_space,
|
| 64 |
+
observations=[np.array([-10, -20], np.float32)],
|
| 65 |
+
len_lookback_buffer=0,
|
| 66 |
+
) for _ in range(2)
|
| 67 |
+
]
|
| 68 |
+
# Make sure everything is setup correctly.
|
| 69 |
+
check(episodes[0].get_observations(0), [-10.0, -20.0])
|
| 70 |
+
check(episodes[1].get_observations(-1), [-10.0, -20.0])
|
| 71 |
+
|
| 72 |
+
# Create our connector piece.
|
| 73 |
+
connector = WriteObservationsToEpisodes(obs_space, act_space)
|
| 74 |
+
|
| 75 |
+
# Call the connector (and thereby write the transformed observations back
|
| 76 |
+
# into the episodes).
|
| 77 |
+
output_batch = connector(
|
| 78 |
+
rl_module=None, # This particular connector works without an RLModule.
|
| 79 |
+
batch=batch,
|
| 80 |
+
episodes=episodes,
|
| 81 |
+
explore=True,
|
| 82 |
+
shared_data={},
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# The connector does NOT change the data batch being passed through.
|
| 86 |
+
check(output_batch, batch)
|
| 87 |
+
|
| 88 |
+
# However, the connector has overwritten the last observations in the episodes.
|
| 89 |
+
check(episodes[0].get_observations(-1), [0.0, 1.0])
|
| 90 |
+
check(episodes[1].get_observations(0), [2.0, 3.0])
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
@override(ConnectorV2)
|
| 94 |
+
def __call__(
|
| 95 |
+
self,
|
| 96 |
+
*,
|
| 97 |
+
rl_module: RLModule,
|
| 98 |
+
batch: Optional[Dict[str, Any]],
|
| 99 |
+
episodes: List[EpisodeType],
|
| 100 |
+
explore: Optional[bool] = None,
|
| 101 |
+
shared_data: Optional[dict] = None,
|
| 102 |
+
**kwargs,
|
| 103 |
+
) -> Any:
|
| 104 |
+
observations = batch.get(Columns.OBS)
|
| 105 |
+
|
| 106 |
+
if observations is None:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
f"`batch` must already have a column named {Columns.OBS} in it "
|
| 109 |
+
f"for this connector to work!"
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Note that the following loop works with multi-agent as well as with
|
| 113 |
+
# single-agent episode, as long as the following conditions are met (these
|
| 114 |
+
# will be validated by `self.single_agent_episode_iterator()`):
|
| 115 |
+
# - Per single agent episode, one observation item is expected to exist in
|
| 116 |
+
# `data`, either in a list directly under the "obs" key OR for multi-agent:
|
| 117 |
+
# in a list sitting under a key `(agent_id, module_id)` of a dict sitting
|
| 118 |
+
# under the "obs" key.
|
| 119 |
+
for sa_episode, obs in self.single_agent_episode_iterator(
|
| 120 |
+
episodes=episodes, zip_with_batch_column=observations
|
| 121 |
+
):
|
| 122 |
+
# Make sure episodes are NOT finalized yet (we are expecting to run in an
|
| 123 |
+
# env-to-module pipeline).
|
| 124 |
+
assert not sa_episode.is_finalized
|
| 125 |
+
# Write new information into the episode.
|
| 126 |
+
sa_episode.set_observations(at_indices=-1, new_data=obs)
|
| 127 |
+
# Change the observation space of the sa_episode.
|
| 128 |
+
sa_episode.observation_space = self.observation_space
|
| 129 |
+
|
| 130 |
+
# Return the unchanged `batch`.
|
| 131 |
+
return batch
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import (
|
| 2 |
+
AddObservationsFromEpisodesToBatch,
|
| 3 |
+
)
|
| 4 |
+
from ray.rllib.connectors.common.add_states_from_episodes_to_batch import (
|
| 5 |
+
AddStatesFromEpisodesToBatch,
|
| 6 |
+
)
|
| 7 |
+
from ray.rllib.connectors.common.agent_to_module_mapping import AgentToModuleMapping
|
| 8 |
+
from ray.rllib.connectors.common.batch_individual_items import BatchIndividualItems
|
| 9 |
+
from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor
|
| 10 |
+
from ray.rllib.connectors.learner.add_columns_from_episodes_to_train_batch import (
|
| 11 |
+
AddColumnsFromEpisodesToTrainBatch,
|
| 12 |
+
)
|
| 13 |
+
from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa
|
| 14 |
+
AddNextObservationsFromEpisodesToTrainBatch,
|
| 15 |
+
)
|
| 16 |
+
from ray.rllib.connectors.learner.add_one_ts_to_episodes_and_truncate import (
|
| 17 |
+
AddOneTsToEpisodesAndTruncate,
|
| 18 |
+
)
|
| 19 |
+
from ray.rllib.connectors.learner.general_advantage_estimation import (
|
| 20 |
+
GeneralAdvantageEstimation,
|
| 21 |
+
)
|
| 22 |
+
from ray.rllib.connectors.learner.learner_connector_pipeline import (
|
| 23 |
+
LearnerConnectorPipeline,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
__all__ = [
|
| 27 |
+
"AddColumnsFromEpisodesToTrainBatch",
|
| 28 |
+
"AddNextObservationsFromEpisodesToTrainBatch",
|
| 29 |
+
"AddObservationsFromEpisodesToBatch",
|
| 30 |
+
"AddOneTsToEpisodesAndTruncate",
|
| 31 |
+
"AddStatesFromEpisodesToBatch",
|
| 32 |
+
"AgentToModuleMapping",
|
| 33 |
+
"BatchIndividualItems",
|
| 34 |
+
"GeneralAdvantageEstimation",
|
| 35 |
+
"LearnerConnectorPipeline",
|
| 36 |
+
"NumpyToTensor",
|
| 37 |
+
]
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.37 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_columns_from_episodes_to_train_batch.cpython-310.pyc
ADDED
|
Binary file (4.6 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_next_observations_from_episodes_to_train_batch.cpython-310.pyc
ADDED
|
Binary file (4.11 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-310.pyc
ADDED
|
Binary file (4.79 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-310.pyc
ADDED
|
Binary file (367 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-310.pyc
ADDED
|
Binary file (5.92 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-310.pyc
ADDED
|
Binary file (543 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
|
| 3 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 4 |
+
from ray.rllib.core.columns import Columns
|
| 5 |
+
from ray.rllib.core.rl_module.rl_module import RLModule
|
| 6 |
+
from ray.rllib.utils.annotations import override
|
| 7 |
+
from ray.rllib.utils.typing import EpisodeType
|
| 8 |
+
from ray.util.annotations import PublicAPI
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@PublicAPI(stability="alpha")
|
| 12 |
+
class AddColumnsFromEpisodesToTrainBatch(ConnectorV2):
|
| 13 |
+
"""Adds infos/actions/rewards/terminateds/... to train batch.
|
| 14 |
+
|
| 15 |
+
Note: This is one of the default Learner ConnectorV2 pieces that are added
|
| 16 |
+
automatically by RLlib into every Learner connector pipeline, unless
|
| 17 |
+
`config.add_default_connectors_to_learner_pipeline` is set to False.
|
| 18 |
+
|
| 19 |
+
The default Learner connector pipeline is:
|
| 20 |
+
[
|
| 21 |
+
[0 or more user defined ConnectorV2 pieces],
|
| 22 |
+
AddObservationsFromEpisodesToBatch,
|
| 23 |
+
AddColumnsFromEpisodesToTrainBatch,
|
| 24 |
+
AddStatesFromEpisodesToBatch,
|
| 25 |
+
AgentToModuleMapping, # only in multi-agent setups!
|
| 26 |
+
BatchIndividualItems,
|
| 27 |
+
NumpyToTensor,
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
Does NOT add observations to train batch (these should have already been added
|
| 31 |
+
by another ConnectorV2 piece: `AddObservationsToTrainBatch` in the same pipeline).
|
| 32 |
+
|
| 33 |
+
If provided with `episodes` data, this connector piece makes sure that the final
|
| 34 |
+
train batch going into the RLModule for updating (`forward_train()` call) contains
|
| 35 |
+
at the minimum:
|
| 36 |
+
- Observations: From all episodes under the Columns.OBS key.
|
| 37 |
+
- Actions, rewards, terminal/truncation flags: From all episodes under the
|
| 38 |
+
respective keys.
|
| 39 |
+
- All data inside the episodes' `extra_model_outs` property, e.g. action logp and
|
| 40 |
+
action probs under the respective keys.
|
| 41 |
+
- Internal states: These will NOT be added to the batch by this connector piece
|
| 42 |
+
as this functionality is handled by a different default connector piece:
|
| 43 |
+
`AddStatesFromEpisodesToBatch`.
|
| 44 |
+
|
| 45 |
+
If the user wants to customize their own data under the given keys (e.g. obs,
|
| 46 |
+
actions, ...), they can extract from the episodes or recompute from `data`
|
| 47 |
+
their own data and store it in `data` under those keys. In this case, the default
|
| 48 |
+
connector will not change the data under these keys and simply act as a
|
| 49 |
+
pass-through.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
@override(ConnectorV2)
|
| 53 |
+
def __call__(
|
| 54 |
+
self,
|
| 55 |
+
*,
|
| 56 |
+
rl_module: RLModule,
|
| 57 |
+
batch: Optional[Dict[str, Any]],
|
| 58 |
+
episodes: List[EpisodeType],
|
| 59 |
+
explore: Optional[bool] = None,
|
| 60 |
+
shared_data: Optional[dict] = None,
|
| 61 |
+
**kwargs,
|
| 62 |
+
) -> Any:
|
| 63 |
+
# Infos.
|
| 64 |
+
if Columns.INFOS not in batch:
|
| 65 |
+
for sa_episode in self.single_agent_episode_iterator(
|
| 66 |
+
episodes,
|
| 67 |
+
agents_that_stepped_only=False,
|
| 68 |
+
):
|
| 69 |
+
self.add_n_batch_items(
|
| 70 |
+
batch,
|
| 71 |
+
Columns.INFOS,
|
| 72 |
+
items_to_add=sa_episode.get_infos(slice(0, len(sa_episode))),
|
| 73 |
+
num_items=len(sa_episode),
|
| 74 |
+
single_agent_episode=sa_episode,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Actions.
|
| 78 |
+
if Columns.ACTIONS not in batch:
|
| 79 |
+
for sa_episode in self.single_agent_episode_iterator(
|
| 80 |
+
episodes,
|
| 81 |
+
agents_that_stepped_only=False,
|
| 82 |
+
):
|
| 83 |
+
self.add_n_batch_items(
|
| 84 |
+
batch,
|
| 85 |
+
Columns.ACTIONS,
|
| 86 |
+
items_to_add=[
|
| 87 |
+
sa_episode.get_actions(indices=ts)
|
| 88 |
+
for ts in range(len(sa_episode))
|
| 89 |
+
],
|
| 90 |
+
num_items=len(sa_episode),
|
| 91 |
+
single_agent_episode=sa_episode,
|
| 92 |
+
)
|
| 93 |
+
# Rewards.
|
| 94 |
+
if Columns.REWARDS not in batch:
|
| 95 |
+
for sa_episode in self.single_agent_episode_iterator(
|
| 96 |
+
episodes,
|
| 97 |
+
agents_that_stepped_only=False,
|
| 98 |
+
):
|
| 99 |
+
self.add_n_batch_items(
|
| 100 |
+
batch,
|
| 101 |
+
Columns.REWARDS,
|
| 102 |
+
items_to_add=[
|
| 103 |
+
sa_episode.get_rewards(indices=ts)
|
| 104 |
+
for ts in range(len(sa_episode))
|
| 105 |
+
],
|
| 106 |
+
num_items=len(sa_episode),
|
| 107 |
+
single_agent_episode=sa_episode,
|
| 108 |
+
)
|
| 109 |
+
# Terminateds.
|
| 110 |
+
if Columns.TERMINATEDS not in batch:
|
| 111 |
+
for sa_episode in self.single_agent_episode_iterator(
|
| 112 |
+
episodes,
|
| 113 |
+
agents_that_stepped_only=False,
|
| 114 |
+
):
|
| 115 |
+
self.add_n_batch_items(
|
| 116 |
+
batch,
|
| 117 |
+
Columns.TERMINATEDS,
|
| 118 |
+
items_to_add=(
|
| 119 |
+
[False] * (len(sa_episode) - 1) + [sa_episode.is_terminated]
|
| 120 |
+
if len(sa_episode) > 0
|
| 121 |
+
else []
|
| 122 |
+
),
|
| 123 |
+
num_items=len(sa_episode),
|
| 124 |
+
single_agent_episode=sa_episode,
|
| 125 |
+
)
|
| 126 |
+
# Truncateds.
|
| 127 |
+
if Columns.TRUNCATEDS not in batch:
|
| 128 |
+
for sa_episode in self.single_agent_episode_iterator(
|
| 129 |
+
episodes,
|
| 130 |
+
agents_that_stepped_only=False,
|
| 131 |
+
):
|
| 132 |
+
self.add_n_batch_items(
|
| 133 |
+
batch,
|
| 134 |
+
Columns.TRUNCATEDS,
|
| 135 |
+
items_to_add=(
|
| 136 |
+
[False] * (len(sa_episode) - 1) + [sa_episode.is_truncated]
|
| 137 |
+
if len(sa_episode) > 0
|
| 138 |
+
else []
|
| 139 |
+
),
|
| 140 |
+
num_items=len(sa_episode),
|
| 141 |
+
single_agent_episode=sa_episode,
|
| 142 |
+
)
|
| 143 |
+
# Extra model outputs (except for STATE_OUT, which will be handled by another
|
| 144 |
+
# default connector piece). Also, like with all the fields above, skip
|
| 145 |
+
# those that the user already seemed to have populated via custom connector
|
| 146 |
+
# pieces.
|
| 147 |
+
skip_columns = set(batch.keys()) | {Columns.STATE_IN, Columns.STATE_OUT}
|
| 148 |
+
for sa_episode in self.single_agent_episode_iterator(
|
| 149 |
+
episodes,
|
| 150 |
+
agents_that_stepped_only=False,
|
| 151 |
+
):
|
| 152 |
+
for column in sa_episode.extra_model_outputs.keys():
|
| 153 |
+
if column not in skip_columns:
|
| 154 |
+
self.add_n_batch_items(
|
| 155 |
+
batch,
|
| 156 |
+
column,
|
| 157 |
+
items_to_add=[
|
| 158 |
+
sa_episode.get_extra_model_outputs(key=column, indices=ts)
|
| 159 |
+
for ts in range(len(sa_episode))
|
| 160 |
+
],
|
| 161 |
+
num_items=len(sa_episode),
|
| 162 |
+
single_agent_episode=sa_episode,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
return batch
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
|
| 3 |
+
from ray.rllib.core.columns import Columns
|
| 4 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 5 |
+
from ray.rllib.core.rl_module.rl_module import RLModule
|
| 6 |
+
from ray.rllib.utils.annotations import override
|
| 7 |
+
from ray.rllib.utils.typing import EpisodeType
|
| 8 |
+
from ray.util.annotations import PublicAPI
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@PublicAPI(stability="alpha")
|
| 12 |
+
class AddNextObservationsFromEpisodesToTrainBatch(ConnectorV2):
|
| 13 |
+
"""Adds the NEXT_OBS column with the correct episode observations to train batch.
|
| 14 |
+
|
| 15 |
+
- Operates on a list of Episode objects.
|
| 16 |
+
- Gets all observation(s) from all the given episodes (except the very first ones)
|
| 17 |
+
and adds them to the batch under construction in the NEXT_OBS column (as a list of
|
| 18 |
+
individual observations).
|
| 19 |
+
- Does NOT alter any observations (or other data) in the given episodes.
|
| 20 |
+
- Can be used in Learner connector pipelines.
|
| 21 |
+
|
| 22 |
+
.. testcode::
|
| 23 |
+
|
| 24 |
+
import gymnasium as gym
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from ray.rllib.connectors.learner import (
|
| 28 |
+
AddNextObservationsFromEpisodesToTrainBatch
|
| 29 |
+
)
|
| 30 |
+
from ray.rllib.core.columns import Columns
|
| 31 |
+
from ray.rllib.env.single_agent_episode import SingleAgentEpisode
|
| 32 |
+
from ray.rllib.utils.test_utils import check
|
| 33 |
+
|
| 34 |
+
# Create two dummy SingleAgentEpisodes, each containing 3 observations,
|
| 35 |
+
# 2 actions and 2 rewards (both episodes are length=2).
|
| 36 |
+
obs_space = gym.spaces.Box(-1.0, 1.0, (2,), np.float32)
|
| 37 |
+
act_space = gym.spaces.Discrete(2)
|
| 38 |
+
|
| 39 |
+
episodes = [SingleAgentEpisode(
|
| 40 |
+
observations=[obs_space.sample(), obs_space.sample(), obs_space.sample()],
|
| 41 |
+
actions=[act_space.sample(), act_space.sample()],
|
| 42 |
+
rewards=[1.0, 2.0],
|
| 43 |
+
len_lookback_buffer=0,
|
| 44 |
+
) for _ in range(2)]
|
| 45 |
+
eps_1_next_obses = episodes[0].get_observations([1, 2])
|
| 46 |
+
eps_2_next_obses = episodes[1].get_observations([1, 2])
|
| 47 |
+
print(f"1st Episode's next obses are {eps_1_next_obses}")
|
| 48 |
+
print(f"2nd Episode's next obses are {eps_2_next_obses}")
|
| 49 |
+
|
| 50 |
+
# Create an instance of this class.
|
| 51 |
+
connector = AddNextObservationsFromEpisodesToTrainBatch()
|
| 52 |
+
|
| 53 |
+
# Call the connector with the two created episodes.
|
| 54 |
+
# Note that this particular connector works without an RLModule, so we
|
| 55 |
+
# simplify here for the sake of this example.
|
| 56 |
+
output_data = connector(
|
| 57 |
+
rl_module=None,
|
| 58 |
+
batch={},
|
| 59 |
+
episodes=episodes,
|
| 60 |
+
explore=True,
|
| 61 |
+
shared_data={},
|
| 62 |
+
)
|
| 63 |
+
# The output data should now contain the last observations of both episodes,
|
| 64 |
+
# in a "per-episode organized" fashion.
|
| 65 |
+
check(
|
| 66 |
+
output_data,
|
| 67 |
+
{
|
| 68 |
+
Columns.NEXT_OBS: {
|
| 69 |
+
(episodes[0].id_,): eps_1_next_obses,
|
| 70 |
+
(episodes[1].id_,): eps_2_next_obses,
|
| 71 |
+
},
|
| 72 |
+
},
|
| 73 |
+
)
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
@override(ConnectorV2)
|
| 77 |
+
def __call__(
|
| 78 |
+
self,
|
| 79 |
+
*,
|
| 80 |
+
rl_module: RLModule,
|
| 81 |
+
batch: Dict[str, Any],
|
| 82 |
+
episodes: List[EpisodeType],
|
| 83 |
+
explore: Optional[bool] = None,
|
| 84 |
+
shared_data: Optional[dict] = None,
|
| 85 |
+
**kwargs,
|
| 86 |
+
) -> Any:
|
| 87 |
+
# If "obs" already in `batch`, early out.
|
| 88 |
+
if Columns.NEXT_OBS in batch:
|
| 89 |
+
return batch
|
| 90 |
+
|
| 91 |
+
for sa_episode in self.single_agent_episode_iterator(
|
| 92 |
+
# This is a Learner-only connector -> Get all episodes (for train batch).
|
| 93 |
+
episodes,
|
| 94 |
+
agents_that_stepped_only=False,
|
| 95 |
+
):
|
| 96 |
+
self.add_n_batch_items(
|
| 97 |
+
batch,
|
| 98 |
+
Columns.NEXT_OBS,
|
| 99 |
+
items_to_add=sa_episode.get_observations(slice(1, len(sa_episode) + 1)),
|
| 100 |
+
num_items=len(sa_episode),
|
| 101 |
+
single_agent_episode=sa_episode,
|
| 102 |
+
)
|
| 103 |
+
return batch
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
|
| 3 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 4 |
+
from ray.rllib.core.columns import Columns
|
| 5 |
+
from ray.rllib.core.rl_module.rl_module import RLModule
|
| 6 |
+
from ray.rllib.env.multi_agent_episode import MultiAgentEpisode
|
| 7 |
+
from ray.rllib.utils.annotations import override
|
| 8 |
+
from ray.rllib.utils.postprocessing.episodes import add_one_ts_to_episodes_and_truncate
|
| 9 |
+
from ray.rllib.utils.typing import EpisodeType
|
| 10 |
+
from ray.util.annotations import PublicAPI
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@PublicAPI(stability="alpha")
|
| 14 |
+
class AddOneTsToEpisodesAndTruncate(ConnectorV2):
|
| 15 |
+
"""Adds an artificial timestep to all incoming episodes at the end.
|
| 16 |
+
|
| 17 |
+
In detail: The last observations, infos, actions, and all `extra_model_outputs`
|
| 18 |
+
will be duplicated and appended to each episode's data. An extra 0.0 reward
|
| 19 |
+
will be appended to the episode's rewards. The episode's timestep will be
|
| 20 |
+
increased by 1. Also, adds the truncated=True flag to each episode if the
|
| 21 |
+
episode is not already done (terminated or truncated).
|
| 22 |
+
|
| 23 |
+
Useful for value function bootstrapping, where it is required to compute a
|
| 24 |
+
forward pass for the very last timestep within the episode,
|
| 25 |
+
i.e. using the following input dict: {
|
| 26 |
+
obs=[final obs],
|
| 27 |
+
state=[final state output],
|
| 28 |
+
prev. reward=[final reward],
|
| 29 |
+
etc..
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
.. testcode::
|
| 33 |
+
|
| 34 |
+
from ray.rllib.connectors.learner import AddOneTsToEpisodesAndTruncate
|
| 35 |
+
from ray.rllib.env.single_agent_episode import SingleAgentEpisode
|
| 36 |
+
from ray.rllib.utils.test_utils import check
|
| 37 |
+
|
| 38 |
+
# Create 2 episodes (both to be extended by one timestep).
|
| 39 |
+
episode1 = SingleAgentEpisode(
|
| 40 |
+
observations=[0, 1, 2],
|
| 41 |
+
actions=[0, 1],
|
| 42 |
+
rewards=[0.0, 1.0],
|
| 43 |
+
terminated=False,
|
| 44 |
+
truncated=False,
|
| 45 |
+
len_lookback_buffer=0,
|
| 46 |
+
).finalize()
|
| 47 |
+
check(len(episode1), 2)
|
| 48 |
+
check(episode1.is_truncated, False)
|
| 49 |
+
|
| 50 |
+
episode2 = SingleAgentEpisode(
|
| 51 |
+
observations=[0, 1, 2, 3, 4, 5],
|
| 52 |
+
actions=[0, 1, 2, 3, 4],
|
| 53 |
+
rewards=[0.0, 1.0, 2.0, 3.0, 4.0],
|
| 54 |
+
terminated=True, # a terminated episode
|
| 55 |
+
truncated=False,
|
| 56 |
+
len_lookback_buffer=0,
|
| 57 |
+
).finalize()
|
| 58 |
+
check(len(episode2), 5)
|
| 59 |
+
check(episode2.is_truncated, False)
|
| 60 |
+
check(episode2.is_terminated, True)
|
| 61 |
+
|
| 62 |
+
# Create an instance of this class.
|
| 63 |
+
connector = AddOneTsToEpisodesAndTruncate()
|
| 64 |
+
|
| 65 |
+
# Call the connector.
|
| 66 |
+
shared_data = {}
|
| 67 |
+
_ = connector(
|
| 68 |
+
rl_module=None, # Connector used here does not require RLModule.
|
| 69 |
+
batch={},
|
| 70 |
+
episodes=[episode1, episode2],
|
| 71 |
+
shared_data=shared_data,
|
| 72 |
+
)
|
| 73 |
+
# Check on the episodes. Both of them should now be 1 timestep longer.
|
| 74 |
+
check(len(episode1), 3)
|
| 75 |
+
check(episode1.is_truncated, True)
|
| 76 |
+
check(len(episode2), 6)
|
| 77 |
+
check(episode2.is_truncated, False)
|
| 78 |
+
check(episode2.is_terminated, True)
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
@override(ConnectorV2)
|
| 82 |
+
def __call__(
|
| 83 |
+
self,
|
| 84 |
+
*,
|
| 85 |
+
rl_module: RLModule,
|
| 86 |
+
batch: Dict[str, Any],
|
| 87 |
+
episodes: List[EpisodeType],
|
| 88 |
+
explore: Optional[bool] = None,
|
| 89 |
+
shared_data: Optional[dict] = None,
|
| 90 |
+
**kwargs,
|
| 91 |
+
) -> Any:
|
| 92 |
+
# Build the loss mask to make sure the extra added timesteps do not influence
|
| 93 |
+
# the final loss and fix the terminateds and truncateds in the batch.
|
| 94 |
+
|
| 95 |
+
# For proper v-trace execution, the rules must be as follows:
|
| 96 |
+
# Legend:
|
| 97 |
+
# T: terminal=True
|
| 98 |
+
# R: truncated=True
|
| 99 |
+
# B0: bootstrap with value 0 (also: terminal=True)
|
| 100 |
+
# Bx: bootstrap with some vf-computed value (also: terminal=True)
|
| 101 |
+
|
| 102 |
+
# batch: - - - - - - - T B0- - - - - R Bx- - - - R Bx
|
| 103 |
+
# mask : t t t t t t t t f t t t t t t f t t t t t f
|
| 104 |
+
|
| 105 |
+
# TODO (sven): Same situation as in TODO below, but for multi-agent episode.
|
| 106 |
+
# Maybe add a dedicated connector piece for this task?
|
| 107 |
+
# We extend the MultiAgentEpisode's ID by a running number here to make sure
|
| 108 |
+
# we treat each MAEpisode chunk as separate (for potentially upcoming v-trace
|
| 109 |
+
# and LSTM zero-padding) and don't mix data from different chunks.
|
| 110 |
+
if isinstance(episodes[0], MultiAgentEpisode):
|
| 111 |
+
for i, ma_episode in enumerate(episodes):
|
| 112 |
+
ma_episode.id_ += "_" + str(i)
|
| 113 |
+
# Also change the underlying single-agent episode's
|
| 114 |
+
# `multi_agent_episode_id` properties.
|
| 115 |
+
for sa_episode in ma_episode.agent_episodes.values():
|
| 116 |
+
sa_episode.multi_agent_episode_id = ma_episode.id_
|
| 117 |
+
|
| 118 |
+
for i, sa_episode in enumerate(
|
| 119 |
+
self.single_agent_episode_iterator(episodes, agents_that_stepped_only=False)
|
| 120 |
+
):
|
| 121 |
+
# TODO (sven): This is a little bit of a hack: By extending the Episode's
|
| 122 |
+
# ID, we make sure that each episode chunk in `episodes` is treated as a
|
| 123 |
+
# separate episode in the `self.add_n_batch_items` below. Some algos (e.g.
|
| 124 |
+
# APPO) may have >1 episode chunks from the same episode (same ID) in the
|
| 125 |
+
# training data, thus leading to a malformatted batch in case of
|
| 126 |
+
# RNN-triggered zero-padding of the train batch.
|
| 127 |
+
# For example, if e1 (id=a len=4) and e2 (id=a len=5) are two chunks of the
|
| 128 |
+
# same episode in `episodes`, the resulting batch would have an additional
|
| 129 |
+
# timestep in the middle of the episode's "row":
|
| 130 |
+
# { "obs": {
|
| 131 |
+
# ("a", <- eps ID): [0, 1, 2, 3 <- len=4, [additional 1 ts (bad)],
|
| 132 |
+
# 0, 1, 2, 3, 4 <- len=5, [additional 1 ts]]
|
| 133 |
+
# }}
|
| 134 |
+
sa_episode.id_ += "_" + str(i)
|
| 135 |
+
|
| 136 |
+
len_ = len(sa_episode)
|
| 137 |
+
|
| 138 |
+
# Extend all episodes by one ts.
|
| 139 |
+
add_one_ts_to_episodes_and_truncate([sa_episode])
|
| 140 |
+
|
| 141 |
+
loss_mask = [True for _ in range(len_)] + [False]
|
| 142 |
+
self.add_n_batch_items(
|
| 143 |
+
batch,
|
| 144 |
+
Columns.LOSS_MASK,
|
| 145 |
+
loss_mask,
|
| 146 |
+
len_ + 1,
|
| 147 |
+
sa_episode,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
terminateds = (
|
| 151 |
+
[False for _ in range(len_ - 1)]
|
| 152 |
+
+ [bool(sa_episode.is_terminated)]
|
| 153 |
+
+ [True] # extra timestep
|
| 154 |
+
)
|
| 155 |
+
self.add_n_batch_items(
|
| 156 |
+
batch,
|
| 157 |
+
Columns.TERMINATEDS,
|
| 158 |
+
terminateds,
|
| 159 |
+
len_ + 1,
|
| 160 |
+
sa_episode,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# Signal to following connector pieces that the loss-mask which masks out
|
| 164 |
+
# invalid episode ts (for the extra added ts at the end) has already been
|
| 165 |
+
# added to `data`.
|
| 166 |
+
shared_data["_added_loss_mask_for_valid_episode_ts"] = True
|
| 167 |
+
|
| 168 |
+
return batch
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/frame_stacking.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import partial
|
| 2 |
+
|
| 3 |
+
from ray.rllib.connectors.common.frame_stacking import _FrameStacking
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
FrameStackingLearner = partial(_FrameStacking, as_learner_connector=True)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/general_advantage_estimation.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, List, Dict
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from ray.rllib.connectors.connector_v2 import ConnectorV2
|
| 6 |
+
from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor
|
| 7 |
+
from ray.rllib.core.columns import Columns
|
| 8 |
+
from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI
|
| 9 |
+
from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule
|
| 10 |
+
from ray.rllib.evaluation.postprocessing import Postprocessing
|
| 11 |
+
from ray.rllib.utils.annotations import override
|
| 12 |
+
from ray.rllib.utils.numpy import convert_to_numpy
|
| 13 |
+
from ray.rllib.utils.postprocessing.value_predictions import compute_value_targets
|
| 14 |
+
from ray.rllib.utils.postprocessing.zero_padding import (
|
| 15 |
+
split_and_zero_pad_n_episodes,
|
| 16 |
+
unpad_data_if_necessary,
|
| 17 |
+
)
|
| 18 |
+
from ray.rllib.utils.typing import EpisodeType
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class GeneralAdvantageEstimation(ConnectorV2):
|
| 22 |
+
"""Learner ConnectorV2 piece computing GAE advantages and value targets on episodes.
|
| 23 |
+
|
| 24 |
+
This ConnectorV2:
|
| 25 |
+
- Operates on a list of Episode objects (single- or multi-agent).
|
| 26 |
+
- Should be used only in the Learner pipeline and as one of the last pieces (due
|
| 27 |
+
to the fact that it requires the batch for the value functions to be already
|
| 28 |
+
complete).
|
| 29 |
+
- Requires the incoming episodes to already be elongated by one artificial timestep
|
| 30 |
+
at the end (last obs, actions, states, etc.. repeated, last reward=0.0, etc..),
|
| 31 |
+
making it possible to combine the per-timestep value computations with the
|
| 32 |
+
necessary "bootstrap" value computations at the episode (chunk) truncation points.
|
| 33 |
+
The extra timestep should be added using the `ray.rllib.connectors.learner.
|
| 34 |
+
add_one_ts_to_episodes_and_truncate.AddOneTsToEpisodesAndTruncate` connector piece.
|
| 35 |
+
|
| 36 |
+
The GAE computation is performed in an efficient way through using the arriving
|
| 37 |
+
`batch` as forward batch for the value function, extracting the bootstrap values
|
| 38 |
+
(at the artificially added time steos) and all other value predictions (all other
|
| 39 |
+
timesteps), performing GAE, and adding the results back into `batch` (under
|
| 40 |
+
Postprocessing.ADVANTAGES and Postprocessing.VALUE_TARGETS.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
input_observation_space=None,
|
| 46 |
+
input_action_space=None,
|
| 47 |
+
*,
|
| 48 |
+
gamma,
|
| 49 |
+
lambda_,
|
| 50 |
+
):
|
| 51 |
+
"""Initializes a GeneralAdvantageEstimation instance.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
gamma: The discount factor gamma.
|
| 55 |
+
lambda_: The lambda parameter for General Advantage Estimation (GAE).
|
| 56 |
+
Defines the exponential weight used between actually measured rewards
|
| 57 |
+
vs value function estimates over multiple time steps. Specifically,
|
| 58 |
+
`lambda_` balances short-term, low-variance estimates with longer-term,
|
| 59 |
+
high-variance returns. A `lambda_` or 0.0 makes the GAE rely only on
|
| 60 |
+
immediate rewards (and vf predictions from there on, reducing variance,
|
| 61 |
+
but increasing bias), while a `lambda_` of 1.0 only incorporates vf
|
| 62 |
+
predictions at the truncation points of the given episodes or episode
|
| 63 |
+
chunks (reducing bias but increasing variance).
|
| 64 |
+
"""
|
| 65 |
+
super().__init__(input_observation_space, input_action_space)
|
| 66 |
+
self.gamma = gamma
|
| 67 |
+
self.lambda_ = lambda_
|
| 68 |
+
|
| 69 |
+
# Internal numpy-to-tensor connector to translate GAE results (advantages and
|
| 70 |
+
# vf targets) into tensors.
|
| 71 |
+
self._numpy_to_tensor_connector = None
|
| 72 |
+
|
| 73 |
+
@override(ConnectorV2)
|
| 74 |
+
def __call__(
|
| 75 |
+
self,
|
| 76 |
+
*,
|
| 77 |
+
rl_module: MultiRLModule,
|
| 78 |
+
episodes: List[EpisodeType],
|
| 79 |
+
batch: Dict[str, Any],
|
| 80 |
+
**kwargs,
|
| 81 |
+
):
|
| 82 |
+
# Device to place all GAE result tensors (advantages and value targets) on.
|
| 83 |
+
device = None
|
| 84 |
+
|
| 85 |
+
# Extract all single-agent episodes.
|
| 86 |
+
sa_episodes_list = list(
|
| 87 |
+
self.single_agent_episode_iterator(episodes, agents_that_stepped_only=False)
|
| 88 |
+
)
|
| 89 |
+
# Perform the value nets' forward passes.
|
| 90 |
+
# TODO (sven): We need to check here in the pipeline already, whether a module
|
| 91 |
+
# should even be updated or not (which we usually do after(!) the Learner
|
| 92 |
+
# pipeline). This is an open TODO to move this filter into a connector as well.
|
| 93 |
+
# For now, we'll just check, whether `mid` is in batch and skip if it isn't.
|
| 94 |
+
vf_preds = rl_module.foreach_module(
|
| 95 |
+
func=lambda mid, module: (
|
| 96 |
+
module.compute_values(batch[mid])
|
| 97 |
+
if mid in batch and isinstance(module, ValueFunctionAPI)
|
| 98 |
+
else None
|
| 99 |
+
),
|
| 100 |
+
return_dict=True,
|
| 101 |
+
)
|
| 102 |
+
# Loop through all modules and perform each one's GAE computation.
|
| 103 |
+
for module_id, module_vf_preds in vf_preds.items():
|
| 104 |
+
# Skip those outputs of RLModules that are not implementers of
|
| 105 |
+
# `ValueFunctionAPI`.
|
| 106 |
+
if module_vf_preds is None:
|
| 107 |
+
continue
|
| 108 |
+
|
| 109 |
+
module = rl_module[module_id]
|
| 110 |
+
device = module_vf_preds.device
|
| 111 |
+
# Convert to numpy for the upcoming GAE computations.
|
| 112 |
+
module_vf_preds = convert_to_numpy(module_vf_preds)
|
| 113 |
+
|
| 114 |
+
# Collect (single-agent) episode lengths for this particular module.
|
| 115 |
+
episode_lens = [
|
| 116 |
+
len(e) for e in sa_episodes_list if e.module_id in [None, module_id]
|
| 117 |
+
]
|
| 118 |
+
|
| 119 |
+
# Remove all zero-padding again, if applicable, for the upcoming
|
| 120 |
+
# GAE computations.
|
| 121 |
+
module_vf_preds = unpad_data_if_necessary(episode_lens, module_vf_preds)
|
| 122 |
+
# Compute value targets.
|
| 123 |
+
module_value_targets = compute_value_targets(
|
| 124 |
+
values=module_vf_preds,
|
| 125 |
+
rewards=unpad_data_if_necessary(
|
| 126 |
+
episode_lens,
|
| 127 |
+
convert_to_numpy(batch[module_id][Columns.REWARDS]),
|
| 128 |
+
),
|
| 129 |
+
terminateds=unpad_data_if_necessary(
|
| 130 |
+
episode_lens,
|
| 131 |
+
convert_to_numpy(batch[module_id][Columns.TERMINATEDS]),
|
| 132 |
+
),
|
| 133 |
+
truncateds=unpad_data_if_necessary(
|
| 134 |
+
episode_lens,
|
| 135 |
+
convert_to_numpy(batch[module_id][Columns.TRUNCATEDS]),
|
| 136 |
+
),
|
| 137 |
+
gamma=self.gamma,
|
| 138 |
+
lambda_=self.lambda_,
|
| 139 |
+
)
|
| 140 |
+
assert module_value_targets.shape[0] == sum(episode_lens)
|
| 141 |
+
|
| 142 |
+
module_advantages = module_value_targets - module_vf_preds
|
| 143 |
+
# Drop vf-preds, not needed in loss. Note that in the PPORLModule, vf-preds
|
| 144 |
+
# are recomputed with each `forward_train` call anyway.
|
| 145 |
+
# Standardize advantages (used for more stable and better weighted
|
| 146 |
+
# policy gradient computations).
|
| 147 |
+
module_advantages = (module_advantages - module_advantages.mean()) / max(
|
| 148 |
+
1e-4, module_advantages.std()
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
# Zero-pad the new computations, if necessary.
|
| 152 |
+
if module.is_stateful():
|
| 153 |
+
module_advantages = np.stack(
|
| 154 |
+
split_and_zero_pad_n_episodes(
|
| 155 |
+
module_advantages,
|
| 156 |
+
episode_lens=episode_lens,
|
| 157 |
+
max_seq_len=module.model_config["max_seq_len"],
|
| 158 |
+
),
|
| 159 |
+
axis=0,
|
| 160 |
+
)
|
| 161 |
+
module_value_targets = np.stack(
|
| 162 |
+
split_and_zero_pad_n_episodes(
|
| 163 |
+
module_value_targets,
|
| 164 |
+
episode_lens=episode_lens,
|
| 165 |
+
max_seq_len=module.model_config["max_seq_len"],
|
| 166 |
+
),
|
| 167 |
+
axis=0,
|
| 168 |
+
)
|
| 169 |
+
batch[module_id][Postprocessing.ADVANTAGES] = module_advantages
|
| 170 |
+
batch[module_id][Postprocessing.VALUE_TARGETS] = module_value_targets
|
| 171 |
+
|
| 172 |
+
# Convert all GAE results to tensors.
|
| 173 |
+
if self._numpy_to_tensor_connector is None:
|
| 174 |
+
self._numpy_to_tensor_connector = NumpyToTensor(
|
| 175 |
+
as_learner_connector=True, device=device
|
| 176 |
+
)
|
| 177 |
+
tensor_results = self._numpy_to_tensor_connector(
|
| 178 |
+
rl_module=rl_module,
|
| 179 |
+
batch={
|
| 180 |
+
mid: {
|
| 181 |
+
Postprocessing.ADVANTAGES: module_batch[Postprocessing.ADVANTAGES],
|
| 182 |
+
Postprocessing.VALUE_TARGETS: (
|
| 183 |
+
module_batch[Postprocessing.VALUE_TARGETS]
|
| 184 |
+
),
|
| 185 |
+
}
|
| 186 |
+
for mid, module_batch in batch.items()
|
| 187 |
+
if vf_preds[mid] is not None
|
| 188 |
+
},
|
| 189 |
+
episodes=episodes,
|
| 190 |
+
)
|
| 191 |
+
# Move converted tensors back to `batch`.
|
| 192 |
+
for mid, module_batch in tensor_results.items():
|
| 193 |
+
batch[mid].update(module_batch)
|
| 194 |
+
|
| 195 |
+
return batch
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2
|
| 2 |
+
from ray.util.annotations import PublicAPI
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@PublicAPI(stability="alpha")
|
| 6 |
+
class LearnerConnectorPipeline(ConnectorPipelineV2):
|
| 7 |
+
pass
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/registry.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Registry of connector names for global access."""
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 5 |
+
from ray.rllib.connectors.connector import Connector, ConnectorContext
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
ALL_CONNECTORS = dict()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@OldAPIStack
|
| 12 |
+
def register_connector(name: str, cls: Connector):
|
| 13 |
+
"""Register a connector for use with RLlib.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
name: Name to register.
|
| 17 |
+
cls: Callable that creates an env.
|
| 18 |
+
"""
|
| 19 |
+
if name in ALL_CONNECTORS:
|
| 20 |
+
return
|
| 21 |
+
|
| 22 |
+
if not issubclass(cls, Connector):
|
| 23 |
+
raise TypeError("Can only register Connector type.", cls)
|
| 24 |
+
|
| 25 |
+
# Record it in local registry in case we need to register everything
|
| 26 |
+
# again in the global registry, for example in the event of cluster
|
| 27 |
+
# restarts.
|
| 28 |
+
ALL_CONNECTORS[name] = cls
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@OldAPIStack
|
| 32 |
+
def get_connector(name: str, ctx: ConnectorContext, params: Any = None) -> Connector:
|
| 33 |
+
# TODO(jungong) : switch the order of parameters man!!
|
| 34 |
+
"""Get a connector by its name and serialized config.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
name: name of the connector.
|
| 38 |
+
ctx: Connector context.
|
| 39 |
+
params: serialized parameters of the connector.
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
Constructed connector.
|
| 43 |
+
"""
|
| 44 |
+
if name not in ALL_CONNECTORS:
|
| 45 |
+
raise NameError("connector not found.", name)
|
| 46 |
+
return ALL_CONNECTORS[name].from_state(ctx, params)
|
vllm/lib/python3.10/site-packages/ray/rllib/connectors/util.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Any, Tuple, TYPE_CHECKING
|
| 3 |
+
|
| 4 |
+
from ray.rllib.connectors.action.clip import ClipActionsConnector
|
| 5 |
+
from ray.rllib.connectors.action.immutable import ImmutableActionsConnector
|
| 6 |
+
from ray.rllib.connectors.action.lambdas import ConvertToNumpyConnector
|
| 7 |
+
from ray.rllib.connectors.action.normalize import NormalizeActionsConnector
|
| 8 |
+
from ray.rllib.connectors.action.pipeline import ActionConnectorPipeline
|
| 9 |
+
from ray.rllib.connectors.agent.clip_reward import ClipRewardAgentConnector
|
| 10 |
+
from ray.rllib.connectors.agent.obs_preproc import ObsPreprocessorConnector
|
| 11 |
+
from ray.rllib.connectors.agent.pipeline import AgentConnectorPipeline
|
| 12 |
+
from ray.rllib.connectors.agent.state_buffer import StateBufferConnector
|
| 13 |
+
from ray.rllib.connectors.agent.view_requirement import ViewRequirementAgentConnector
|
| 14 |
+
from ray.rllib.connectors.connector import Connector, ConnectorContext
|
| 15 |
+
from ray.rllib.connectors.registry import get_connector
|
| 16 |
+
from ray.rllib.connectors.agent.mean_std_filter import (
|
| 17 |
+
MeanStdObservationFilterAgentConnector,
|
| 18 |
+
ConcurrentMeanStdObservationFilterAgentConnector,
|
| 19 |
+
)
|
| 20 |
+
from ray.rllib.utils.annotations import OldAPIStack
|
| 21 |
+
from ray.rllib.connectors.agent.synced_filter import SyncedFilterAgentConnector
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
|
| 25 |
+
from ray.rllib.policy.policy import Policy
|
| 26 |
+
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def __preprocessing_enabled(config: "AlgorithmConfig"):
|
| 31 |
+
if config._disable_preprocessor_api:
|
| 32 |
+
return False
|
| 33 |
+
# Same conditions as in RolloutWorker.__init__.
|
| 34 |
+
if config.is_atari and config.preprocessor_pref == "deepmind":
|
| 35 |
+
return False
|
| 36 |
+
if config.preprocessor_pref is None:
|
| 37 |
+
return False
|
| 38 |
+
return True
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def __clip_rewards(config: "AlgorithmConfig"):
|
| 42 |
+
# Same logic as in RolloutWorker.__init__.
|
| 43 |
+
# We always clip rewards for Atari games.
|
| 44 |
+
return config.clip_rewards or config.is_atari
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@OldAPIStack
|
| 48 |
+
def get_agent_connectors_from_config(
|
| 49 |
+
ctx: ConnectorContext,
|
| 50 |
+
config: "AlgorithmConfig",
|
| 51 |
+
) -> AgentConnectorPipeline:
|
| 52 |
+
connectors = []
|
| 53 |
+
|
| 54 |
+
clip_rewards = __clip_rewards(config)
|
| 55 |
+
if clip_rewards is True:
|
| 56 |
+
connectors.append(ClipRewardAgentConnector(ctx, sign=True))
|
| 57 |
+
elif type(clip_rewards) == float:
|
| 58 |
+
connectors.append(ClipRewardAgentConnector(ctx, limit=abs(clip_rewards)))
|
| 59 |
+
|
| 60 |
+
if __preprocessing_enabled(config):
|
| 61 |
+
connectors.append(ObsPreprocessorConnector(ctx))
|
| 62 |
+
|
| 63 |
+
# Filters should be after observation preprocessing
|
| 64 |
+
filter_connector = get_synced_filter_connector(
|
| 65 |
+
ctx,
|
| 66 |
+
)
|
| 67 |
+
# Configuration option "NoFilter" results in `filter_connector==None`.
|
| 68 |
+
if filter_connector:
|
| 69 |
+
connectors.append(filter_connector)
|
| 70 |
+
|
| 71 |
+
connectors.extend(
|
| 72 |
+
[
|
| 73 |
+
StateBufferConnector(ctx),
|
| 74 |
+
ViewRequirementAgentConnector(ctx),
|
| 75 |
+
]
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
return AgentConnectorPipeline(ctx, connectors)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@OldAPIStack
|
| 82 |
+
def get_action_connectors_from_config(
|
| 83 |
+
ctx: ConnectorContext,
|
| 84 |
+
config: "AlgorithmConfig",
|
| 85 |
+
) -> ActionConnectorPipeline:
|
| 86 |
+
"""Default list of action connectors to use for a new policy.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
ctx: context used to create connectors.
|
| 90 |
+
config: The AlgorithmConfig object.
|
| 91 |
+
"""
|
| 92 |
+
connectors = [ConvertToNumpyConnector(ctx)]
|
| 93 |
+
if config.get("normalize_actions", False):
|
| 94 |
+
connectors.append(NormalizeActionsConnector(ctx))
|
| 95 |
+
if config.get("clip_actions", False):
|
| 96 |
+
connectors.append(ClipActionsConnector(ctx))
|
| 97 |
+
connectors.append(ImmutableActionsConnector(ctx))
|
| 98 |
+
return ActionConnectorPipeline(ctx, connectors)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@OldAPIStack
|
| 102 |
+
def create_connectors_for_policy(policy: "Policy", config: "AlgorithmConfig"):
|
| 103 |
+
"""Util to create agent and action connectors for a Policy.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
policy: Policy instance.
|
| 107 |
+
config: Algorithm config dict.
|
| 108 |
+
"""
|
| 109 |
+
ctx: ConnectorContext = ConnectorContext.from_policy(policy)
|
| 110 |
+
|
| 111 |
+
assert (
|
| 112 |
+
policy.agent_connectors is None and policy.action_connectors is None
|
| 113 |
+
), "Can not create connectors for a policy that already has connectors."
|
| 114 |
+
|
| 115 |
+
policy.agent_connectors = get_agent_connectors_from_config(ctx, config)
|
| 116 |
+
policy.action_connectors = get_action_connectors_from_config(ctx, config)
|
| 117 |
+
|
| 118 |
+
logger.info("Using connectors:")
|
| 119 |
+
logger.info(policy.agent_connectors.__str__(indentation=4))
|
| 120 |
+
logger.info(policy.action_connectors.__str__(indentation=4))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@OldAPIStack
|
| 124 |
+
def restore_connectors_for_policy(
|
| 125 |
+
policy: "Policy", connector_config: Tuple[str, Tuple[Any]]
|
| 126 |
+
) -> Connector:
|
| 127 |
+
"""Util to create connector for a Policy based on serialized config.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
policy: Policy instance.
|
| 131 |
+
connector_config: Serialized connector config.
|
| 132 |
+
"""
|
| 133 |
+
ctx: ConnectorContext = ConnectorContext.from_policy(policy)
|
| 134 |
+
name, params = connector_config
|
| 135 |
+
return get_connector(name, ctx, params)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# We need this filter selection mechanism temporarily to remain compatible to old API
|
| 139 |
+
@OldAPIStack
|
| 140 |
+
def get_synced_filter_connector(ctx: ConnectorContext):
|
| 141 |
+
filter_specifier = ctx.config.get("observation_filter")
|
| 142 |
+
if filter_specifier == "MeanStdFilter":
|
| 143 |
+
return MeanStdObservationFilterAgentConnector(ctx, clip=None)
|
| 144 |
+
elif filter_specifier == "ConcurrentMeanStdFilter":
|
| 145 |
+
return ConcurrentMeanStdObservationFilterAgentConnector(ctx, clip=None)
|
| 146 |
+
elif filter_specifier == "NoFilter":
|
| 147 |
+
return None
|
| 148 |
+
else:
|
| 149 |
+
raise Exception("Unknown observation_filter: " + str(filter_specifier))
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@OldAPIStack
|
| 153 |
+
def maybe_get_filters_for_syncing(rollout_worker, policy_id):
|
| 154 |
+
# As long as the historic filter synchronization mechanism is in
|
| 155 |
+
# place, we need to put filters into self.filters so that they get
|
| 156 |
+
# synchronized
|
| 157 |
+
policy = rollout_worker.policy_map[policy_id]
|
| 158 |
+
if not policy.agent_connectors:
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
filter_connectors = policy.agent_connectors[SyncedFilterAgentConnector]
|
| 162 |
+
# There can only be one filter at a time
|
| 163 |
+
if not filter_connectors:
|
| 164 |
+
return
|
| 165 |
+
|
| 166 |
+
assert len(filter_connectors) == 1, (
|
| 167 |
+
"ConnectorPipeline has multiple connectors of type "
|
| 168 |
+
"SyncedFilterAgentConnector but can only have one."
|
| 169 |
+
)
|
| 170 |
+
rollout_worker.filters[policy_id] = filter_connectors[0].filter
|
vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (3.41 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc
ADDED
|
Binary file (8.02 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-310.pyc
ADDED
|
Binary file (24.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc
ADDED
|
Binary file (4.01 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc
ADDED
|
Binary file (5.31 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/framework.cpython-310.pyc
ADDED
|
Binary file (10 kB). View file
|
|
|