ZTWHHH commited on
Commit
aef02a5
·
verified ·
1 Parent(s): eb225d3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_ufunc.cpython-310.pyc +3 -0
  3. parrot/lib/python3.10/site-packages/scipy/io/__pycache__/_idl.cpython-310.pyc +0 -0
  4. parrot/lib/python3.10/site-packages/scipy/io/__pycache__/idl.cpython-310.pyc +0 -0
  5. parrot/lib/python3.10/site-packages/scipy/io/__pycache__/mmio.cpython-310.pyc +0 -0
  6. parrot/lib/python3.10/site-packages/scipy/io/__pycache__/netcdf.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat +0 -0
  8. parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat +0 -0
  9. parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav +0 -0
  10. parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav +0 -0
  11. vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/base_env.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-310.pyc +0 -0
  14. vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__init__.py +0 -0
  15. vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/__init__.cpython-310.pyc +0 -0
  16. vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/task_settable_env.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/ray/rllib/env/external_multi_agent_env.py +161 -0
  18. vllm/lib/python3.10/site-packages/ray/rllib/env/remote_base_env.py +462 -0
  19. vllm/lib/python3.10/site-packages/ray/rllib/env/utils/__init__.py +124 -0
  20. vllm/lib/python3.10/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py +707 -0
  21. vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/__init__.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/action_dist.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/catalog.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/distributions.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/modelv2.cpython-310.pyc +0 -0
  26. vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/preprocessors.cpython-310.pyc +0 -0
  27. vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/repeated_values.cpython-310.pyc +0 -0
  28. vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/utils.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/ray/rllib/models/preprocessors.py +447 -0
  30. vllm/lib/python3.10/site-packages/ray/rllib/models/repeated_values.py +204 -0
  31. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/attention_net.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/complex_input_net.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/fcnet.cpython-310.pyc +0 -0
  34. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/misc.cpython-310.pyc +0 -0
  35. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/noop.cpython-310.pyc +0 -0
  36. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/recurrent_net.cpython-310.pyc +0 -0
  37. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/tf_distributions.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/visionnet.cpython-310.pyc +0 -0
  39. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/fcnet.py +148 -0
  40. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/__init__.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/gru_gate.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/multi_head_attention.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/noisy_layer.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/relative_multi_head_attention.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/skip_connection.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/gru_gate.py +58 -0
  47. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/multi_head_attention.py +61 -0
  48. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/noisy_layer.py +118 -0
  49. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/relative_multi_head_attention.py +147 -0
  50. vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/skip_connection.py +46 -0
.gitattributes CHANGED
@@ -1452,3 +1452,4 @@ parrot/lib/python3.10/site-packages/numpy/linalg/__pycache__/_linalg.cpython-310
1452
  vllm/lib/python3.10/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1453
  parrot/lib/python3.10/site-packages/numpy/_core/lib/libnpymath.a filter=lfs diff=lfs merge=lfs -text
1454
  parrot/lib/python3.10/site-packages/numpy/_core/_multiarray_tests.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
1452
  vllm/lib/python3.10/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1453
  parrot/lib/python3.10/site-packages/numpy/_core/lib/libnpymath.a filter=lfs diff=lfs merge=lfs -text
1454
  parrot/lib/python3.10/site-packages/numpy/_core/_multiarray_tests.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1455
+ parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_ufunc.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_ufunc.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a4d941a6095db86ad6e706837ad9fb6bb6ee240ed2aada924c37002d0a75470
3
+ size 105385
parrot/lib/python3.10/site-packages/scipy/io/__pycache__/_idl.cpython-310.pyc ADDED
Binary file (19.2 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/io/__pycache__/idl.cpython-310.pyc ADDED
Binary file (564 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/io/__pycache__/mmio.cpython-310.pyc ADDED
Binary file (587 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/io/__pycache__/netcdf.cpython-310.pyc ADDED
Binary file (596 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat ADDED
Binary file (26.4 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat ADDED
Binary file (28 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav ADDED
Binary file (2.08 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav ADDED
Binary file (2.3 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/base_env.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-310.pyc ADDED
Binary file (74.2 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (168 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/env/apis/__pycache__/task_settable_env.cpython-310.pyc ADDED
Binary file (2.09 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/env/external_multi_agent_env.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ import gymnasium as gym
3
+ from typing import Optional
4
+
5
+ from ray.rllib.utils.annotations import override, OldAPIStack
6
+ from ray.rllib.env.external_env import ExternalEnv, _ExternalEnvEpisode
7
+ from ray.rllib.utils.typing import MultiAgentDict
8
+
9
+
10
+ @OldAPIStack
11
+ class ExternalMultiAgentEnv(ExternalEnv):
12
+ """This is the multi-agent version of ExternalEnv."""
13
+
14
+ def __init__(
15
+ self,
16
+ action_space: gym.Space,
17
+ observation_space: gym.Space,
18
+ ):
19
+ """Initializes an ExternalMultiAgentEnv instance.
20
+
21
+ Args:
22
+ action_space: Action space of the env.
23
+ observation_space: Observation space of the env.
24
+ """
25
+ ExternalEnv.__init__(self, action_space, observation_space)
26
+
27
+ # We require to know all agents' spaces.
28
+ if isinstance(self.action_space, dict) or isinstance(
29
+ self.observation_space, dict
30
+ ):
31
+ if not (self.action_space.keys() == self.observation_space.keys()):
32
+ raise ValueError(
33
+ "Agent ids disagree for action space and obs "
34
+ "space dict: {} {}".format(
35
+ self.action_space.keys(), self.observation_space.keys()
36
+ )
37
+ )
38
+
39
+ def run(self):
40
+ """Override this to implement the multi-agent run loop.
41
+
42
+ Your loop should continuously:
43
+ 1. Call self.start_episode(episode_id)
44
+ 2. Call self.get_action(episode_id, obs_dict)
45
+ -or-
46
+ self.log_action(episode_id, obs_dict, action_dict)
47
+ 3. Call self.log_returns(episode_id, reward_dict)
48
+ 4. Call self.end_episode(episode_id, obs_dict)
49
+ 5. Wait if nothing to do.
50
+
51
+ Multiple episodes may be started at the same time.
52
+ """
53
+ raise NotImplementedError
54
+
55
+ @override(ExternalEnv)
56
+ def start_episode(
57
+ self, episode_id: Optional[str] = None, training_enabled: bool = True
58
+ ) -> str:
59
+ if episode_id is None:
60
+ episode_id = uuid.uuid4().hex
61
+
62
+ if episode_id in self._finished:
63
+ raise ValueError("Episode {} has already completed.".format(episode_id))
64
+
65
+ if episode_id in self._episodes:
66
+ raise ValueError("Episode {} is already started".format(episode_id))
67
+
68
+ self._episodes[episode_id] = _ExternalEnvEpisode(
69
+ episode_id, self._results_avail_condition, training_enabled, multiagent=True
70
+ )
71
+
72
+ return episode_id
73
+
74
+ @override(ExternalEnv)
75
+ def get_action(
76
+ self, episode_id: str, observation_dict: MultiAgentDict
77
+ ) -> MultiAgentDict:
78
+ """Record an observation and get the on-policy action.
79
+
80
+ Thereby, observation_dict is expected to contain the observation
81
+ of all agents acting in this episode step.
82
+
83
+ Args:
84
+ episode_id: Episode id returned from start_episode().
85
+ observation_dict: Current environment observation.
86
+
87
+ Returns:
88
+ action: Action from the env action space.
89
+ """
90
+
91
+ episode = self._get(episode_id)
92
+ return episode.wait_for_action(observation_dict)
93
+
94
+ @override(ExternalEnv)
95
+ def log_action(
96
+ self,
97
+ episode_id: str,
98
+ observation_dict: MultiAgentDict,
99
+ action_dict: MultiAgentDict,
100
+ ) -> None:
101
+ """Record an observation and (off-policy) action taken.
102
+
103
+ Args:
104
+ episode_id: Episode id returned from start_episode().
105
+ observation_dict: Current environment observation.
106
+ action_dict: Action for the observation.
107
+ """
108
+
109
+ episode = self._get(episode_id)
110
+ episode.log_action(observation_dict, action_dict)
111
+
112
+ @override(ExternalEnv)
113
+ def log_returns(
114
+ self,
115
+ episode_id: str,
116
+ reward_dict: MultiAgentDict,
117
+ info_dict: MultiAgentDict = None,
118
+ multiagent_done_dict: MultiAgentDict = None,
119
+ ) -> None:
120
+ """Record returns from the environment.
121
+
122
+ The reward will be attributed to the previous action taken by the
123
+ episode. Rewards accumulate until the next action. If no reward is
124
+ logged before the next action, a reward of 0.0 is assumed.
125
+
126
+ Args:
127
+ episode_id: Episode id returned from start_episode().
128
+ reward_dict: Reward from the environment agents.
129
+ info_dict: Optional info dict.
130
+ multiagent_done_dict: Optional done dict for agents.
131
+ """
132
+
133
+ episode = self._get(episode_id)
134
+
135
+ # Accumulate reward by agent.
136
+ # For existing agents, we want to add the reward up.
137
+ for agent, rew in reward_dict.items():
138
+ if agent in episode.cur_reward_dict:
139
+ episode.cur_reward_dict[agent] += rew
140
+ else:
141
+ episode.cur_reward_dict[agent] = rew
142
+
143
+ if multiagent_done_dict:
144
+ for agent, done in multiagent_done_dict.items():
145
+ episode.cur_done_dict[agent] = done
146
+
147
+ if info_dict:
148
+ episode.cur_info_dict = info_dict or {}
149
+
150
+ @override(ExternalEnv)
151
+ def end_episode(self, episode_id: str, observation_dict: MultiAgentDict) -> None:
152
+ """Record the end of an episode.
153
+
154
+ Args:
155
+ episode_id: Episode id returned from start_episode().
156
+ observation_dict: Current environment observation.
157
+ """
158
+
159
+ episode = self._get(episode_id)
160
+ self._finished.add(episode.episode_id)
161
+ episode.done(observation_dict)
vllm/lib/python3.10/site-packages/ray/rllib/env/remote_base_env.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gymnasium as gym
2
+ import logging
3
+ from typing import Callable, Dict, List, Optional, Set, Tuple, TYPE_CHECKING
4
+
5
+ import ray
6
+ from ray.util import log_once
7
+ from ray.rllib.env.base_env import BaseEnv, _DUMMY_AGENT_ID, ASYNC_RESET_RETURN
8
+ from ray.rllib.utils.annotations import override, OldAPIStack
9
+ from ray.rllib.utils.typing import AgentID, EnvID, EnvType, MultiEnvDict
10
+
11
+ if TYPE_CHECKING:
12
+ from ray.rllib.evaluation.rollout_worker import RolloutWorker
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ @OldAPIStack
18
+ class RemoteBaseEnv(BaseEnv):
19
+ """BaseEnv that executes its sub environments as @ray.remote actors.
20
+
21
+ This provides dynamic batching of inference as observations are returned
22
+ from the remote simulator actors. Both single and multi-agent child envs
23
+ are supported, and envs can be stepped synchronously or asynchronously.
24
+
25
+ NOTE: This class implicitly assumes that the remote envs are gym.Env's
26
+
27
+ You shouldn't need to instantiate this class directly. It's automatically
28
+ inserted when you use the `remote_worker_envs=True` option in your
29
+ Algorithm's config.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ make_env: Callable[[int], EnvType],
35
+ num_envs: int,
36
+ multiagent: bool,
37
+ remote_env_batch_wait_ms: int,
38
+ existing_envs: Optional[List[ray.actor.ActorHandle]] = None,
39
+ worker: Optional["RolloutWorker"] = None,
40
+ restart_failed_sub_environments: bool = False,
41
+ ):
42
+ """Initializes a RemoteVectorEnv instance.
43
+
44
+ Args:
45
+ make_env: Callable that produces a single (non-vectorized) env,
46
+ given the vector env index as only arg.
47
+ num_envs: The number of sub-environments to create for the
48
+ vectorization.
49
+ multiagent: Whether this is a multiagent env or not.
50
+ remote_env_batch_wait_ms: Time to wait for (ray.remote)
51
+ sub-environments to have new observations available when
52
+ polled. Only when none of the sub-environments is ready,
53
+ repeat the `ray.wait()` call until at least one sub-env
54
+ is ready. Then return only the observations of the ready
55
+ sub-environment(s).
56
+ existing_envs: Optional list of already created sub-environments.
57
+ These will be used as-is and only as many new sub-envs as
58
+ necessary (`num_envs - len(existing_envs)`) will be created.
59
+ worker: An optional RolloutWorker that owns the env. This is only
60
+ used if `remote_worker_envs` is True in your config and the
61
+ `on_sub_environment_created` custom callback needs to be
62
+ called on each created actor.
63
+ restart_failed_sub_environments: If True and any sub-environment (within
64
+ a vectorized env) throws any error during env stepping, the
65
+ Sampler will try to restart the faulty sub-environment. This is done
66
+ without disturbing the other (still intact) sub-environment and without
67
+ the RolloutWorker crashing.
68
+ """
69
+
70
+ # Could be creating local or remote envs.
71
+ self.make_env = make_env
72
+ self.num_envs = num_envs
73
+ self.multiagent = multiagent
74
+ self.poll_timeout = remote_env_batch_wait_ms / 1000
75
+ self.worker = worker
76
+ self.restart_failed_sub_environments = restart_failed_sub_environments
77
+
78
+ # Already existing env objects (generated by the RolloutWorker).
79
+ existing_envs = existing_envs or []
80
+
81
+ # Whether the given `make_env` callable already returns ActorHandles
82
+ # (@ray.remote class instances) or not.
83
+ self.make_env_creates_actors = False
84
+
85
+ self._observation_space = None
86
+ self._action_space = None
87
+
88
+ # List of ray actor handles (each handle points to one @ray.remote
89
+ # sub-environment).
90
+ self.actors: Optional[List[ray.actor.ActorHandle]] = None
91
+
92
+ # `self.make_env` already produces Actors: Use it directly.
93
+ if len(existing_envs) > 0 and isinstance(
94
+ existing_envs[0], ray.actor.ActorHandle
95
+ ):
96
+ self.make_env_creates_actors = True
97
+ self.actors = existing_envs
98
+ while len(self.actors) < self.num_envs:
99
+ self.actors.append(self._make_sub_env(len(self.actors)))
100
+
101
+ # `self.make_env` produces gym.Envs (or children thereof, such
102
+ # as MultiAgentEnv): Need to auto-wrap it here. The problem with
103
+ # this is that custom methods wil get lost. If you would like to
104
+ # keep your custom methods in your envs, you should provide the
105
+ # env class directly in your config (w/o tune.register_env()),
106
+ # such that your class can directly be made a @ray.remote
107
+ # (w/o the wrapping via `_Remote[Multi|Single]AgentEnv`).
108
+ # Also, if `len(existing_envs) > 0`, we have to throw those away
109
+ # as we need to create ray actors here.
110
+ else:
111
+ self.actors = [self._make_sub_env(i) for i in range(self.num_envs)]
112
+ # Utilize existing envs for inferring observation/action spaces.
113
+ if len(existing_envs) > 0:
114
+ self._observation_space = existing_envs[0].observation_space
115
+ self._action_space = existing_envs[0].action_space
116
+ # Have to call actors' remote methods to get observation/action spaces.
117
+ else:
118
+ self._observation_space, self._action_space = ray.get(
119
+ [
120
+ self.actors[0].observation_space.remote(),
121
+ self.actors[0].action_space.remote(),
122
+ ]
123
+ )
124
+
125
+ # Dict mapping object refs (return values of @ray.remote calls),
126
+ # whose actual values we are waiting for (via ray.wait in
127
+ # `self.poll()`) to their corresponding actor handles (the actors
128
+ # that created these return values).
129
+ # Call `reset()` on all @ray.remote sub-environment actors.
130
+ self.pending: Dict[ray.actor.ActorHandle] = {
131
+ a.reset.remote(): a for a in self.actors
132
+ }
133
+
134
+ @override(BaseEnv)
135
+ def poll(
136
+ self,
137
+ ) -> Tuple[
138
+ MultiEnvDict,
139
+ MultiEnvDict,
140
+ MultiEnvDict,
141
+ MultiEnvDict,
142
+ MultiEnvDict,
143
+ MultiEnvDict,
144
+ ]:
145
+
146
+ # each keyed by env_id in [0, num_remote_envs)
147
+ obs, rewards, terminateds, truncateds, infos = {}, {}, {}, {}, {}
148
+ ready = []
149
+
150
+ # Wait for at least 1 env to be ready here.
151
+ while not ready:
152
+ ready, _ = ray.wait(
153
+ list(self.pending),
154
+ num_returns=len(self.pending),
155
+ timeout=self.poll_timeout,
156
+ )
157
+
158
+ # Get and return observations for each of the ready envs
159
+ env_ids = set()
160
+ for obj_ref in ready:
161
+ # Get the corresponding actor handle from our dict and remove the
162
+ # object ref (we will call `ray.get()` on it and it will no longer
163
+ # be "pending").
164
+ actor = self.pending.pop(obj_ref)
165
+ env_id = self.actors.index(actor)
166
+ env_ids.add(env_id)
167
+ # Get the ready object ref (this may be return value(s) of
168
+ # `reset()` or `step()`).
169
+ try:
170
+ ret = ray.get(obj_ref)
171
+ except Exception as e:
172
+ # Something happened on the actor during stepping/resetting.
173
+ # Restart sub-environment (create new actor; close old one).
174
+ if self.restart_failed_sub_environments:
175
+ logger.exception(e.args[0])
176
+ self.try_restart(env_id)
177
+ # Always return multi-agent data.
178
+ # Set the observation to the exception, no rewards,
179
+ # terminated[__all__]=True (episode will be discarded anyways),
180
+ # no infos.
181
+ ret = (
182
+ e,
183
+ {},
184
+ {"__all__": True},
185
+ {"__all__": False},
186
+ {},
187
+ )
188
+ # Do not try to restart. Just raise the error.
189
+ else:
190
+ raise e
191
+
192
+ # Our sub-envs are simple Actor-turned gym.Envs or MultiAgentEnvs.
193
+ if self.make_env_creates_actors:
194
+ rew, terminated, truncated, info = None, None, None, None
195
+ if self.multiagent:
196
+ if isinstance(ret, tuple):
197
+ # Gym >= 0.26: `step()` result: Obs, reward, terminated,
198
+ # truncated, info.
199
+ if len(ret) == 5:
200
+ ob, rew, terminated, truncated, info = ret
201
+ # Gym >= 0.26: `reset()` result: Obs and infos.
202
+ elif len(ret) == 2:
203
+ ob = ret[0]
204
+ info = ret[1]
205
+ # Gym < 0.26? Something went wrong.
206
+ else:
207
+ raise AssertionError(
208
+ "Your gymnasium.Env seems to NOT return the correct "
209
+ "number of return values for `step()` (needs to return"
210
+ " 5 values: obs, reward, terminated, truncated and "
211
+ "info) or `reset()` (needs to return 2 values: obs and "
212
+ "info)!"
213
+ )
214
+ # Gym < 0.26: `reset()` result: Only obs.
215
+ else:
216
+ raise AssertionError(
217
+ "Your gymnasium.Env seems to only return a single value "
218
+ "upon `reset()`! Must return 2 (obs AND infos)."
219
+ )
220
+ else:
221
+ if isinstance(ret, tuple):
222
+ # `step()` result: Obs, reward, terminated, truncated, info.
223
+ if len(ret) == 5:
224
+ ob = {_DUMMY_AGENT_ID: ret[0]}
225
+ rew = {_DUMMY_AGENT_ID: ret[1]}
226
+ terminated = {_DUMMY_AGENT_ID: ret[2], "__all__": ret[2]}
227
+ truncated = {_DUMMY_AGENT_ID: ret[3], "__all__": ret[3]}
228
+ info = {_DUMMY_AGENT_ID: ret[4]}
229
+ # `reset()` result: Obs and infos.
230
+ elif len(ret) == 2:
231
+ ob = {_DUMMY_AGENT_ID: ret[0]}
232
+ info = {_DUMMY_AGENT_ID: ret[1]}
233
+ # Gym < 0.26? Something went wrong.
234
+ else:
235
+ raise AssertionError(
236
+ "Your gymnasium.Env seems to NOT return the correct "
237
+ "number of return values for `step()` (needs to return"
238
+ " 5 values: obs, reward, terminated, truncated and "
239
+ "info) or `reset()` (needs to return 2 values: obs and "
240
+ "info)!"
241
+ )
242
+ # Gym < 0.26?
243
+ else:
244
+ raise AssertionError(
245
+ "Your gymnasium.Env seems to only return a single value "
246
+ "upon `reset()`! Must return 2 (obs and infos)."
247
+ )
248
+
249
+ # If this is a `reset()` return value, we only have the initial
250
+ # observations and infos: Set rewards, terminateds, and truncateds to
251
+ # dummy values.
252
+ if rew is None:
253
+ rew = {agent_id: 0 for agent_id in ob.keys()}
254
+ terminated = {"__all__": False}
255
+ truncated = {"__all__": False}
256
+
257
+ # Our sub-envs are auto-wrapped (by `_RemoteSingleAgentEnv` or
258
+ # `_RemoteMultiAgentEnv`) and already behave like multi-agent
259
+ # envs.
260
+ else:
261
+ ob, rew, terminated, truncated, info = ret
262
+ obs[env_id] = ob
263
+ rewards[env_id] = rew
264
+ terminateds[env_id] = terminated
265
+ truncateds[env_id] = truncated
266
+ infos[env_id] = info
267
+
268
+ logger.debug(f"Got obs batch for actors {env_ids}")
269
+ return obs, rewards, terminateds, truncateds, infos, {}
270
+
271
+ @override(BaseEnv)
272
+ def send_actions(self, action_dict: MultiEnvDict) -> None:
273
+ for env_id, actions in action_dict.items():
274
+ actor = self.actors[env_id]
275
+ # `actor` is a simple single-agent (remote) env, e.g. a gym.Env
276
+ # that was made a @ray.remote.
277
+ if not self.multiagent and self.make_env_creates_actors:
278
+ obj_ref = actor.step.remote(actions[_DUMMY_AGENT_ID])
279
+ # `actor` is already a _RemoteSingleAgentEnv or
280
+ # _RemoteMultiAgentEnv wrapper
281
+ # (handles the multi-agent action_dict automatically).
282
+ else:
283
+ obj_ref = actor.step.remote(actions)
284
+ self.pending[obj_ref] = actor
285
+
286
+ @override(BaseEnv)
287
+ def try_reset(
288
+ self,
289
+ env_id: Optional[EnvID] = None,
290
+ *,
291
+ seed: Optional[int] = None,
292
+ options: Optional[dict] = None,
293
+ ) -> Tuple[MultiEnvDict, MultiEnvDict]:
294
+ actor = self.actors[env_id]
295
+ obj_ref = actor.reset.remote(seed=seed, options=options)
296
+
297
+ self.pending[obj_ref] = actor
298
+ # Because this env type does not support synchronous reset requests (with
299
+ # immediate return value), we return ASYNC_RESET_RETURN here to indicate
300
+ # that the reset results will be available via the next `poll()` call.
301
+ return ASYNC_RESET_RETURN, ASYNC_RESET_RETURN
302
+
303
+ @override(BaseEnv)
304
+ def try_restart(self, env_id: Optional[EnvID] = None) -> None:
305
+ # Try closing down the old (possibly faulty) sub-env, but ignore errors.
306
+ try:
307
+ # Close the env on the remote side.
308
+ self.actors[env_id].close.remote()
309
+ except Exception as e:
310
+ if log_once("close_sub_env"):
311
+ logger.warning(
312
+ "Trying to close old and replaced sub-environment (at vector "
313
+ f"index={env_id}), but closing resulted in error:\n{e}"
314
+ )
315
+
316
+ # Terminate the actor itself to free up its resources.
317
+ self.actors[env_id].__ray_terminate__.remote()
318
+
319
+ # Re-create a new sub-environment.
320
+ self.actors[env_id] = self._make_sub_env(env_id)
321
+
322
+ @override(BaseEnv)
323
+ def stop(self) -> None:
324
+ if self.actors is not None:
325
+ for actor in self.actors:
326
+ actor.__ray_terminate__.remote()
327
+
328
+ @override(BaseEnv)
329
+ def get_sub_environments(self, as_dict: bool = False) -> List[EnvType]:
330
+ if as_dict:
331
+ return {env_id: actor for env_id, actor in enumerate(self.actors)}
332
+ return self.actors
333
+
334
+ @property
335
+ @override(BaseEnv)
336
+ def observation_space(self) -> gym.spaces.Dict:
337
+ return self._observation_space
338
+
339
+ @property
340
+ @override(BaseEnv)
341
+ def action_space(self) -> gym.Space:
342
+ return self._action_space
343
+
344
+ def _make_sub_env(self, idx: Optional[int] = None):
345
+ """Re-creates a sub-environment at the new index."""
346
+
347
+ # Our `make_env` creates ray actors directly.
348
+ if self.make_env_creates_actors:
349
+ sub_env = self.make_env(idx)
350
+ if self.worker is not None:
351
+ self.worker.callbacks.on_sub_environment_created(
352
+ worker=self.worker,
353
+ sub_environment=self.actors[idx],
354
+ env_context=self.worker.env_context.copy_with_overrides(
355
+ vector_index=idx
356
+ ),
357
+ )
358
+
359
+ # Our `make_env` returns actual envs -> Have to convert them into actors
360
+ # using our utility wrapper classes.
361
+ else:
362
+
363
+ def make_remote_env(i):
364
+ logger.info("Launching env {} in remote actor".format(i))
365
+ if self.multiagent:
366
+ sub_env = _RemoteMultiAgentEnv.remote(self.make_env, i)
367
+ else:
368
+ sub_env = _RemoteSingleAgentEnv.remote(self.make_env, i)
369
+
370
+ if self.worker is not None:
371
+ self.worker.callbacks.on_sub_environment_created(
372
+ worker=self.worker,
373
+ sub_environment=sub_env,
374
+ env_context=self.worker.env_context.copy_with_overrides(
375
+ vector_index=i
376
+ ),
377
+ )
378
+
379
+ return sub_env
380
+
381
+ sub_env = make_remote_env(idx)
382
+
383
+ return sub_env
384
+
385
+ @override(BaseEnv)
386
+ def get_agent_ids(self) -> Set[AgentID]:
387
+ if self.multiagent:
388
+ return ray.get(self.actors[0].get_agent_ids.remote())
389
+ else:
390
+ return {_DUMMY_AGENT_ID}
391
+
392
+
393
+ @ray.remote(num_cpus=0)
394
+ class _RemoteMultiAgentEnv:
395
+ """Wrapper class for making a multi-agent env a remote actor."""
396
+
397
+ def __init__(self, make_env, i):
398
+ self.env = make_env(i)
399
+ self.agent_ids = set()
400
+
401
+ def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None):
402
+ obs, info = self.env.reset(seed=seed, options=options)
403
+
404
+ # each keyed by agent_id in the env
405
+ rew = {}
406
+ for agent_id in obs.keys():
407
+ self.agent_ids.add(agent_id)
408
+ rew[agent_id] = 0.0
409
+ terminated = {"__all__": False}
410
+ truncated = {"__all__": False}
411
+ return obs, rew, terminated, truncated, info
412
+
413
+ def step(self, action_dict):
414
+ return self.env.step(action_dict)
415
+
416
+ # Defining these 2 functions that way this information can be queried
417
+ # with a call to ray.get().
418
+ def observation_space(self):
419
+ return self.env.observation_space
420
+
421
+ def action_space(self):
422
+ return self.env.action_space
423
+
424
+ def get_agent_ids(self) -> Set[AgentID]:
425
+ return self.agent_ids
426
+
427
+
428
+ @ray.remote(num_cpus=0)
429
+ class _RemoteSingleAgentEnv:
430
+ """Wrapper class for making a gym env a remote actor."""
431
+
432
+ def __init__(self, make_env, i):
433
+ self.env = make_env(i)
434
+
435
+ def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None):
436
+ obs_and_info = self.env.reset(seed=seed, options=options)
437
+
438
+ obs = {_DUMMY_AGENT_ID: obs_and_info[0]}
439
+ info = {_DUMMY_AGENT_ID: obs_and_info[1]}
440
+
441
+ rew = {_DUMMY_AGENT_ID: 0.0}
442
+ terminated = {"__all__": False}
443
+ truncated = {"__all__": False}
444
+ return obs, rew, terminated, truncated, info
445
+
446
+ def step(self, action):
447
+ results = self.env.step(action[_DUMMY_AGENT_ID])
448
+
449
+ obs, rew, terminated, truncated, info = [{_DUMMY_AGENT_ID: x} for x in results]
450
+
451
+ terminated["__all__"] = terminated[_DUMMY_AGENT_ID]
452
+ truncated["__all__"] = truncated[_DUMMY_AGENT_ID]
453
+
454
+ return obs, rew, terminated, truncated, info
455
+
456
+ # Defining these 2 functions that way this information can be queried
457
+ # with a call to ray.get().
458
+ def observation_space(self):
459
+ return self.env.observation_space
460
+
461
+ def action_space(self):
462
+ return self.env.action_space
vllm/lib/python3.10/site-packages/ray/rllib/env/utils/__init__.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Type, Union
3
+
4
+ import gymnasium as gym
5
+
6
+ from ray.rllib.env.env_context import EnvContext
7
+ from ray.rllib.utils.error import (
8
+ ERR_MSG_INVALID_ENV_DESCRIPTOR,
9
+ EnvError,
10
+ )
11
+ from ray.util.annotations import PublicAPI
12
+
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ @PublicAPI
18
+ def try_import_pyspiel(error: bool = False):
19
+ """Tries importing pyspiel and returns the module (or None).
20
+
21
+ Args:
22
+ error: Whether to raise an error if pyspiel cannot be imported.
23
+
24
+ Returns:
25
+ The pyspiel module.
26
+
27
+ Raises:
28
+ ImportError: If error=True and pyspiel is not installed.
29
+ """
30
+ try:
31
+ import pyspiel
32
+
33
+ return pyspiel
34
+ except ImportError:
35
+ if error:
36
+ raise ImportError(
37
+ "Could not import pyspiel! Pygame is not a dependency of RLlib "
38
+ "and RLlib requires you to install pygame separately: "
39
+ "`pip install pygame`."
40
+ )
41
+ return None
42
+
43
+
44
+ @PublicAPI
45
+ def try_import_open_spiel(error: bool = False):
46
+ """Tries importing open_spiel and returns the module (or None).
47
+
48
+ Args:
49
+ error: Whether to raise an error if open_spiel cannot be imported.
50
+
51
+ Returns:
52
+ The open_spiel module.
53
+
54
+ Raises:
55
+ ImportError: If error=True and open_spiel is not installed.
56
+ """
57
+ try:
58
+ import open_spiel
59
+
60
+ return open_spiel
61
+ except ImportError:
62
+ if error:
63
+ raise ImportError(
64
+ "Could not import open_spiel! open_spiel is not a dependency of RLlib "
65
+ "and RLlib requires you to install open_spiel separately: "
66
+ "`pip install open_spiel`."
67
+ )
68
+ return None
69
+
70
+
71
+ def _gym_env_creator(
72
+ env_context: EnvContext,
73
+ env_descriptor: Union[str, Type[gym.Env]],
74
+ ) -> gym.Env:
75
+ """Tries to create a gym env given an EnvContext object and descriptor.
76
+
77
+ Note: This function tries to construct the env from a string descriptor
78
+ only using possibly installed RL env packages (such as gym, pybullet_envs,
79
+ etc). These packages are no installation requirements for RLlib. In case
80
+ you would like to support more such env packages, add the necessary imports
81
+ and construction logic below.
82
+
83
+ Args:
84
+ env_context: The env context object to configure the env.
85
+ Note that this is a config dict, plus the properties:
86
+ `worker_index`, `vector_index`, and `remote`.
87
+ env_descriptor: The env descriptor as a gym-registered string, e.g. CartPole-v1,
88
+ ALE/MsPacman-v5, or CartPoleContinuousBulletEnv-v0.
89
+ Alternatively, the gym.Env subclass to use.
90
+
91
+ Returns:
92
+ The actual gym environment object.
93
+
94
+ Raises:
95
+ gym.error.Error: If the env cannot be constructed.
96
+ """
97
+ # Allow for PyBullet or envs to be used as well (via string). This allows
98
+ # for doing things like `env=CartPoleContinuousBulletEnv-v0`.
99
+ try:
100
+ import pybullet_envs
101
+
102
+ pybullet_envs.getList()
103
+ except (AttributeError, ModuleNotFoundError, ImportError):
104
+ pass
105
+
106
+ # If env descriptor is a str, starting with "ale_py:ALE/", for now, register all ALE
107
+ # envs from ale_py.
108
+ if isinstance(env_descriptor, str) and env_descriptor.startswith("ale_py:ALE/"):
109
+ import ale_py
110
+
111
+ gym.register_envs(ale_py)
112
+
113
+ # Try creating a gym env. If this fails we can output a
114
+ # decent error message.
115
+ try:
116
+ # If class provided, call constructor directly.
117
+ if isinstance(env_descriptor, type):
118
+ env = env_descriptor(env_context)
119
+ else:
120
+ env = gym.make(env_descriptor, **env_context)
121
+ except gym.error.Error:
122
+ raise EnvError(ERR_MSG_INVALID_ENV_DESCRIPTOR.format(env_descriptor))
123
+
124
+ return env
vllm/lib/python3.10/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py ADDED
@@ -0,0 +1,707 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Union
2
+
3
+ import gymnasium as gym
4
+ import numpy as np
5
+ import tree # pip install dm_tree
6
+
7
+ from ray.rllib.utils.numpy import LARGE_INTEGER, one_hot, one_hot_multidiscrete
8
+ from ray.rllib.utils.serialization import gym_space_from_dict, gym_space_to_dict
9
+ from ray.rllib.utils.spaces.space_utils import (
10
+ batch,
11
+ from_jsonable_if_needed,
12
+ get_dummy_batch_for_space,
13
+ get_base_struct_from_space,
14
+ to_jsonable_if_needed,
15
+ )
16
+
17
+
18
+ class InfiniteLookbackBuffer:
19
+ @property
20
+ def space(self):
21
+ return self._space
22
+
23
+ @space.setter
24
+ def space(self, value):
25
+ self._space = value
26
+ self.space_struct = get_base_struct_from_space(value)
27
+
28
+ def __init__(
29
+ self,
30
+ data: Optional[Union[List, np.ndarray]] = None,
31
+ lookback: int = 0,
32
+ space: Optional[gym.Space] = None,
33
+ ):
34
+ self.data = data if data is not None else []
35
+ self.lookback = min(lookback, len(self.data))
36
+ self.finalized = not isinstance(self.data, list)
37
+ self.space_struct = None
38
+ self.space = space
39
+
40
+ def __eq__(
41
+ self,
42
+ other: "InfiniteLookbackBuffer",
43
+ ) -> bool:
44
+ """Compares two `InfiniteLookbackBuffers.
45
+
46
+ Args:
47
+ other: Another object. If another `LookbackBuffer` instance all
48
+ their attributes are compared.
49
+
50
+ Returns:
51
+ `True`, if `other` is an `InfiniteLookbackBuffer` instance and all
52
+ attributes are identical. Otherwise, returns `False`.
53
+ """
54
+ if isinstance(other, InfiniteLookbackBuffer):
55
+ if (
56
+ self.data == other.data
57
+ and self.lookback == other.lookback
58
+ and self.finalized == other.finalized
59
+ and self.space_struct == other.space_struct
60
+ and self.space == other.space
61
+ ):
62
+ return True
63
+ return False
64
+
65
+ def get_state(self) -> Dict[str, Any]:
66
+ """Returns the pickable state of a buffer.
67
+
68
+ The data in the buffer is stored into a dictionary. Note that
69
+ buffers can also be generated from pickable states (see
70
+ `InfiniteLookbackBuffer.from_state`)
71
+
72
+ Returns:
73
+ A dict containing all the data and metadata from the buffer.
74
+ """
75
+ return {
76
+ "data": to_jsonable_if_needed(self.data, self.space)
77
+ if self.space
78
+ else self.data,
79
+ "lookback": self.lookback,
80
+ "finalized": self.finalized,
81
+ "space": gym_space_to_dict(self.space) if self.space else self.space,
82
+ }
83
+
84
+ @staticmethod
85
+ def from_state(state: Dict[str, Any]) -> None:
86
+ """Creates a new `InfiniteLookbackBuffer` from a state dict.
87
+
88
+ Args:
89
+ state: The state dict, as returned by `self.get_state`.
90
+
91
+ Returns:
92
+ A new `InfiniteLookbackBuffer` instance with the data and metadata
93
+ from the state dict.
94
+ """
95
+ buffer = InfiniteLookbackBuffer()
96
+ buffer.lookback = state["lookback"]
97
+ buffer.finalized = state["finalized"]
98
+ buffer.space = gym_space_from_dict(state["space"]) if state["space"] else None
99
+ buffer.space_struct = (
100
+ get_base_struct_from_space(buffer.space) if buffer.space else None
101
+ )
102
+ buffer.data = (
103
+ from_jsonable_if_needed(state["data"], buffer.space)
104
+ if buffer.space
105
+ else state["data"]
106
+ )
107
+
108
+ return buffer
109
+
110
+ def append(self, item) -> None:
111
+ """Appends the given item to the end of this buffer."""
112
+ if self.finalized:
113
+ self.data = tree.map_structure(
114
+ lambda d, i: np.concatenate([d, [i]], axis=0), self.data, item
115
+ )
116
+ else:
117
+ self.data.append(item)
118
+
119
+ def extend(self, items) -> None:
120
+ """Appends all items in `items` to the end of this buffer."""
121
+ if self.finalized:
122
+ # TODO (sven): When extending with a list of structs, we should
123
+ # probably rather do: `tree.map_structure(..., self.data,
124
+ # tree.map_structure(lambda *s: np.array(*s), *items)`)??
125
+ self.data = tree.map_structure(
126
+ lambda d, i: np.concatenate([d, i], axis=0), self.data, np.array(items)
127
+ )
128
+ else:
129
+ for item in items:
130
+ self.append(item)
131
+
132
+ def concat(self, other: "InfiniteLookbackBuffer") -> None:
133
+ """Concatenates the data of `other` (w/o its lookback) to `self`.
134
+
135
+ Args:
136
+ other: The other InfiniteLookbackBuffer to be concatenated to self.
137
+ """
138
+ self.data.extend(other.get())
139
+
140
+ def pop(self, index: int = -1) -> None:
141
+ """Removes the item at `index` from this buffer, but does NOT return it.
142
+
143
+ Args:
144
+ index: The index to pop out of this buffer (w/o returning it from this
145
+ method).
146
+ """
147
+ if self.finalized:
148
+ self.data = tree.map_structure(
149
+ lambda s: np.delete(s, index, axis=0), self.data
150
+ )
151
+ else:
152
+ self.data.pop(index)
153
+
154
+ def finalize(self) -> None:
155
+ """Finalizes this buffer by converting internal data lists into numpy arrays.
156
+
157
+ Thereby, if the individual items in the list are nested structures, the
158
+ resulting buffer content will be a nested struct of np.ndarrays (leafs).
159
+ """
160
+ if not self.finalized:
161
+ self.data = batch(self.data)
162
+ self.finalized = True
163
+
164
+ def get(
165
+ self,
166
+ indices: Optional[Union[int, slice, List[int]]] = None,
167
+ *,
168
+ neg_index_as_lookback: bool = False,
169
+ fill: Optional[Any] = None,
170
+ one_hot_discrete: bool = False,
171
+ _ignore_last_ts: bool = False,
172
+ _add_last_ts_value: Optional[Any] = None,
173
+ ) -> Any:
174
+ """Returns data, based on the given args, from this buffer.
175
+
176
+ Args:
177
+ indices: A single int is interpreted as an index, from which to return the
178
+ individual data stored at this index.
179
+ A list of ints is interpreted as a list of indices from which to gather
180
+ individual data in a batch of size len(indices).
181
+ A slice object is interpreted as a range of data to be returned.
182
+ Thereby, negative indices by default are interpreted as "before the end"
183
+ unless the `neg_index_as_lookback=True` option is used, in which case
184
+ negative indices are interpreted as "before ts=0", meaning going back
185
+ into the lookback buffer.
186
+ neg_index_as_lookback: If True, negative values in `indices` are
187
+ interpreted as "before ts=0", meaning going back into the lookback
188
+ buffer. For example, a buffer with data [4, 5, 6, 7, 8, 9],
189
+ where [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will
190
+ respond to `get(-1, neg_index_as_lookback=True)` with `6` and to
191
+ `get(slice(-2, 1), neg_index_as_lookback=True)` with `[5, 6, 7]`.
192
+ fill: An optional float value to use for filling up the returned results at
193
+ the boundaries. This filling only happens if the requested index range's
194
+ start/stop boundaries exceed the buffer's boundaries (including the
195
+ lookback buffer on the left side). This comes in very handy, if users
196
+ don't want to worry about reaching such boundaries and want to zero-pad.
197
+ For example, a buffer with data [10, 11, 12, 13, 14] and lookback
198
+ buffer size of 2 (meaning `10` and `11` are part of the lookback buffer)
199
+ will respond to `get(slice(-7, -2), fill=0.0)`
200
+ with `[0.0, 0.0, 10, 11, 12]`.
201
+ one_hot_discrete: If True, will return one-hot vectors (instead of
202
+ int-values) for those sub-components of a (possibly complex) space
203
+ that are Discrete or MultiDiscrete. Note that if `fill=0` and the
204
+ requested `indices` are out of the range of our data, the returned
205
+ one-hot vectors will actually be zero-hot (all slots zero).
206
+ _ignore_last_ts: Whether to ignore the last record in our internal
207
+ `self.data` when getting the provided indices.
208
+ _add_last_ts_value: Whether to add the value of this arg to the end of
209
+ the internal `self.data` buffer (just for the duration of this get
210
+ operation, not permanently).
211
+ """
212
+ if indices is None:
213
+ data = self._get_all_data(
214
+ one_hot_discrete=one_hot_discrete,
215
+ _ignore_last_ts=_ignore_last_ts,
216
+ )
217
+ elif isinstance(indices, slice):
218
+ data = self._get_slice(
219
+ indices,
220
+ fill=fill,
221
+ neg_index_as_lookback=neg_index_as_lookback,
222
+ one_hot_discrete=one_hot_discrete,
223
+ _ignore_last_ts=_ignore_last_ts,
224
+ _add_last_ts_value=_add_last_ts_value,
225
+ )
226
+ elif isinstance(indices, list):
227
+ data = [
228
+ self._get_int_index(
229
+ idx,
230
+ fill=fill,
231
+ neg_index_as_lookback=neg_index_as_lookback,
232
+ one_hot_discrete=one_hot_discrete,
233
+ _ignore_last_ts=_ignore_last_ts,
234
+ _add_last_ts_value=_add_last_ts_value,
235
+ )
236
+ for idx in indices
237
+ ]
238
+ if self.finalized:
239
+ data = batch(data)
240
+ else:
241
+ assert isinstance(indices, int)
242
+ data = self._get_int_index(
243
+ indices,
244
+ fill=fill,
245
+ neg_index_as_lookback=neg_index_as_lookback,
246
+ one_hot_discrete=one_hot_discrete,
247
+ _ignore_last_ts=_ignore_last_ts,
248
+ _add_last_ts_value=_add_last_ts_value,
249
+ )
250
+
251
+ return data
252
+
253
+ def __add__(
254
+ self, other: Union[List, "InfiniteLookbackBuffer", int, float, complex]
255
+ ) -> "InfiniteLookbackBuffer":
256
+ """Adds another InfiniteLookbackBuffer object or list to the end of this one.
257
+
258
+ Args:
259
+ other: Another `InfiniteLookbackBuffer` or a `list` or a number.
260
+ If a `InfiniteLookbackBuffer` its data (w/o its lookback buffer) gets
261
+ concatenated to self's data. If a `list`, we concat it to self's data.
262
+ If a number, we add this number to each element of self (if possible).
263
+
264
+ Returns:
265
+ A new `InfiniteLookbackBuffer` instance `self.data` containing
266
+ concatenated data from `self` and `other` (or adding `other` to each element
267
+ in self's data).
268
+ """
269
+
270
+ if self.finalized:
271
+ raise RuntimeError(f"Cannot `add` to a finalized {type(self).__name__}.")
272
+ else:
273
+ # If `other` is an int, simply add it to all our values (if possible) and
274
+ # use the result as the underlying data for the returned buffer.
275
+ if isinstance(other, (int, float, complex)):
276
+ data = [
277
+ (d + other) if isinstance(d, (int, float, complex)) else d
278
+ for d in self.data
279
+ ]
280
+ # If `other` is a InfiniteLookbackBuffer itself, do NOT include its
281
+ # lookback buffer anymore. We assume that `other`'s lookback buffer i
282
+ # already at the end of `self`.
283
+ elif isinstance(other, InfiniteLookbackBuffer):
284
+ data = self.data + other.data[other.lookback :]
285
+ # `other` is a list, simply concat the two lists and use the result as
286
+ # the underlying data for the returned buffer.
287
+ else:
288
+ data = self.data + other
289
+
290
+ return InfiniteLookbackBuffer(
291
+ data=data,
292
+ lookback=self.lookback,
293
+ space=self.space,
294
+ )
295
+
296
+ def __getitem__(self, item):
297
+ """Support squared bracket syntax, e.g. buffer[:5]."""
298
+ return self.get(item)
299
+
300
+ def __setitem__(self, key, value):
301
+ self.set(new_data=value, at_indices=key)
302
+
303
+ def set(
304
+ self,
305
+ new_data,
306
+ *,
307
+ at_indices: Optional[Union[int, slice, List[int]]] = None,
308
+ neg_index_as_lookback: bool = False,
309
+ ) -> None:
310
+ """Overwrites all or some of the data in this buffer with the provided data.
311
+
312
+ Args:
313
+ new_data: The new data to overwrite existing records with.
314
+ at_indices: A single int is interpreted as an index, at which to overwrite
315
+ the individual record stored at this index with `new_data`.
316
+ A list of ints is interpreted as a list of indices, which to overwrite
317
+ with `new_data`, which must be a batch of size `len(at_indices)`.
318
+ A slice object is interpreted as a range, which to overwrite with
319
+ `new_data`. Thereby, negative indices by default are interpreted as
320
+ "before the end" unless the `neg_index_as_lookback=True` option is
321
+ used, in which case negative indices are interpreted as
322
+ "before ts=0", meaning going back into the lookback buffer.
323
+ neg_index_as_lookback: If True, negative values in `at_indices` are
324
+ interpreted as "before ts=0", meaning going back into the lookback
325
+ buffer. For example, a buffer with data [4, 5, 6, 7, 8, 9],
326
+ where [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will
327
+ handle a call `set(99, at_indices=-1, neg_index_as_lookback=True)`
328
+ with `6` being replaced by 99 and to `set([98, 99, 100],
329
+ at_indices=slice(-2, 1), neg_index_as_lookback=True)` with
330
+ `[5, 6, 7]` being replaced by `[98, 99, 100]`.
331
+ """
332
+ # `at_indices` is None -> Override all our data (excluding the lookback buffer).
333
+ if at_indices is None:
334
+ self._set_all_data(new_data)
335
+
336
+ elif isinstance(at_indices, slice):
337
+ self._set_slice(
338
+ new_data,
339
+ slice_=at_indices,
340
+ neg_index_as_lookback=neg_index_as_lookback,
341
+ )
342
+ elif isinstance(at_indices, list):
343
+ for i, idx in enumerate(at_indices):
344
+ self._set_int_index(
345
+ new_data[i],
346
+ idx=idx,
347
+ neg_index_as_lookback=neg_index_as_lookback,
348
+ )
349
+ else:
350
+ assert isinstance(at_indices, int)
351
+ self._set_int_index(
352
+ new_data,
353
+ idx=at_indices,
354
+ neg_index_as_lookback=neg_index_as_lookback,
355
+ )
356
+
357
+ def __len__(self):
358
+ """Return the length of our data, excluding the lookback buffer."""
359
+ len_ = self.len_incl_lookback()
360
+ # Only count the data after the lookback.
361
+ return max(len_ - self.lookback, 0)
362
+
363
+ def len_incl_lookback(self):
364
+ if self.finalized:
365
+ return len(tree.flatten(self.data)[0])
366
+ else:
367
+ return len(self.data)
368
+
369
+ def __repr__(self):
370
+ return (
371
+ f"{type(self).__name__}({self.data[:self.lookback]} <- "
372
+ f"lookback({self.lookback}) | {self.data[self.lookback:]})"
373
+ )
374
+
375
+ def _get_all_data(self, one_hot_discrete=False, _ignore_last_ts=False):
376
+ data = self[: (None if not _ignore_last_ts else -1)]
377
+ if one_hot_discrete:
378
+ data = self._one_hot(data, space_struct=self.space_struct)
379
+ return data
380
+
381
+ def _set_all_data(self, new_data):
382
+ self._set_slice(new_data, slice(0, None))
383
+
384
+ def _get_slice(
385
+ self,
386
+ slice_,
387
+ fill=None,
388
+ neg_index_as_lookback=False,
389
+ one_hot_discrete=False,
390
+ _ignore_last_ts=False,
391
+ _add_last_ts_value=None,
392
+ ):
393
+ data_to_use = self.data
394
+ if _ignore_last_ts:
395
+ if self.finalized:
396
+ data_to_use = tree.map_structure(lambda s: s[:-1], self.data)
397
+ else:
398
+ data_to_use = self.data[:-1]
399
+ if _add_last_ts_value is not None:
400
+ if self.finalized:
401
+ data_to_use = tree.map_structure(
402
+ lambda s, t: np.append(s, t),
403
+ data_to_use.copy(),
404
+ _add_last_ts_value,
405
+ )
406
+ else:
407
+ data_to_use = np.append(data_to_use.copy(), _add_last_ts_value)
408
+
409
+ slice_, slice_len, fill_left_count, fill_right_count = self._interpret_slice(
410
+ slice_,
411
+ neg_index_as_lookback,
412
+ len_self_plus_lookback=(
413
+ self.len_incl_lookback()
414
+ + int(_add_last_ts_value is not None)
415
+ - int(_ignore_last_ts)
416
+ ),
417
+ )
418
+
419
+ # Perform the actual slice.
420
+ data_slice = None
421
+ if slice_len > 0:
422
+ if self.finalized:
423
+ data_slice = tree.map_structure(lambda s: s[slice_], data_to_use)
424
+ else:
425
+ data_slice = data_to_use[slice_]
426
+
427
+ if one_hot_discrete:
428
+ data_slice = self._one_hot(data_slice, space_struct=self.space_struct)
429
+
430
+ # Data is shorter than the range requested -> Fill the rest with `fill` data.
431
+ if fill is not None and (fill_right_count > 0 or fill_left_count > 0):
432
+ if self.finalized:
433
+ if fill_left_count:
434
+ if self.space is None:
435
+ fill_batch = np.array([fill] * fill_left_count)
436
+ else:
437
+ fill_batch = get_dummy_batch_for_space(
438
+ self.space,
439
+ fill_value=fill,
440
+ batch_size=fill_left_count,
441
+ one_hot_discrete=one_hot_discrete,
442
+ )
443
+ if data_slice is not None:
444
+ data_slice = tree.map_structure(
445
+ lambda s0, s: np.concatenate([s0, s]),
446
+ fill_batch,
447
+ data_slice,
448
+ )
449
+ else:
450
+ data_slice = fill_batch
451
+ if fill_right_count:
452
+ if self.space is None:
453
+ fill_batch = np.array([fill] * fill_right_count)
454
+ else:
455
+ fill_batch = get_dummy_batch_for_space(
456
+ self.space,
457
+ fill_value=fill,
458
+ batch_size=fill_right_count,
459
+ one_hot_discrete=one_hot_discrete,
460
+ )
461
+ if data_slice is not None:
462
+ data_slice = tree.map_structure(
463
+ lambda s0, s: np.concatenate([s, s0]),
464
+ fill_batch,
465
+ data_slice,
466
+ )
467
+ else:
468
+ data_slice = fill_batch
469
+
470
+ else:
471
+ if self.space is None:
472
+ fill_batch = [fill]
473
+ else:
474
+ fill_batch = [
475
+ get_dummy_batch_for_space(
476
+ self.space,
477
+ fill_value=fill,
478
+ batch_size=0,
479
+ one_hot_discrete=one_hot_discrete,
480
+ )
481
+ ]
482
+ data_slice = (
483
+ fill_batch * fill_left_count
484
+ + (data_slice if data_slice is not None else [])
485
+ + fill_batch * fill_right_count
486
+ )
487
+
488
+ if data_slice is None:
489
+ if self.finalized:
490
+ return tree.map_structure(lambda s: s[slice_], data_to_use)
491
+ else:
492
+ return data_to_use[slice_]
493
+ return data_slice
494
+
495
+ def _set_slice(
496
+ self,
497
+ new_data,
498
+ slice_,
499
+ neg_index_as_lookback=False,
500
+ ):
501
+ slice_, _, _, _ = self._interpret_slice(slice_, neg_index_as_lookback)
502
+
503
+ # Check, whether the setting to new_data changes the length of self
504
+ # (it shouldn't). If it does, raise an error.
505
+ try:
506
+ if self.finalized:
507
+
508
+ def __set(s, n):
509
+ if self.space:
510
+ assert self.space.contains(n[0])
511
+ assert len(s[slice_]) == len(n)
512
+ s[slice_] = n
513
+
514
+ tree.map_structure(__set, self.data, new_data)
515
+ else:
516
+ assert len(self.data[slice_]) == len(new_data)
517
+ self.data[slice_] = new_data
518
+ except AssertionError:
519
+ raise IndexError(
520
+ f"Cannot `set()` value via at_indices={slice_} (option "
521
+ f"neg_index_as_lookback={neg_index_as_lookback})! Slice of data "
522
+ "does NOT have the same size as `new_data`."
523
+ )
524
+
525
+ def _get_int_index(
526
+ self,
527
+ idx: int,
528
+ fill=None,
529
+ neg_index_as_lookback=False,
530
+ one_hot_discrete=False,
531
+ _ignore_last_ts=False,
532
+ _add_last_ts_value=None,
533
+ ):
534
+ data_to_use = self.data
535
+ if _ignore_last_ts:
536
+ data_to_use = self.data[:-1]
537
+ if _add_last_ts_value is not None:
538
+ data_to_use = np.append(data_to_use.copy(), _add_last_ts_value)
539
+
540
+ # If index >= 0 -> Ignore lookback buffer.
541
+ # Otherwise, include lookback buffer.
542
+ if idx >= 0 or neg_index_as_lookback:
543
+ idx = self.lookback + idx
544
+ # Negative indices mean: Go to left into lookback buffer starting from idx=0.
545
+ # But if we pass the lookback buffer, the index should be invalid and we will
546
+ # have to fill, if required. Invalidate the index by setting it to one larger
547
+ # than max.
548
+ if neg_index_as_lookback and idx < 0:
549
+ idx = len(self) + self.lookback - (_ignore_last_ts is True)
550
+
551
+ try:
552
+ if self.finalized:
553
+ data = tree.map_structure(lambda s: s[idx], data_to_use)
554
+ else:
555
+ data = data_to_use[idx]
556
+ # Out of range index -> If `fill`, use a fill dummy (B=0), if not, error out.
557
+ except IndexError as e:
558
+ if fill is not None:
559
+ if self.space is None:
560
+ return fill
561
+ return get_dummy_batch_for_space(
562
+ self.space,
563
+ fill_value=fill,
564
+ batch_size=0,
565
+ one_hot_discrete=one_hot_discrete,
566
+ )
567
+ else:
568
+ raise e
569
+
570
+ # Convert discrete/multi-discrete components to one-hot vectors, if required.
571
+ if one_hot_discrete:
572
+ data = self._one_hot(data, self.space_struct)
573
+ return data
574
+
575
+ def _set_int_index(self, new_data, idx, neg_index_as_lookback):
576
+ actual_idx = idx
577
+ # If index >= 0 -> Ignore lookback buffer.
578
+ # Otherwise, include lookback buffer.
579
+ if actual_idx >= 0 or neg_index_as_lookback:
580
+ actual_idx = self.lookback + actual_idx
581
+ # Negative indices mean: Go to left into lookback buffer starting from idx=0.
582
+ # But if we pass the lookback buffer, the index should be invalid and we will
583
+ # have to fill, if required. Invalidate the index by setting it to one larger
584
+ # than max.
585
+ if neg_index_as_lookback and actual_idx < 0:
586
+ actual_idx = len(self) + self.lookback
587
+
588
+ try:
589
+ if self.finalized:
590
+
591
+ def __set(s, n):
592
+ if self.space:
593
+ assert self.space.contains(n), n
594
+ s[actual_idx] = n
595
+
596
+ tree.map_structure(__set, self.data, new_data)
597
+ else:
598
+ self.data[actual_idx] = new_data
599
+ except IndexError:
600
+ raise IndexError(
601
+ f"Cannot `set()` value at index {idx} (option "
602
+ f"neg_index_as_lookback={neg_index_as_lookback})! Out of range "
603
+ f"of buffer data."
604
+ )
605
+
606
+ def _interpret_slice(
607
+ self,
608
+ slice_,
609
+ neg_index_as_lookback,
610
+ len_self_plus_lookback=None,
611
+ ):
612
+ if len_self_plus_lookback is None:
613
+ len_self_plus_lookback = len(self) + self.lookback
614
+
615
+ # Re-interpret slice bounds as absolute positions (>=0) within our
616
+ # internal data.
617
+ start = slice_.start
618
+ stop = slice_.stop
619
+
620
+ # Start is None -> Exclude lookback buffer.
621
+ if start is None:
622
+ start = self.lookback
623
+ # Start is negative.
624
+ elif start < 0:
625
+ # `neg_index_as_lookback=True` -> User wants to index into the lookback
626
+ # range.
627
+ if neg_index_as_lookback:
628
+ start = self.lookback + start
629
+ # Interpret index as counting "from end".
630
+ else:
631
+ start = len_self_plus_lookback + start
632
+ # Start is 0 or positive -> timestep right after lookback is interpreted as 0.
633
+ else:
634
+ start = self.lookback + start
635
+
636
+ # Stop is None -> Set stop to very last index + 1 of our internal data.
637
+ if stop is None:
638
+ stop = len_self_plus_lookback
639
+ # Stop is negative.
640
+ elif stop < 0:
641
+ # `neg_index_as_lookback=True` -> User wants to index into the lookback
642
+ # range. Set to 0 (beginning of lookback buffer) if result is a negative
643
+ # index.
644
+ if neg_index_as_lookback:
645
+ stop = self.lookback + stop
646
+ # Interpret index as counting "from end". Set to 0 (beginning of actual
647
+ # episode) if result is a negative index.
648
+ else:
649
+ stop = len_self_plus_lookback + stop
650
+ # Stop is positive -> Add lookback range to it.
651
+ else:
652
+ stop = self.lookback + stop
653
+
654
+ fill_left_count = fill_right_count = 0
655
+ # Both start and stop are on left side.
656
+ if start < 0 and stop < 0:
657
+ fill_left_count = abs(start - stop)
658
+ fill_right_count = 0
659
+ start = stop = 0
660
+ # Both start and stop are on right side.
661
+ elif start >= len_self_plus_lookback and stop >= len_self_plus_lookback:
662
+ fill_right_count = abs(start - stop)
663
+ fill_left_count = 0
664
+ start = stop = len_self_plus_lookback
665
+ # Set to 0 (beginning of actual episode) if result is a negative index.
666
+ elif start < 0:
667
+ fill_left_count = -start
668
+ start = 0
669
+ elif stop >= len_self_plus_lookback:
670
+ fill_right_count = stop - len_self_plus_lookback
671
+ stop = len_self_plus_lookback
672
+ # Only `stop` might be < 0, when slice has negative step and start is > 0.
673
+ elif stop < 0:
674
+ if start >= len_self_plus_lookback:
675
+ fill_left_count = start - len_self_plus_lookback + 1
676
+ start = len_self_plus_lookback - 1
677
+ fill_right_count = -stop - 1
678
+ stop = -LARGE_INTEGER
679
+
680
+ assert start >= 0 and (stop >= 0 or stop == -LARGE_INTEGER), (start, stop)
681
+
682
+ step = slice_.step if slice_.step is not None else 1
683
+ slice_ = slice(start, stop, step)
684
+ slice_len = max(0, (stop - start + (step - (1 if step > 0 else -1))) // step)
685
+ return slice_, slice_len, fill_left_count, fill_right_count
686
+
687
+ def _one_hot(self, data, space_struct):
688
+ if space_struct is None:
689
+ raise ValueError(
690
+ f"Cannot `one_hot` data in `{type(self).__name__}` if a "
691
+ "gym.Space was NOT provided during construction!"
692
+ )
693
+
694
+ def _convert(dat_, space):
695
+ if isinstance(space, gym.spaces.Discrete):
696
+ return one_hot(dat_, depth=space.n)
697
+ elif isinstance(space, gym.spaces.MultiDiscrete):
698
+ return one_hot_multidiscrete(dat_, depths=space.nvec)
699
+ return dat_
700
+
701
+ if isinstance(data, list):
702
+ data = [
703
+ tree.map_structure(_convert, dslice, space_struct) for dslice in data
704
+ ]
705
+ else:
706
+ data = tree.map_structure(_convert, data, space_struct)
707
+ return data
vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (492 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/action_dist.cpython-310.pyc ADDED
Binary file (4.33 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/catalog.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/distributions.cpython-310.pyc ADDED
Binary file (8.96 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/modelv2.cpython-310.pyc ADDED
Binary file (14.9 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/preprocessors.cpython-310.pyc ADDED
Binary file (14.4 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/repeated_values.cpython-310.pyc ADDED
Binary file (7.15 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/__pycache__/utils.cpython-310.pyc ADDED
Binary file (6.51 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/preprocessors.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ import logging
3
+ import numpy as np
4
+ import gymnasium as gym
5
+ from typing import Any, List
6
+
7
+ from ray.rllib.utils.annotations import OldAPIStack, override
8
+ from ray.rllib.utils.spaces.repeated import Repeated
9
+ from ray.rllib.utils.typing import TensorType
10
+ from ray.rllib.utils.images import resize
11
+ from ray.rllib.utils.spaces.space_utils import convert_element_to_space_type
12
+
13
+ ATARI_OBS_SHAPE = (210, 160, 3)
14
+ ATARI_RAM_OBS_SHAPE = (128,)
15
+
16
+ # Only validate env observations vs the observation space every n times in a
17
+ # Preprocessor.
18
+ OBS_VALIDATION_INTERVAL = 100
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ @OldAPIStack
24
+ class Preprocessor:
25
+ """Defines an abstract observation preprocessor function.
26
+
27
+ Attributes:
28
+ shape (List[int]): Shape of the preprocessed output.
29
+ """
30
+
31
+ def __init__(self, obs_space: gym.Space, options: dict = None):
32
+ _legacy_patch_shapes(obs_space)
33
+ self._obs_space = obs_space
34
+ if not options:
35
+ from ray.rllib.models.catalog import MODEL_DEFAULTS
36
+
37
+ self._options = MODEL_DEFAULTS.copy()
38
+ else:
39
+ self._options = options
40
+ self.shape = self._init_shape(obs_space, self._options)
41
+ self._size = int(np.prod(self.shape))
42
+ self._i = 0
43
+ self._obs_for_type_matching = self._obs_space.sample()
44
+
45
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
46
+ """Returns the shape after preprocessing."""
47
+ raise NotImplementedError
48
+
49
+ def transform(self, observation: TensorType) -> np.ndarray:
50
+ """Returns the preprocessed observation."""
51
+ raise NotImplementedError
52
+
53
+ def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None:
54
+ """Alternative to transform for more efficient flattening."""
55
+ array[offset : offset + self._size] = self.transform(observation)
56
+
57
+ def check_shape(self, observation: Any) -> None:
58
+ """Checks the shape of the given observation."""
59
+ if self._i % OBS_VALIDATION_INTERVAL == 0:
60
+ # Convert lists to np.ndarrays.
61
+ if type(observation) is list and isinstance(
62
+ self._obs_space, gym.spaces.Box
63
+ ):
64
+ observation = np.array(observation).astype(np.float32)
65
+ if not self._obs_space.contains(observation):
66
+ observation = convert_element_to_space_type(
67
+ observation, self._obs_for_type_matching
68
+ )
69
+ try:
70
+ if not self._obs_space.contains(observation):
71
+ raise ValueError(
72
+ "Observation ({} dtype={}) outside given space ({})!".format(
73
+ observation,
74
+ observation.dtype
75
+ if isinstance(self._obs_space, gym.spaces.Box)
76
+ else None,
77
+ self._obs_space,
78
+ )
79
+ )
80
+ except AttributeError as e:
81
+ raise ValueError(
82
+ "Observation for a Box/MultiBinary/MultiDiscrete space "
83
+ "should be an np.array, not a Python list.",
84
+ observation,
85
+ ) from e
86
+ self._i += 1
87
+
88
+ @property
89
+ def size(self) -> int:
90
+ return self._size
91
+
92
+ @property
93
+ def observation_space(self) -> gym.Space:
94
+ obs_space = gym.spaces.Box(-1.0, 1.0, self.shape, dtype=np.float32)
95
+ # Stash the unwrapped space so that we can unwrap dict and tuple spaces
96
+ # automatically in modelv2.py
97
+ classes = (
98
+ DictFlatteningPreprocessor,
99
+ OneHotPreprocessor,
100
+ RepeatedValuesPreprocessor,
101
+ TupleFlatteningPreprocessor,
102
+ AtariRamPreprocessor,
103
+ GenericPixelPreprocessor,
104
+ )
105
+ if isinstance(self, classes):
106
+ obs_space.original_space = self._obs_space
107
+ return obs_space
108
+
109
+
110
+ @OldAPIStack
111
+ class GenericPixelPreprocessor(Preprocessor):
112
+ """Generic image preprocessor.
113
+
114
+ Note: for Atari games, use config {"preprocessor_pref": "deepmind"}
115
+ instead for deepmind-style Atari preprocessing.
116
+ """
117
+
118
+ @override(Preprocessor)
119
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
120
+ self._grayscale = options.get("grayscale")
121
+ self._zero_mean = options.get("zero_mean")
122
+ self._dim = options.get("dim")
123
+ if self._grayscale:
124
+ shape = (self._dim, self._dim, 1)
125
+ else:
126
+ shape = (self._dim, self._dim, 3)
127
+
128
+ return shape
129
+
130
+ @override(Preprocessor)
131
+ def transform(self, observation: TensorType) -> np.ndarray:
132
+ """Downsamples images from (210, 160, 3) by the configured factor."""
133
+ self.check_shape(observation)
134
+ scaled = observation[25:-25, :, :]
135
+ if self._dim < 84:
136
+ scaled = resize(scaled, height=84, width=84)
137
+ # OpenAI: Resize by half, then down to 42x42 (essentially mipmapping).
138
+ # If we resize directly we lose pixels that, when mapped to 42x42,
139
+ # aren't close enough to the pixel boundary.
140
+ scaled = resize(scaled, height=self._dim, width=self._dim)
141
+ if self._grayscale:
142
+ scaled = scaled.mean(2)
143
+ scaled = scaled.astype(np.float32)
144
+ # Rescale needed for maintaining 1 channel
145
+ scaled = np.reshape(scaled, [self._dim, self._dim, 1])
146
+ if self._zero_mean:
147
+ scaled = (scaled - 128) / 128
148
+ else:
149
+ scaled *= 1.0 / 255.0
150
+ return scaled
151
+
152
+
153
+ @OldAPIStack
154
+ class AtariRamPreprocessor(Preprocessor):
155
+ @override(Preprocessor)
156
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
157
+ return (128,)
158
+
159
+ @override(Preprocessor)
160
+ def transform(self, observation: TensorType) -> np.ndarray:
161
+ self.check_shape(observation)
162
+ return (observation.astype("float32") - 128) / 128
163
+
164
+
165
+ @OldAPIStack
166
+ class OneHotPreprocessor(Preprocessor):
167
+ """One-hot preprocessor for Discrete and MultiDiscrete spaces.
168
+
169
+ .. testcode::
170
+ :skipif: True
171
+
172
+ self.transform(Discrete(3).sample())
173
+
174
+ .. testoutput::
175
+
176
+ np.array([0.0, 1.0, 0.0])
177
+
178
+ .. testcode::
179
+ :skipif: True
180
+
181
+ self.transform(MultiDiscrete([2, 3]).sample())
182
+
183
+ .. testoutput::
184
+
185
+ np.array([0.0, 1.0, 0.0, 0.0, 1.0])
186
+ """
187
+
188
+ @override(Preprocessor)
189
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
190
+ if isinstance(obs_space, gym.spaces.Discrete):
191
+ return (self._obs_space.n,)
192
+ else:
193
+ return (np.sum(self._obs_space.nvec),)
194
+
195
+ @override(Preprocessor)
196
+ def transform(self, observation: TensorType) -> np.ndarray:
197
+ self.check_shape(observation)
198
+ return gym.spaces.utils.flatten(self._obs_space, observation).astype(np.float32)
199
+
200
+ @override(Preprocessor)
201
+ def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None:
202
+ array[offset : offset + self.size] = self.transform(observation)
203
+
204
+
205
+ @OldAPIStack
206
+ class NoPreprocessor(Preprocessor):
207
+ @override(Preprocessor)
208
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
209
+ return self._obs_space.shape
210
+
211
+ @override(Preprocessor)
212
+ def transform(self, observation: TensorType) -> np.ndarray:
213
+ self.check_shape(observation)
214
+ return observation
215
+
216
+ @override(Preprocessor)
217
+ def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None:
218
+ array[offset : offset + self._size] = np.array(observation, copy=False).ravel()
219
+
220
+ @property
221
+ @override(Preprocessor)
222
+ def observation_space(self) -> gym.Space:
223
+ return self._obs_space
224
+
225
+
226
+ @OldAPIStack
227
+ class MultiBinaryPreprocessor(Preprocessor):
228
+ """Preprocessor that turns a MultiBinary space into a Box.
229
+
230
+ Note: Before RLModules were introduced, RLlib's ModelCatalogV2 would produce
231
+ ComplexInputNetworks that treat MultiBinary spaces as Boxes. This preprocessor is
232
+ needed to get rid of the ComplexInputNetworks and use RLModules instead because
233
+ RLModules lack the logic to handle MultiBinary or other non-Box spaces.
234
+ """
235
+
236
+ @override(Preprocessor)
237
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
238
+ return self._obs_space.shape
239
+
240
+ @override(Preprocessor)
241
+ def transform(self, observation: TensorType) -> np.ndarray:
242
+ # The shape stays the same, but the dtype changes.
243
+ self.check_shape(observation)
244
+ return observation.astype(np.float32)
245
+
246
+ @override(Preprocessor)
247
+ def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None:
248
+ array[offset : offset + self._size] = np.array(observation, copy=False).ravel()
249
+
250
+ @property
251
+ @override(Preprocessor)
252
+ def observation_space(self) -> gym.Space:
253
+ obs_space = gym.spaces.Box(0.0, 1.0, self.shape, dtype=np.float32)
254
+ obs_space.original_space = self._obs_space
255
+ return obs_space
256
+
257
+
258
+ @OldAPIStack
259
+ class TupleFlatteningPreprocessor(Preprocessor):
260
+ """Preprocesses each tuple element, then flattens it all into a vector.
261
+
262
+ RLlib models will unpack the flattened output before _build_layers_v2().
263
+ """
264
+
265
+ @override(Preprocessor)
266
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
267
+ assert isinstance(self._obs_space, gym.spaces.Tuple)
268
+ size = 0
269
+ self.preprocessors = []
270
+ for i in range(len(self._obs_space.spaces)):
271
+ space = self._obs_space.spaces[i]
272
+ logger.debug("Creating sub-preprocessor for {}".format(space))
273
+ preprocessor_class = get_preprocessor(space)
274
+ if preprocessor_class is not None:
275
+ preprocessor = preprocessor_class(space, self._options)
276
+ size += preprocessor.size
277
+ else:
278
+ preprocessor = None
279
+ size += int(np.prod(space.shape))
280
+ self.preprocessors.append(preprocessor)
281
+ return (size,)
282
+
283
+ @override(Preprocessor)
284
+ def transform(self, observation: TensorType) -> np.ndarray:
285
+ self.check_shape(observation)
286
+ array = np.zeros(self.shape, dtype=np.float32)
287
+ self.write(observation, array, 0)
288
+ return array
289
+
290
+ @override(Preprocessor)
291
+ def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None:
292
+ assert len(observation) == len(self.preprocessors), observation
293
+ for o, p in zip(observation, self.preprocessors):
294
+ p.write(o, array, offset)
295
+ offset += p.size
296
+
297
+
298
+ @OldAPIStack
299
+ class DictFlatteningPreprocessor(Preprocessor):
300
+ """Preprocesses each dict value, then flattens it all into a vector.
301
+
302
+ RLlib models will unpack the flattened output before _build_layers_v2().
303
+ """
304
+
305
+ @override(Preprocessor)
306
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
307
+ assert isinstance(self._obs_space, gym.spaces.Dict)
308
+ size = 0
309
+ self.preprocessors = []
310
+ for space in self._obs_space.spaces.values():
311
+ logger.debug("Creating sub-preprocessor for {}".format(space))
312
+ preprocessor_class = get_preprocessor(space)
313
+ if preprocessor_class is not None:
314
+ preprocessor = preprocessor_class(space, self._options)
315
+ size += preprocessor.size
316
+ else:
317
+ preprocessor = None
318
+ size += int(np.prod(space.shape))
319
+ self.preprocessors.append(preprocessor)
320
+ return (size,)
321
+
322
+ @override(Preprocessor)
323
+ def transform(self, observation: TensorType) -> np.ndarray:
324
+ self.check_shape(observation)
325
+ array = np.zeros(self.shape, dtype=np.float32)
326
+ self.write(observation, array, 0)
327
+ return array
328
+
329
+ @override(Preprocessor)
330
+ def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None:
331
+ if not isinstance(observation, OrderedDict):
332
+ observation = OrderedDict(sorted(observation.items()))
333
+ assert len(observation) == len(self.preprocessors), (
334
+ len(observation),
335
+ len(self.preprocessors),
336
+ )
337
+ for o, p in zip(observation.values(), self.preprocessors):
338
+ p.write(o, array, offset)
339
+ offset += p.size
340
+
341
+
342
+ @OldAPIStack
343
+ class RepeatedValuesPreprocessor(Preprocessor):
344
+ """Pads and batches the variable-length list value."""
345
+
346
+ @override(Preprocessor)
347
+ def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]:
348
+ assert isinstance(self._obs_space, Repeated)
349
+ child_space = obs_space.child_space
350
+ self.child_preprocessor = get_preprocessor(child_space)(
351
+ child_space, self._options
352
+ )
353
+ # The first slot encodes the list length.
354
+ size = 1 + self.child_preprocessor.size * obs_space.max_len
355
+ return (size,)
356
+
357
+ @override(Preprocessor)
358
+ def transform(self, observation: TensorType) -> np.ndarray:
359
+ array = np.zeros(self.shape)
360
+ if isinstance(observation, list):
361
+ for elem in observation:
362
+ self.child_preprocessor.check_shape(elem)
363
+ else:
364
+ pass # ValueError will be raised in write() below.
365
+ self.write(observation, array, 0)
366
+ return array
367
+
368
+ @override(Preprocessor)
369
+ def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None:
370
+ if not isinstance(observation, (list, np.ndarray)):
371
+ raise ValueError(
372
+ "Input for {} must be list type, got {}".format(self, observation)
373
+ )
374
+ elif len(observation) > self._obs_space.max_len:
375
+ raise ValueError(
376
+ "Input {} exceeds max len of space {}".format(
377
+ observation, self._obs_space.max_len
378
+ )
379
+ )
380
+ # The first slot encodes the list length.
381
+ array[offset] = len(observation)
382
+ for i, elem in enumerate(observation):
383
+ offset_i = offset + 1 + i * self.child_preprocessor.size
384
+ self.child_preprocessor.write(elem, array, offset_i)
385
+
386
+
387
+ @OldAPIStack
388
+ def get_preprocessor(space: gym.Space, include_multi_binary=False) -> type:
389
+ """Returns an appropriate preprocessor class for the given space."""
390
+
391
+ _legacy_patch_shapes(space)
392
+ obs_shape = space.shape
393
+
394
+ if isinstance(space, (gym.spaces.Discrete, gym.spaces.MultiDiscrete)):
395
+ preprocessor = OneHotPreprocessor
396
+ elif obs_shape == ATARI_OBS_SHAPE:
397
+ logger.debug(
398
+ "Defaulting to RLlib's GenericPixelPreprocessor because input "
399
+ "space has the atari-typical shape {}. Turn this behaviour off by setting "
400
+ "`preprocessor_pref=None` or "
401
+ "`preprocessor_pref='deepmind'` or disabling the preprocessing API "
402
+ "altogether with `_disable_preprocessor_api=True`.".format(ATARI_OBS_SHAPE)
403
+ )
404
+ preprocessor = GenericPixelPreprocessor
405
+ elif obs_shape == ATARI_RAM_OBS_SHAPE:
406
+ logger.debug(
407
+ "Defaulting to RLlib's AtariRamPreprocessor because input "
408
+ "space has the atari-typical shape {}. Turn this behaviour off by setting "
409
+ "`preprocessor_pref=None` or "
410
+ "`preprocessor_pref='deepmind' or disabling the preprocessing API "
411
+ "altogether with `_disable_preprocessor_api=True`."
412
+ "`.".format(ATARI_OBS_SHAPE)
413
+ )
414
+ preprocessor = AtariRamPreprocessor
415
+ elif isinstance(space, gym.spaces.Tuple):
416
+ preprocessor = TupleFlatteningPreprocessor
417
+ elif isinstance(space, gym.spaces.Dict):
418
+ preprocessor = DictFlatteningPreprocessor
419
+ elif isinstance(space, Repeated):
420
+ preprocessor = RepeatedValuesPreprocessor
421
+ # We usually only want to include this when using RLModules
422
+ elif isinstance(space, gym.spaces.MultiBinary) and include_multi_binary:
423
+ preprocessor = MultiBinaryPreprocessor
424
+ else:
425
+ preprocessor = NoPreprocessor
426
+
427
+ return preprocessor
428
+
429
+
430
+ def _legacy_patch_shapes(space: gym.Space) -> List[int]:
431
+ """Assigns shapes to spaces that don't have shapes.
432
+
433
+ This is only needed for older gym versions that don't set shapes properly
434
+ for Tuple and Discrete spaces.
435
+ """
436
+
437
+ if not hasattr(space, "shape"):
438
+ if isinstance(space, gym.spaces.Discrete):
439
+ space.shape = ()
440
+ elif isinstance(space, gym.spaces.Tuple):
441
+ shapes = []
442
+ for s in space.spaces:
443
+ shape = _legacy_patch_shapes(s)
444
+ shapes.append(shape)
445
+ space.shape = tuple(shapes)
446
+
447
+ return space.shape
vllm/lib/python3.10/site-packages/ray/rllib/models/repeated_values.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+ from ray.rllib.utils.annotations import OldAPIStack
4
+ from ray.rllib.utils.typing import TensorType, TensorStructType
5
+
6
+
7
+ @OldAPIStack
8
+ class RepeatedValues:
9
+ """Represents a variable-length list of items from spaces.Repeated.
10
+
11
+ RepeatedValues are created when you use spaces.Repeated, and are
12
+ accessible as part of input_dict["obs"] in ModelV2 forward functions.
13
+
14
+ Example:
15
+ Suppose the gym space definition was:
16
+ Repeated(Repeated(Box(K), N), M)
17
+
18
+ Then in the model forward function, input_dict["obs"] is of type:
19
+ RepeatedValues(RepeatedValues(<Tensor shape=(B, M, N, K)>))
20
+
21
+ The tensor is accessible via:
22
+ input_dict["obs"].values.values
23
+
24
+ And the actual data lengths via:
25
+ # outer repetition, shape [B], range [0, M]
26
+ input_dict["obs"].lengths
27
+ -and-
28
+ # inner repetition, shape [B, M], range [0, N]
29
+ input_dict["obs"].values.lengths
30
+
31
+ Attributes:
32
+ values: The padded data tensor of shape [B, max_len, ..., sz],
33
+ where B is the batch dimension, max_len is the max length of this
34
+ list, followed by any number of sub list max lens, followed by the
35
+ actual data size.
36
+ lengths (List[int]): Tensor of shape [B, ...] that represents the
37
+ number of valid items in each list. When the list is nested within
38
+ other lists, there will be extra dimensions for the parent list
39
+ max lens.
40
+ max_len: The max number of items allowed in each list.
41
+
42
+ TODO(ekl): support conversion to tf.RaggedTensor.
43
+ """
44
+
45
+ def __init__(self, values: TensorType, lengths: List[int], max_len: int):
46
+ self.values = values
47
+ self.lengths = lengths
48
+ self.max_len = max_len
49
+ self._unbatched_repr = None
50
+
51
+ def unbatch_all(self) -> List[List[TensorType]]:
52
+ """Unbatch both the repeat and batch dimensions into Python lists.
53
+
54
+ This is only supported in PyTorch / TF eager mode.
55
+
56
+ This lets you view the data unbatched in its original form, but is
57
+ not efficient for processing.
58
+
59
+ .. testcode::
60
+ :skipif: True
61
+
62
+ batch = RepeatedValues(<Tensor shape=(B, N, K)>)
63
+ items = batch.unbatch_all()
64
+ print(len(items) == B)
65
+
66
+ .. testoutput::
67
+
68
+ True
69
+
70
+ .. testcode::
71
+ :skipif: True
72
+
73
+ print(max(len(x) for x in items) <= N)
74
+
75
+ .. testoutput::
76
+
77
+ True
78
+
79
+ .. testcode::
80
+ :skipif: True
81
+
82
+ print(items)
83
+
84
+ .. testoutput::
85
+
86
+ [[<Tensor_1 shape=(K)>, ..., <Tensor_N, shape=(K)>],
87
+ ...
88
+ [<Tensor_1 shape=(K)>, <Tensor_2 shape=(K)>],
89
+ ...
90
+ [<Tensor_1 shape=(K)>],
91
+ ...
92
+ [<Tensor_1 shape=(K)>, ..., <Tensor_N shape=(K)>]]
93
+ """
94
+
95
+ if self._unbatched_repr is None:
96
+ B = _get_batch_dim_helper(self.values)
97
+ if B is None:
98
+ raise ValueError(
99
+ "Cannot call unbatch_all() when batch_dim is unknown. "
100
+ "This is probably because you are using TF graph mode."
101
+ )
102
+ else:
103
+ B = int(B)
104
+ slices = self.unbatch_repeat_dim()
105
+ result = []
106
+ for i in range(B):
107
+ if hasattr(self.lengths[i], "item"):
108
+ dynamic_len = int(self.lengths[i].item())
109
+ else:
110
+ dynamic_len = int(self.lengths[i].numpy())
111
+ dynamic_slice = []
112
+ for j in range(dynamic_len):
113
+ dynamic_slice.append(_batch_index_helper(slices, i, j))
114
+ result.append(dynamic_slice)
115
+ self._unbatched_repr = result
116
+
117
+ return self._unbatched_repr
118
+
119
+ def unbatch_repeat_dim(self) -> List[TensorType]:
120
+ """Unbatches the repeat dimension (the one `max_len` in size).
121
+
122
+ This removes the repeat dimension. The result will be a Python list of
123
+ with length `self.max_len`. Note that the data is still padded.
124
+
125
+ .. testcode::
126
+ :skipif: True
127
+
128
+ batch = RepeatedValues(<Tensor shape=(B, N, K)>)
129
+ items = batch.unbatch()
130
+ len(items) == batch.max_len
131
+
132
+ .. testoutput::
133
+
134
+ True
135
+
136
+ .. testcode::
137
+ :skipif: True
138
+
139
+ print(items)
140
+
141
+ .. testoutput::
142
+
143
+ [<Tensor_1 shape=(B, K)>, ..., <Tensor_N shape=(B, K)>]
144
+ """
145
+ return _unbatch_helper(self.values, self.max_len)
146
+
147
+ def __repr__(self):
148
+ return "RepeatedValues(value={}, lengths={}, max_len={})".format(
149
+ repr(self.values), repr(self.lengths), self.max_len
150
+ )
151
+
152
+ def __str__(self):
153
+ return repr(self)
154
+
155
+
156
+ def _get_batch_dim_helper(v: TensorStructType) -> int:
157
+ """Tries to find the batch dimension size of v, or None."""
158
+ if isinstance(v, dict):
159
+ for u in v.values():
160
+ return _get_batch_dim_helper(u)
161
+ elif isinstance(v, tuple):
162
+ return _get_batch_dim_helper(v[0])
163
+ elif isinstance(v, RepeatedValues):
164
+ return _get_batch_dim_helper(v.values)
165
+ else:
166
+ B = v.shape[0]
167
+ if hasattr(B, "value"):
168
+ B = B.value # TensorFlow
169
+ return B
170
+
171
+
172
+ def _unbatch_helper(v: TensorStructType, max_len: int) -> TensorStructType:
173
+ """Recursively unpacks the repeat dimension (max_len)."""
174
+ if isinstance(v, dict):
175
+ return {k: _unbatch_helper(u, max_len) for (k, u) in v.items()}
176
+ elif isinstance(v, tuple):
177
+ return tuple(_unbatch_helper(u, max_len) for u in v)
178
+ elif isinstance(v, RepeatedValues):
179
+ unbatched = _unbatch_helper(v.values, max_len)
180
+ return [
181
+ RepeatedValues(u, v.lengths[:, i, ...], v.max_len)
182
+ for i, u in enumerate(unbatched)
183
+ ]
184
+ else:
185
+ return [v[:, i, ...] for i in range(max_len)]
186
+
187
+
188
+ def _batch_index_helper(v: TensorStructType, i: int, j: int) -> TensorStructType:
189
+ """Selects the item at the ith batch index and jth repetition."""
190
+ if isinstance(v, dict):
191
+ return {k: _batch_index_helper(u, i, j) for (k, u) in v.items()}
192
+ elif isinstance(v, tuple):
193
+ return tuple(_batch_index_helper(u, i, j) for u in v)
194
+ elif isinstance(v, list):
195
+ # This is the output of unbatch_repeat_dim(). Unfortunately we have to
196
+ # process it here instead of in unbatch_all(), since it may be buried
197
+ # under a dict / tuple.
198
+ return _batch_index_helper(v[j], i, j)
199
+ elif isinstance(v, RepeatedValues):
200
+ unbatched = v.unbatch_all()
201
+ # Don't need to select j here; that's already done in unbatch_all.
202
+ return unbatched[i]
203
+ else:
204
+ return v[i, ...]
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/attention_net.cpython-310.pyc ADDED
Binary file (15.8 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/complex_input_net.cpython-310.pyc ADDED
Binary file (4.7 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/fcnet.cpython-310.pyc ADDED
Binary file (3.49 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/misc.cpython-310.pyc ADDED
Binary file (2.54 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/noop.cpython-310.pyc ADDED
Binary file (956 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/recurrent_net.cpython-310.pyc ADDED
Binary file (8.72 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/tf_distributions.cpython-310.pyc ADDED
Binary file (20.9 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/__pycache__/visionnet.cpython-310.pyc ADDED
Binary file (5.02 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/fcnet.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gymnasium as gym
3
+ from typing import Dict
4
+
5
+ from ray.rllib.models.tf.misc import normc_initializer
6
+ from ray.rllib.models.tf.tf_modelv2 import TFModelV2
7
+ from ray.rllib.models.utils import get_activation_fn
8
+ from ray.rllib.utils.annotations import OldAPIStack
9
+ from ray.rllib.utils.framework import try_import_tf
10
+ from ray.rllib.utils.typing import TensorType, List, ModelConfigDict
11
+
12
+ tf1, tf, tfv = try_import_tf()
13
+
14
+
15
+ @OldAPIStack
16
+ class FullyConnectedNetwork(TFModelV2):
17
+ """Generic fully connected network implemented in ModelV2 API."""
18
+
19
+ def __init__(
20
+ self,
21
+ obs_space: gym.spaces.Space,
22
+ action_space: gym.spaces.Space,
23
+ num_outputs: int,
24
+ model_config: ModelConfigDict,
25
+ name: str,
26
+ ):
27
+ super(FullyConnectedNetwork, self).__init__(
28
+ obs_space, action_space, num_outputs, model_config, name
29
+ )
30
+
31
+ hiddens = list(model_config.get("fcnet_hiddens", [])) + list(
32
+ model_config.get("post_fcnet_hiddens", [])
33
+ )
34
+ activation = model_config.get("fcnet_activation")
35
+ if not model_config.get("fcnet_hiddens", []):
36
+ activation = model_config.get("post_fcnet_activation")
37
+ activation = get_activation_fn(activation)
38
+ no_final_linear = model_config.get("no_final_linear")
39
+ vf_share_layers = model_config.get("vf_share_layers")
40
+ free_log_std = model_config.get("free_log_std")
41
+
42
+ # Generate free-floating bias variables for the second half of
43
+ # the outputs.
44
+ if free_log_std:
45
+ assert num_outputs % 2 == 0, (
46
+ "num_outputs must be divisible by two",
47
+ num_outputs,
48
+ )
49
+ num_outputs = num_outputs // 2
50
+ self.log_std_var = tf.Variable(
51
+ [0.0] * num_outputs, dtype=tf.float32, name="log_std"
52
+ )
53
+
54
+ # We are using obs_flat, so take the flattened shape as input.
55
+ inputs = tf.keras.layers.Input(
56
+ shape=(int(np.prod(obs_space.shape)),), name="observations"
57
+ )
58
+ # Last hidden layer output (before logits outputs).
59
+ last_layer = inputs
60
+ # The action distribution outputs.
61
+ logits_out = None
62
+ i = 1
63
+
64
+ # Create layers 0 to second-last.
65
+ for size in hiddens[:-1]:
66
+ last_layer = tf.keras.layers.Dense(
67
+ size,
68
+ name="fc_{}".format(i),
69
+ activation=activation,
70
+ kernel_initializer=normc_initializer(1.0),
71
+ )(last_layer)
72
+ i += 1
73
+
74
+ # The last layer is adjusted to be of size num_outputs, but it's a
75
+ # layer with activation.
76
+ if no_final_linear and num_outputs:
77
+ logits_out = tf.keras.layers.Dense(
78
+ num_outputs,
79
+ name="fc_out",
80
+ activation=activation,
81
+ kernel_initializer=normc_initializer(1.0),
82
+ )(last_layer)
83
+ # Finish the layers with the provided sizes (`hiddens`), plus -
84
+ # iff num_outputs > 0 - a last linear layer of size num_outputs.
85
+ else:
86
+ if len(hiddens) > 0:
87
+ last_layer = tf.keras.layers.Dense(
88
+ hiddens[-1],
89
+ name="fc_{}".format(i),
90
+ activation=activation,
91
+ kernel_initializer=normc_initializer(1.0),
92
+ )(last_layer)
93
+ if num_outputs:
94
+ logits_out = tf.keras.layers.Dense(
95
+ num_outputs,
96
+ name="fc_out",
97
+ activation=None,
98
+ kernel_initializer=normc_initializer(0.01),
99
+ )(last_layer)
100
+ # Adjust num_outputs to be the number of nodes in the last layer.
101
+ else:
102
+ self.num_outputs = ([int(np.prod(obs_space.shape))] + hiddens[-1:])[-1]
103
+
104
+ # Concat the log std vars to the end of the state-dependent means.
105
+ if free_log_std and logits_out is not None:
106
+
107
+ def tiled_log_std(x):
108
+ return tf.tile(tf.expand_dims(self.log_std_var, 0), [tf.shape(x)[0], 1])
109
+
110
+ log_std_out = tf.keras.layers.Lambda(tiled_log_std)(inputs)
111
+ logits_out = tf.keras.layers.Concatenate(axis=1)([logits_out, log_std_out])
112
+
113
+ last_vf_layer = None
114
+ if not vf_share_layers:
115
+ # Build a parallel set of hidden layers for the value net.
116
+ last_vf_layer = inputs
117
+ i = 1
118
+ for size in hiddens:
119
+ last_vf_layer = tf.keras.layers.Dense(
120
+ size,
121
+ name="fc_value_{}".format(i),
122
+ activation=activation,
123
+ kernel_initializer=normc_initializer(1.0),
124
+ )(last_vf_layer)
125
+ i += 1
126
+
127
+ value_out = tf.keras.layers.Dense(
128
+ 1,
129
+ name="value_out",
130
+ activation=None,
131
+ kernel_initializer=normc_initializer(0.01),
132
+ )(last_vf_layer if last_vf_layer is not None else last_layer)
133
+
134
+ self.base_model = tf.keras.Model(
135
+ inputs, [(logits_out if logits_out is not None else last_layer), value_out]
136
+ )
137
+
138
+ def forward(
139
+ self,
140
+ input_dict: Dict[str, TensorType],
141
+ state: List[TensorType],
142
+ seq_lens: TensorType,
143
+ ) -> (TensorType, List[TensorType]):
144
+ model_out, self._value_out = self.base_model(input_dict["obs_flat"])
145
+ return model_out, state
146
+
147
+ def value_function(self) -> TensorType:
148
+ return tf.reshape(self._value_out, [-1])
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (675 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/gru_gate.cpython-310.pyc ADDED
Binary file (2.2 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/multi_head_attention.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/noisy_layer.cpython-310.pyc ADDED
Binary file (3.43 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/relative_multi_head_attention.cpython-310.pyc ADDED
Binary file (4.7 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/__pycache__/skip_connection.cpython-310.pyc ADDED
Binary file (1.85 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/gru_gate.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ray.rllib.utils.framework import try_import_tf
2
+ from ray.rllib.utils.typing import TensorType, TensorShape
3
+ from ray.rllib.utils.deprecation import deprecation_warning
4
+ from ray.util import log_once
5
+
6
+ tf1, tf, tfv = try_import_tf()
7
+
8
+
9
+ class GRUGate(tf.keras.layers.Layer if tf else object):
10
+ def __init__(self, init_bias: float = 0.0, **kwargs):
11
+ super().__init__(**kwargs)
12
+ self._init_bias = init_bias
13
+ if log_once("gru_gate"):
14
+ deprecation_warning(
15
+ old="rllib.models.tf.layers.GRUGate",
16
+ )
17
+
18
+ def build(self, input_shape: TensorShape):
19
+ h_shape, x_shape = input_shape
20
+ if x_shape[-1] != h_shape[-1]:
21
+ raise ValueError(
22
+ "Both inputs to GRUGate must have equal size in last axis!"
23
+ )
24
+
25
+ dim = int(h_shape[-1])
26
+ self._w_r = self.add_weight(shape=(dim, dim))
27
+ self._w_z = self.add_weight(shape=(dim, dim))
28
+ self._w_h = self.add_weight(shape=(dim, dim))
29
+
30
+ self._u_r = self.add_weight(shape=(dim, dim))
31
+ self._u_z = self.add_weight(shape=(dim, dim))
32
+ self._u_h = self.add_weight(shape=(dim, dim))
33
+
34
+ def bias_initializer(shape, dtype):
35
+ return tf.fill(shape, tf.cast(self._init_bias, dtype=dtype))
36
+
37
+ self._bias_z = self.add_weight(shape=(dim,), initializer=bias_initializer)
38
+
39
+ def call(self, inputs: TensorType, **kwargs) -> TensorType:
40
+ # Pass in internal state first.
41
+ h, X = inputs
42
+
43
+ r = tf.tensordot(X, self._w_r, axes=1) + tf.tensordot(h, self._u_r, axes=1)
44
+ r = tf.nn.sigmoid(r)
45
+
46
+ z = (
47
+ tf.tensordot(X, self._w_z, axes=1)
48
+ + tf.tensordot(h, self._u_z, axes=1)
49
+ - self._bias_z
50
+ )
51
+ z = tf.nn.sigmoid(z)
52
+
53
+ h_next = tf.tensordot(X, self._w_h, axes=1) + tf.tensordot(
54
+ (h * r), self._u_h, axes=1
55
+ )
56
+ h_next = tf.nn.tanh(h_next)
57
+
58
+ return (1 - z) * h + z * h_next
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/multi_head_attention.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ [1] - Attention Is All You Need - Vaswani, Jones, Shazeer, Parmar,
3
+ Uszkoreit, Gomez, Kaiser - Google Brain/Research, U Toronto - 2017.
4
+ https://arxiv.org/pdf/1706.03762.pdf
5
+ """
6
+ from ray.rllib.utils.framework import try_import_tf
7
+ from ray.rllib.utils.typing import TensorType
8
+ from ray.rllib.utils.deprecation import deprecation_warning
9
+ from ray.util import log_once
10
+
11
+ tf1, tf, tfv = try_import_tf()
12
+
13
+
14
+ class MultiHeadAttention(tf.keras.layers.Layer if tf else object):
15
+ """A multi-head attention layer described in [1]."""
16
+
17
+ def __init__(self, out_dim: int, num_heads: int, head_dim: int, **kwargs):
18
+ super().__init__(**kwargs)
19
+
20
+ # No bias or non-linearity.
21
+ self._num_heads = num_heads
22
+ self._head_dim = head_dim
23
+ self._qkv_layer = tf.keras.layers.Dense(
24
+ 3 * num_heads * head_dim, use_bias=False
25
+ )
26
+ self._linear_layer = tf.keras.layers.TimeDistributed(
27
+ tf.keras.layers.Dense(out_dim, use_bias=False)
28
+ )
29
+ if log_once("multi_head_attention"):
30
+ deprecation_warning(
31
+ old="rllib.models.tf.layers.MultiHeadAttention",
32
+ )
33
+
34
+ def call(self, inputs: TensorType) -> TensorType:
35
+ L = tf.shape(inputs)[1] # length of segment
36
+ H = self._num_heads # number of attention heads
37
+ D = self._head_dim # attention head dimension
38
+
39
+ qkv = self._qkv_layer(inputs)
40
+
41
+ queries, keys, values = tf.split(qkv, 3, -1)
42
+ queries = queries[:, -L:] # only query based on the segment
43
+
44
+ queries = tf.reshape(queries, [-1, L, H, D])
45
+ keys = tf.reshape(keys, [-1, L, H, D])
46
+ values = tf.reshape(values, [-1, L, H, D])
47
+
48
+ score = tf.einsum("bihd,bjhd->bijh", queries, keys)
49
+ score = score / D**0.5
50
+
51
+ # causal mask of the same length as the sequence
52
+ mask = tf.sequence_mask(tf.range(1, L + 1), dtype=score.dtype)
53
+ mask = mask[None, :, :, None]
54
+
55
+ masked_score = score * mask + 1e30 * (mask - 1.0)
56
+ wmat = tf.nn.softmax(masked_score, axis=2)
57
+
58
+ out = tf.einsum("bijh,bjhd->bihd", wmat, values)
59
+ shape = tf.concat([tf.shape(out)[:2], [H * D]], axis=0)
60
+ out = tf.reshape(out, shape)
61
+ return self._linear_layer(out)
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/noisy_layer.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ray.rllib.models.utils import get_activation_fn
4
+ from ray.rllib.utils.framework import (
5
+ get_variable,
6
+ try_import_tf,
7
+ TensorType,
8
+ TensorShape,
9
+ )
10
+ from ray.rllib.utils.deprecation import deprecation_warning
11
+ from ray.util import log_once
12
+
13
+ tf1, tf, tfv = try_import_tf()
14
+
15
+
16
+ class NoisyLayer(tf.keras.layers.Layer if tf else object):
17
+ r"""A Layer that adds learnable Noise to some previous layer's outputs.
18
+
19
+ Consists of:
20
+ - a common dense layer: y = w^{T}x + b
21
+ - a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x +
22
+ (b+\epsilon_b*\sigma_b)
23
+ , where \epsilon are random variables sampled from factorized normal
24
+ distributions and \sigma are trainable variables which are expected to
25
+ vanish along the training procedure.
26
+ """
27
+
28
+ def __init__(
29
+ self, prefix: str, out_size: int, sigma0: float, activation: str = "relu"
30
+ ):
31
+ """Initializes a NoisyLayer object.
32
+
33
+ Args:
34
+ prefix:
35
+ out_size: Output size for Noisy Layer
36
+ sigma0: Initialization value for sigma_b (bias noise)
37
+ non_linear: Non-linear activation for Noisy Layer
38
+ """
39
+ super().__init__()
40
+ self.prefix = prefix
41
+ self.out_size = out_size
42
+ # TF noise generation can be unreliable on GPU
43
+ # If generating the noise on the CPU,
44
+ # lowering sigma0 to 0.1 may be helpful
45
+ self.sigma0 = sigma0 # 0.5~GPU, 0.1~CPU
46
+ self.activation = activation
47
+ # Variables.
48
+ self.w = None # Weight matrix.
49
+ self.b = None # Biases.
50
+ self.sigma_w = None # Noise for weight matrix
51
+ self.sigma_b = None # Noise for biases.
52
+ if log_once("noisy_layer"):
53
+ deprecation_warning(
54
+ old="rllib.models.tf.layers.NoisyLayer",
55
+ )
56
+
57
+ def build(self, input_shape: TensorShape):
58
+ in_size = int(input_shape[1])
59
+
60
+ self.sigma_w = get_variable(
61
+ value=tf.keras.initializers.RandomUniform(
62
+ minval=-1.0 / np.sqrt(float(in_size)),
63
+ maxval=1.0 / np.sqrt(float(in_size)),
64
+ ),
65
+ trainable=True,
66
+ tf_name=self.prefix + "_sigma_w",
67
+ shape=[in_size, self.out_size],
68
+ dtype=tf.float32,
69
+ )
70
+
71
+ self.sigma_b = get_variable(
72
+ value=tf.keras.initializers.Constant(self.sigma0 / np.sqrt(float(in_size))),
73
+ trainable=True,
74
+ tf_name=self.prefix + "_sigma_b",
75
+ shape=[self.out_size],
76
+ dtype=tf.float32,
77
+ )
78
+
79
+ self.w = get_variable(
80
+ value=tf.keras.initializers.GlorotUniform(),
81
+ tf_name=self.prefix + "_fc_w",
82
+ trainable=True,
83
+ shape=[in_size, self.out_size],
84
+ dtype=tf.float32,
85
+ )
86
+
87
+ self.b = get_variable(
88
+ value=tf.keras.initializers.Zeros(),
89
+ tf_name=self.prefix + "_fc_b",
90
+ trainable=True,
91
+ shape=[self.out_size],
92
+ dtype=tf.float32,
93
+ )
94
+
95
+ def call(self, inputs: TensorType) -> TensorType:
96
+ in_size = int(inputs.shape[1])
97
+ epsilon_in = tf.random.normal(shape=[in_size])
98
+ epsilon_out = tf.random.normal(shape=[self.out_size])
99
+ epsilon_in = self._f_epsilon(epsilon_in)
100
+ epsilon_out = self._f_epsilon(epsilon_out)
101
+ epsilon_w = tf.matmul(
102
+ a=tf.expand_dims(epsilon_in, -1), b=tf.expand_dims(epsilon_out, 0)
103
+ )
104
+ epsilon_b = epsilon_out
105
+
106
+ action_activation = (
107
+ tf.matmul(inputs, self.w + self.sigma_w * epsilon_w)
108
+ + self.b
109
+ + self.sigma_b * epsilon_b
110
+ )
111
+
112
+ fn = get_activation_fn(self.activation, framework="tf")
113
+ if fn is not None:
114
+ action_activation = fn(action_activation)
115
+ return action_activation
116
+
117
+ def _f_epsilon(self, x: TensorType) -> TensorType:
118
+ return tf.math.sign(x) * tf.math.sqrt(tf.math.abs(x))
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/relative_multi_head_attention.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from ray.rllib.utils.framework import try_import_tf
4
+ from ray.rllib.utils.typing import TensorType
5
+ from ray.rllib.utils.deprecation import deprecation_warning
6
+ from ray.util import log_once
7
+
8
+ tf1, tf, tfv = try_import_tf()
9
+
10
+
11
+ class RelativeMultiHeadAttention(tf.keras.layers.Layer if tf else object):
12
+ """A RelativeMultiHeadAttention layer as described in [3].
13
+
14
+ Uses segment level recurrence with state reuse.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ out_dim: int,
20
+ num_heads: int,
21
+ head_dim: int,
22
+ input_layernorm: bool = False,
23
+ output_activation: Optional["tf.nn.activation"] = None,
24
+ **kwargs
25
+ ):
26
+ """Initializes a RelativeMultiHeadAttention keras Layer object.
27
+
28
+ Args:
29
+ out_dim: The output dimensions of the multi-head attention
30
+ unit.
31
+ num_heads: The number of attention heads to use.
32
+ Denoted `H` in [2].
33
+ head_dim: The dimension of a single(!) attention head within
34
+ a multi-head attention unit. Denoted as `d` in [3].
35
+ input_layernorm: Whether to prepend a LayerNorm before
36
+ everything else. Should be True for building a GTrXL.
37
+ output_activation (Optional[tf.nn.activation]): Optional tf.nn
38
+ activation function. Should be relu for GTrXL.
39
+ **kwargs:
40
+ """
41
+ if log_once("relative_multi_head_attention"):
42
+ deprecation_warning(
43
+ old="rllib.models.tf.layers.RelativeMultiHeadAttention",
44
+ )
45
+ super().__init__(**kwargs)
46
+
47
+ # No bias or non-linearity.
48
+ self._num_heads = num_heads
49
+ self._head_dim = head_dim
50
+ # 3=Query, key, and value inputs.
51
+ self._qkv_layer = tf.keras.layers.Dense(
52
+ 3 * num_heads * head_dim, use_bias=False
53
+ )
54
+ self._linear_layer = tf.keras.layers.TimeDistributed(
55
+ tf.keras.layers.Dense(out_dim, use_bias=False, activation=output_activation)
56
+ )
57
+
58
+ self._uvar = self.add_weight(shape=(num_heads, head_dim))
59
+ self._vvar = self.add_weight(shape=(num_heads, head_dim))
60
+
61
+ # Constant (non-trainable) sinusoid rel pos encoding matrix, which
62
+ # depends on this incoming time dimension.
63
+ # For inference, we prepend the memory to the current timestep's
64
+ # input: Tau + 1. For training, we prepend the memory to the input
65
+ # sequence: Tau + T.
66
+ self._pos_embedding = PositionalEmbedding(out_dim)
67
+ self._pos_proj = tf.keras.layers.Dense(num_heads * head_dim, use_bias=False)
68
+
69
+ self._input_layernorm = None
70
+ if input_layernorm:
71
+ self._input_layernorm = tf.keras.layers.LayerNormalization(axis=-1)
72
+
73
+ def call(
74
+ self, inputs: TensorType, memory: Optional[TensorType] = None
75
+ ) -> TensorType:
76
+ T = tf.shape(inputs)[1] # length of segment (time)
77
+ H = self._num_heads # number of attention heads
78
+ d = self._head_dim # attention head dimension
79
+
80
+ # Add previous memory chunk (as const, w/o gradient) to input.
81
+ # Tau (number of (prev) time slices in each memory chunk).
82
+ Tau = tf.shape(memory)[1]
83
+ inputs = tf.concat([tf.stop_gradient(memory), inputs], axis=1)
84
+
85
+ # Apply the Layer-Norm.
86
+ if self._input_layernorm is not None:
87
+ inputs = self._input_layernorm(inputs)
88
+
89
+ qkv = self._qkv_layer(inputs)
90
+
91
+ queries, keys, values = tf.split(qkv, 3, -1)
92
+ # Cut out memory timesteps from query.
93
+ queries = queries[:, -T:]
94
+
95
+ # Splitting up queries into per-head dims (d).
96
+ queries = tf.reshape(queries, [-1, T, H, d])
97
+ keys = tf.reshape(keys, [-1, Tau + T, H, d])
98
+ values = tf.reshape(values, [-1, Tau + T, H, d])
99
+
100
+ R = self._pos_embedding(Tau + T)
101
+ R = self._pos_proj(R)
102
+ R = tf.reshape(R, [Tau + T, H, d])
103
+
104
+ # b=batch
105
+ # i and j=time indices (i=max-timesteps (inputs); j=Tau memory space)
106
+ # h=head
107
+ # d=head-dim (over which we will reduce-sum)
108
+ score = tf.einsum("bihd,bjhd->bijh", queries + self._uvar, keys)
109
+ pos_score = tf.einsum("bihd,jhd->bijh", queries + self._vvar, R)
110
+ score = score + self.rel_shift(pos_score)
111
+ score = score / d**0.5
112
+
113
+ # Causal mask of the same length as the sequence.
114
+ mask = tf.sequence_mask(tf.range(Tau + 1, Tau + T + 1), dtype=score.dtype)
115
+ mask = mask[None, :, :, None]
116
+
117
+ masked_score = score * mask + 1e30 * (mask - 1.0)
118
+ wmat = tf.nn.softmax(masked_score, axis=2)
119
+
120
+ out = tf.einsum("bijh,bjhd->bihd", wmat, values)
121
+ out = tf.reshape(out, tf.concat((tf.shape(out)[:2], [H * d]), axis=0))
122
+ return self._linear_layer(out)
123
+
124
+ @staticmethod
125
+ def rel_shift(x: TensorType) -> TensorType:
126
+ # Transposed version of the shift approach described in [3].
127
+ # https://github.com/kimiyoung/transformer-xl/blob/
128
+ # 44781ed21dbaec88b280f74d9ae2877f52b492a5/tf/model.py#L31
129
+ x_size = tf.shape(x)
130
+
131
+ x = tf.pad(x, [[0, 0], [0, 0], [1, 0], [0, 0]])
132
+ x = tf.reshape(x, [x_size[0], x_size[2] + 1, x_size[1], x_size[3]])
133
+ x = x[:, 1:, :, :]
134
+ x = tf.reshape(x, x_size)
135
+
136
+ return x
137
+
138
+
139
+ class PositionalEmbedding(tf.keras.layers.Layer if tf else object):
140
+ def __init__(self, out_dim, **kwargs):
141
+ super().__init__(**kwargs)
142
+ self.inverse_freq = 1 / (10000 ** (tf.range(0, out_dim, 2.0) / out_dim))
143
+
144
+ def call(self, seq_length):
145
+ pos_offsets = tf.cast(tf.range(seq_length - 1, -1, -1), tf.float32)
146
+ inputs = pos_offsets[:, None] * self.inverse_freq[None, :]
147
+ return tf.concat((tf.sin(inputs), tf.cos(inputs)), axis=-1)
vllm/lib/python3.10/site-packages/ray/rllib/models/tf/layers/skip_connection.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Any
2
+
3
+ from ray.rllib.utils.framework import try_import_tf
4
+ from ray.rllib.utils.typing import TensorType
5
+ from ray.rllib.utils.deprecation import deprecation_warning
6
+ from ray.util import log_once
7
+
8
+ tf1, tf, tfv = try_import_tf()
9
+
10
+
11
+ class SkipConnection(tf.keras.layers.Layer if tf else object):
12
+ """Skip connection layer.
13
+
14
+ Adds the original input to the output (regular residual layer) OR uses
15
+ input as hidden state input to a given fan_in_layer.
16
+ """
17
+
18
+ def __init__(self, layer: Any, fan_in_layer: Optional[Any] = None, **kwargs):
19
+ """Initializes a SkipConnection keras layer object.
20
+
21
+ Args:
22
+ layer (tf.keras.layers.Layer): Any layer processing inputs.
23
+ fan_in_layer (Optional[tf.keras.layers.Layer]): An optional
24
+ layer taking two inputs: The original input and the output
25
+ of `layer`.
26
+ """
27
+ if log_once("skip_connection"):
28
+ deprecation_warning(
29
+ old="rllib.models.tf.layers.SkipConnection",
30
+ )
31
+ super().__init__(**kwargs)
32
+ self._layer = layer
33
+ self._fan_in_layer = fan_in_layer
34
+
35
+ def call(self, inputs: TensorType, **kwargs) -> TensorType:
36
+ # del kwargs
37
+ outputs = self._layer(inputs, **kwargs)
38
+ # Residual case, just add inputs to outputs.
39
+ if self._fan_in_layer is None:
40
+ outputs = outputs + inputs
41
+ # Fan-in e.g. RNN: Call fan-in with `inputs` and `outputs`.
42
+ else:
43
+ # NOTE: In the GRU case, `inputs` is the state input.
44
+ outputs = self._fan_in_layer((inputs, outputs))
45
+
46
+ return outputs