ADAPT-Chase commited on
Commit
b65bf4f
·
verified ·
1 Parent(s): 89f15ae

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 +2 -0
  2. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/bc_module.cpython-312.pyc +0 -0
  3. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/__init__.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/base_env.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_context.cpython-312.pyc +0 -0
  6. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner.cpython-312.pyc +0 -0
  7. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner_group.cpython-312.pyc +0 -0
  8. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_env.cpython-312.pyc +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_multi_agent_env.cpython-312.pyc +0 -0
  10. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env.cpython-312.pyc +0 -0
  11. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env_runner.cpython-312.pyc +0 -0
  12. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc +3 -0
  13. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_client.cpython-312.pyc +0 -0
  14. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_server_input.cpython-312.pyc +0 -0
  15. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-312.pyc +0 -0
  16. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_env_runner.cpython-312.pyc +0 -0
  17. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-312.pyc +0 -0
  18. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/tcp_client_inference_env_runner.cpython-312.pyc +0 -0
  19. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/vector_env.cpython-312.pyc +0 -0
  20. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__init__.py +12 -0
  21. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/__init__.cpython-312.pyc +0 -0
  22. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/env_runner_server_for_external_inference.cpython-312.pyc +0 -0
  23. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/rllink.cpython-312.pyc +0 -0
  24. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/env_runner_server_for_external_inference.py +368 -0
  25. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/rllink.py +109 -0
  26. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__init__.py +124 -0
  27. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/__init__.cpython-312.pyc +0 -0
  28. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/external_env_protocol.cpython-312.pyc +0 -0
  29. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/infinite_lookback_buffer.cpython-312.pyc +0 -0
  30. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/external_env_protocol.py +8 -0
  31. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py +721 -0
  32. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__init__.py +0 -0
  33. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/__init__.cpython-312.pyc +0 -0
  34. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/registration.cpython-312.pyc +0 -0
  35. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/sync_vector_multi_agent_env.cpython-312.pyc +0 -0
  36. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/vector_multi_agent_env.cpython-312.pyc +0 -0
  37. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/registration.py +91 -0
  38. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/sync_vector_multi_agent_env.py +215 -0
  39. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/vector_multi_agent_env.py +88 -0
  40. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__init__.py +0 -0
  41. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/__init__.cpython-312.pyc +0 -0
  42. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/atari_wrappers.cpython-312.pyc +0 -0
  43. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_control_wrapper.cpython-312.pyc +0 -0
  44. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_env_wrapper.cpython-312.pyc +0 -0
  45. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/group_agents_wrapper.cpython-312.pyc +0 -0
  46. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/multi_agent_env_compatibility.cpython-312.pyc +0 -0
  47. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/open_spiel.cpython-312.pyc +0 -0
  48. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/pettingzoo_env.cpython-312.pyc +0 -0
  49. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/unity3d_env.cpython-312.pyc +0 -0
  50. tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/atari_wrappers.py +411 -0
.gitattributes CHANGED
@@ -4445,3 +4445,5 @@ tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/dataset.cpyt
4445
  tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4446
  tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4447
  tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
4445
  tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4446
  tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4447
  tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4448
+ tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4449
+ tool_server/.venv/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/bc_module.cpython-312.pyc ADDED
Binary file (9.25 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/base_env.cpython-312.pyc ADDED
Binary file (16.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_context.cpython-312.pyc ADDED
Binary file (5.91 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner.cpython-312.pyc ADDED
Binary file (11.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/env_runner_group.cpython-312.pyc ADDED
Binary file (52.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_env.cpython-312.pyc ADDED
Binary file (19.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/external_multi_agent_env.cpython-312.pyc ADDED
Binary file (7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env.cpython-312.pyc ADDED
Binary file (34.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_env_runner.cpython-312.pyc ADDED
Binary file (38.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5fce1cd7e76ccc16f30a194e79b53a2670fd5eeffd12846f185ac2b5e302619
3
+ size 105683
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_client.cpython-312.pyc ADDED
Binary file (13.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/policy_server_input.cpython-312.pyc ADDED
Binary file (12.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/remote_base_env.cpython-312.pyc ADDED
Binary file (18.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_env_runner.cpython-312.pyc ADDED
Binary file (31.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/single_agent_episode.cpython-312.pyc ADDED
Binary file (86.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/tcp_client_inference_env_runner.cpython-312.pyc ADDED
Binary file (376 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__pycache__/vector_env.cpython-312.pyc ADDED
Binary file (24.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ray.rllib.env.external.rllink import (
2
+ get_rllink_message,
3
+ send_rllink_message,
4
+ RLlink,
5
+ )
6
+
7
+
8
+ __all__ = [
9
+ "get_rllink_message",
10
+ "send_rllink_message",
11
+ "RLlink",
12
+ ]
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (345 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/env_runner_server_for_external_inference.cpython-312.pyc ADDED
Binary file (16.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/__pycache__/rllink.cpython-312.pyc ADDED
Binary file (3.73 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/env_runner_server_for_external_inference.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ import pickle
3
+ import socket
4
+ import threading
5
+ import time
6
+ from typing import Collection, DefaultDict, List, Optional, Union
7
+
8
+ from ray.rllib.core import (
9
+ COMPONENT_RL_MODULE,
10
+ DEFAULT_AGENT_ID,
11
+ DEFAULT_MODULE_ID,
12
+ )
13
+ from ray.rllib.env import INPUT_ENV_SPACES
14
+ from ray.rllib.env.env_runner import EnvRunner
15
+ from ray.rllib.env.single_agent_env_runner import SingleAgentEnvRunner
16
+ from ray.rllib.env.single_agent_episode import SingleAgentEpisode
17
+ from ray.rllib.env.external.rllink import (
18
+ get_rllink_message,
19
+ send_rllink_message,
20
+ RLlink,
21
+ )
22
+ from ray.rllib.utils.annotations import override
23
+ from ray.rllib.utils.checkpoints import Checkpointable
24
+ from ray.rllib.utils.framework import try_import_torch
25
+ from ray.rllib.utils.metrics import (
26
+ EPISODE_DURATION_SEC_MEAN,
27
+ EPISODE_LEN_MAX,
28
+ EPISODE_LEN_MEAN,
29
+ EPISODE_LEN_MIN,
30
+ EPISODE_RETURN_MAX,
31
+ EPISODE_RETURN_MEAN,
32
+ EPISODE_RETURN_MIN,
33
+ WEIGHTS_SEQ_NO,
34
+ )
35
+ from ray.rllib.utils.metrics.metrics_logger import MetricsLogger
36
+ from ray.rllib.utils.typing import EpisodeID, StateDict
37
+ from ray.util.annotations import DeveloperAPI
38
+
39
+ torch, _ = try_import_torch()
40
+
41
+
42
+ @DeveloperAPI
43
+ class EnvRunnerServerForExternalInference(EnvRunner, Checkpointable):
44
+ """An EnvRunner communicating with an external env through a TCP socket.
45
+
46
+ This implementation assumes:
47
+ - Only one external client ever connects to this env runner.
48
+ - The external client owns the connector pipelines (env-to-module and module-to-env)
49
+ as well as the RLModule and thus performs inference locally. Samples are sent in
50
+ bulk as lists of RLlib episodes once a certain number of timesteps has been executed
51
+ on the client's side.
52
+ - A copy of the RLModule is kept at all times on this EnvRunner, but is never used
53
+ for inference, only as a weights container.
54
+ TODO (sven): The above might be inefficient as we have to store basically two
55
+ models, one in this EnvRunner, one in the env (as ONNX).
56
+ - As a consequence, there are no environment and no connectors on this env runner.
57
+ The external env is responsible for generating all the data to create episodes.
58
+ """
59
+
60
+ @override(EnvRunner)
61
+ def __init__(self, *, config, **kwargs):
62
+ """
63
+ Initializes an EnvRunnerServerForExternalInference instance.
64
+
65
+ Args:
66
+ config: The AlgorithmConfig to use for setup.
67
+
68
+ Keyword Args:
69
+ port: The base port number. The server socket is then actually bound to
70
+ `port` + self.worker_index.
71
+ """
72
+ super().__init__(config=config, **kwargs)
73
+
74
+ self.worker_index: int = kwargs.get("worker_index", 0)
75
+
76
+ self._weights_seq_no = 0
77
+
78
+ # Build the module from its spec.
79
+ module_spec = self.config.get_rl_module_spec(
80
+ spaces=self.get_spaces(), inference_only=True
81
+ )
82
+ self.module = module_spec.build()
83
+
84
+ self.host = "localhost"
85
+ self.port = int(self.config.env_config.get("port", 5555)) + self.worker_index
86
+ self.server_socket = None
87
+ self.client_socket = None
88
+ self.address = None
89
+
90
+ self.metrics = MetricsLogger()
91
+
92
+ self._episode_chunks_to_return: Optional[List[SingleAgentEpisode]] = None
93
+ self._done_episodes_for_metrics: List[SingleAgentEpisode] = []
94
+ self._ongoing_episodes_for_metrics: DefaultDict[
95
+ EpisodeID, List[SingleAgentEpisode]
96
+ ] = defaultdict(list)
97
+
98
+ self._sample_lock = threading.Lock()
99
+ self._on_policy_lock = threading.Lock()
100
+ self._blocked_on_state = False
101
+
102
+ # Start a background thread for client communication.
103
+ self.thread = threading.Thread(
104
+ target=self._client_message_listener, daemon=True
105
+ )
106
+ self.thread.start()
107
+
108
+ @override(EnvRunner)
109
+ def assert_healthy(self):
110
+ """Checks that the server socket is open and listening."""
111
+ assert (
112
+ self.server_socket is not None
113
+ ), "Server socket is None (not connected, not listening)."
114
+
115
+ @override(EnvRunner)
116
+ def sample(self, **kwargs):
117
+ """Waits for the client to send episodes."""
118
+ while True:
119
+ with self._sample_lock:
120
+ if self._episode_chunks_to_return is not None:
121
+ num_env_steps = 0
122
+ num_episodes_completed = 0
123
+ for eps in self._episode_chunks_to_return:
124
+ if eps.is_done:
125
+ self._done_episodes_for_metrics.append(eps)
126
+ num_episodes_completed += 1
127
+ else:
128
+ self._ongoing_episodes_for_metrics[eps.id_].append(eps)
129
+ num_env_steps += len(eps)
130
+
131
+ ret = self._episode_chunks_to_return
132
+ self._episode_chunks_to_return = None
133
+
134
+ SingleAgentEnvRunner._increase_sampled_metrics(
135
+ self, num_env_steps, num_episodes_completed
136
+ )
137
+
138
+ return ret
139
+ time.sleep(0.01)
140
+
141
+ @override(EnvRunner)
142
+ def get_metrics(self):
143
+ # TODO (sven): We should probably make this a utility function to be called
144
+ # from within Single/MultiAgentEnvRunner and other EnvRunner subclasses, as
145
+ # needed.
146
+ # Compute per-episode metrics (only on already completed episodes).
147
+ for eps in self._done_episodes_for_metrics:
148
+ assert eps.is_done
149
+ episode_length = len(eps)
150
+ episode_return = eps.get_return()
151
+ episode_duration_s = eps.get_duration_s()
152
+ # Don't forget about the already returned chunks of this episode.
153
+ if eps.id_ in self._ongoing_episodes_for_metrics:
154
+ for eps2 in self._ongoing_episodes_for_metrics[eps.id_]:
155
+ episode_length += len(eps2)
156
+ episode_return += eps2.get_return()
157
+ episode_duration_s += eps2.get_duration_s()
158
+ del self._ongoing_episodes_for_metrics[eps.id_]
159
+
160
+ self._log_episode_metrics(
161
+ episode_length, episode_return, episode_duration_s
162
+ )
163
+
164
+ # Now that we have logged everything, clear cache of done episodes.
165
+ self._done_episodes_for_metrics.clear()
166
+
167
+ # Return reduced metrics.
168
+ return self.metrics.reduce()
169
+
170
+ def get_spaces(self):
171
+ return {
172
+ INPUT_ENV_SPACES: (self.config.observation_space, self.config.action_space),
173
+ DEFAULT_MODULE_ID: (
174
+ self.config.observation_space,
175
+ self.config.action_space,
176
+ ),
177
+ }
178
+
179
+ @override(EnvRunner)
180
+ def stop(self):
181
+ """Closes the client and server sockets."""
182
+ self._close_sockets_if_necessary()
183
+
184
+ @override(Checkpointable)
185
+ def get_ctor_args_and_kwargs(self):
186
+ return (
187
+ (), # *args
188
+ {"config": self.config}, # **kwargs
189
+ )
190
+
191
+ @override(Checkpointable)
192
+ def get_checkpointable_components(self):
193
+ return [
194
+ (COMPONENT_RL_MODULE, self.module),
195
+ ]
196
+
197
+ @override(Checkpointable)
198
+ def get_state(
199
+ self,
200
+ components: Optional[Union[str, Collection[str]]] = None,
201
+ *,
202
+ not_components: Optional[Union[str, Collection[str]]] = None,
203
+ **kwargs,
204
+ ) -> StateDict:
205
+ return {
206
+ COMPONENT_RL_MODULE: self.module.get_state(),
207
+ WEIGHTS_SEQ_NO: self._weights_seq_no,
208
+ }
209
+
210
+ @override(Checkpointable)
211
+ def set_state(self, state: StateDict) -> None:
212
+ # Update the RLModule state.
213
+ if COMPONENT_RL_MODULE in state:
214
+ # A missing value for WEIGHTS_SEQ_NO or a value of 0 means: Force the
215
+ # update.
216
+ weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0)
217
+
218
+ # Only update the weigths, if this is the first synchronization or
219
+ # if the weights of this `EnvRunner` lacks behind the actual ones.
220
+ if weights_seq_no == 0 or self._weights_seq_no < weights_seq_no:
221
+ rl_module_state = state[COMPONENT_RL_MODULE]
222
+ if (
223
+ isinstance(rl_module_state, dict)
224
+ and DEFAULT_MODULE_ID in rl_module_state
225
+ ):
226
+ rl_module_state = rl_module_state[DEFAULT_MODULE_ID]
227
+ self.module.set_state(rl_module_state)
228
+
229
+ # Update our weights_seq_no, if the new one is > 0.
230
+ if weights_seq_no > 0:
231
+ self._weights_seq_no = weights_seq_no
232
+
233
+ if self._blocked_on_state is True:
234
+ self._send_set_state_message()
235
+ self._blocked_on_state = False
236
+
237
+ def _client_message_listener(self):
238
+ """Entry point for the listener thread."""
239
+
240
+ # Set up the server socket and bind to the specified host and port.
241
+ self._recycle_sockets()
242
+
243
+ # Enter an endless message receival- and processing loop.
244
+ while True:
245
+ # As long as we are blocked on a new state, sleep a bit and continue.
246
+ # Do NOT process any incoming messages (until we send out the new state
247
+ # back to the client).
248
+ if self._blocked_on_state is True:
249
+ time.sleep(0.01)
250
+ continue
251
+
252
+ try:
253
+ # Blocking call to get next message.
254
+ msg_type, msg_body = get_rllink_message(self.client_socket)
255
+
256
+ # Process the message received based on its type.
257
+ # Initial handshake.
258
+ if msg_type == RLlink.PING:
259
+ self._send_pong_message()
260
+
261
+ # Episode data from the client.
262
+ elif msg_type in [
263
+ RLlink.EPISODES,
264
+ RLlink.EPISODES_AND_GET_STATE,
265
+ ]:
266
+ self._process_episodes_message(msg_type, msg_body)
267
+
268
+ # Client requests the state (model weights).
269
+ elif msg_type == RLlink.GET_STATE:
270
+ self._send_set_state_message()
271
+
272
+ # Clients requests config information.
273
+ elif msg_type == RLlink.GET_CONFIG:
274
+ self._send_set_config_message()
275
+
276
+ except ConnectionError as e:
277
+ print(f"Messaging/connection error {e}! Recycling sockets ...")
278
+ self._recycle_sockets(5.0)
279
+ continue
280
+
281
+ def _recycle_sockets(self, sleep: float = 0.0):
282
+ # Close all old sockets, if they exist.
283
+ self._close_sockets_if_necessary()
284
+
285
+ time.sleep(sleep)
286
+
287
+ # Start listening on the configured port.
288
+ self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
289
+ # Allow reuse of the address.
290
+ self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
291
+ self.server_socket.bind((self.host, self.port))
292
+ # Listen for a single connection.
293
+ self.server_socket.listen(1)
294
+ print(f"Waiting for client to connect to port {self.port}...")
295
+
296
+ self.client_socket, self.address = self.server_socket.accept()
297
+ print(f"Connected to client at {self.address}")
298
+
299
+ def _close_sockets_if_necessary(self):
300
+ if self.client_socket:
301
+ self.client_socket.close()
302
+ if self.server_socket:
303
+ self.server_socket.close()
304
+
305
+ def _send_pong_message(self):
306
+ send_rllink_message(self.client_socket, {"type": RLlink.PONG.name})
307
+
308
+ def _process_episodes_message(self, msg_type, msg_body):
309
+ # On-policy training -> we have to block until we get a new `set_state` call
310
+ # (b/c the learning step is done and we can send new weights back to all
311
+ # clients).
312
+ if msg_type == RLlink.EPISODES_AND_GET_STATE:
313
+ self._blocked_on_state = True
314
+
315
+ episodes = []
316
+ for episode_state in msg_body["episodes"]:
317
+ episode = SingleAgentEpisode.from_state(episode_state)
318
+ episodes.append(episode.to_numpy())
319
+
320
+ # Push episodes into the to-be-returned list (for `sample()` requests).
321
+ with self._sample_lock:
322
+ if isinstance(self._episode_chunks_to_return, list):
323
+ self._episode_chunks_to_return.extend(episodes)
324
+ else:
325
+ self._episode_chunks_to_return = episodes
326
+
327
+ def _send_set_state_message(self):
328
+ send_rllink_message(
329
+ self.client_socket,
330
+ {
331
+ "type": RLlink.SET_STATE.name,
332
+ "state": self.get_state(inference_only=True),
333
+ },
334
+ )
335
+
336
+ def _send_set_config_message(self):
337
+ send_rllink_message(
338
+ self.client_socket,
339
+ {
340
+ "type": RLlink.SET_CONFIG.name,
341
+ # TODO (sven): We need AlgorithmConfig to be a `Checkpointable` with a
342
+ # msgpack'able state.
343
+ "config": pickle.dumps(self.config),
344
+ },
345
+ )
346
+
347
+ def _log_episode_metrics(self, length, ret, sec):
348
+ # Log general episode metrics.
349
+ # To mimic the old API stack behavior, we'll use `window` here for
350
+ # these particular stats (instead of the default EMA).
351
+ win = self.config.metrics_num_episodes_for_smoothing
352
+ self.metrics.log_value(EPISODE_LEN_MEAN, length, window=win)
353
+ self.metrics.log_value(EPISODE_RETURN_MEAN, ret, window=win)
354
+ self.metrics.log_value(EPISODE_DURATION_SEC_MEAN, sec, window=win)
355
+ # Per-agent returns.
356
+ self.metrics.log_value(
357
+ ("agent_episode_returns_mean", DEFAULT_AGENT_ID), ret, window=win
358
+ )
359
+ # Per-RLModule returns.
360
+ self.metrics.log_value(
361
+ ("module_episode_returns_mean", DEFAULT_MODULE_ID), ret, window=win
362
+ )
363
+
364
+ # For some metrics, log min/max as well.
365
+ self.metrics.log_value(EPISODE_LEN_MIN, length, reduce="min", window=win)
366
+ self.metrics.log_value(EPISODE_RETURN_MIN, ret, reduce="min", window=win)
367
+ self.metrics.log_value(EPISODE_LEN_MAX, length, reduce="max", window=win)
368
+ self.metrics.log_value(EPISODE_RETURN_MAX, ret, reduce="max", window=win)
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external/rllink.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ from packaging.version import Version
3
+
4
+ from ray.rllib.utils.checkpoints import try_import_msgpack
5
+ from ray.util.annotations import DeveloperAPI
6
+
7
+
8
+ msgpack = None
9
+
10
+
11
+ @DeveloperAPI
12
+ class RLlink(Enum):
13
+ PROTOCOL_VERSION = Version("0.0.1")
14
+
15
+ # Requests: Client (external env) -> Server (RLlib).
16
+ # ----
17
+ # Ping command (initial handshake).
18
+ PING = "PING"
19
+ # List of episodes (similar to what an EnvRunner.sample() call would return).
20
+ EPISODES = "EPISODES"
21
+ # Request state (e.g. model weights).
22
+ GET_STATE = "GET_STATE"
23
+ # Request Algorithm config.
24
+ GET_CONFIG = "GET_CONFIG"
25
+ # Send episodes and request the next state update right after that.
26
+ # Clients sending this message should wait for a SET_STATE message as an immediate
27
+ # response. Useful for external samplers that must collect on-policy data.
28
+ EPISODES_AND_GET_STATE = "EPISODES_AND_GET_STATE"
29
+
30
+ # Responses: Server (RLlib) -> Client (external env).
31
+ # ----
32
+ # Pong response (initial handshake).
33
+ PONG = "PONG"
34
+ # Set state (e.g. model weights).
35
+ SET_STATE = "SET_STATE"
36
+ # Set Algorithm config.
37
+ SET_CONFIG = "SET_CONFIG"
38
+
39
+ # @OldAPIStack (to be deprecated soon).
40
+ ACTION_SPACE = "ACTION_SPACE"
41
+ OBSERVATION_SPACE = "OBSERVATION_SPACE"
42
+ GET_WORKER_ARGS = "GET_WORKER_ARGS"
43
+ GET_WEIGHTS = "GET_WEIGHTS"
44
+ REPORT_SAMPLES = "REPORT_SAMPLES"
45
+ START_EPISODE = "START_EPISODE"
46
+ GET_ACTION = "GET_ACTION"
47
+ LOG_ACTION = "LOG_ACTION"
48
+ LOG_RETURNS = "LOG_RETURNS"
49
+ END_EPISODE = "END_EPISODE"
50
+
51
+ def __str__(self):
52
+ return self.name
53
+
54
+
55
+ @DeveloperAPI
56
+ def send_rllink_message(sock_, message: dict):
57
+ """Sends a message to the client with a length header."""
58
+ global msgpack
59
+ if msgpack is None:
60
+ msgpack = try_import_msgpack(error=True)
61
+
62
+ body = msgpack.packb(message, use_bin_type=True) # .encode("utf-8")
63
+ header = str(len(body)).zfill(8).encode("utf-8")
64
+ try:
65
+ sock_.sendall(header + body)
66
+ except Exception as e:
67
+ raise ConnectionError(
68
+ f"Error sending message {message} to server on socket {sock_}! "
69
+ f"Original error was: {e}"
70
+ )
71
+
72
+
73
+ @DeveloperAPI
74
+ def get_rllink_message(sock_):
75
+ """Receives a message from the client following the length-header protocol."""
76
+ global msgpack
77
+ if msgpack is None:
78
+ msgpack = try_import_msgpack(error=True)
79
+
80
+ try:
81
+ # Read the length header (8 bytes)
82
+ header = _get_num_bytes(sock_, 8)
83
+ msg_length = int(header.decode("utf-8"))
84
+ # Read the message body
85
+ body = _get_num_bytes(sock_, msg_length)
86
+ # Decode JSON.
87
+ message = msgpack.unpackb(body, raw=False) # .loads(body.decode("utf-8"))
88
+ # Check for proper protocol.
89
+ if "type" not in message:
90
+ raise ConnectionError(
91
+ "Protocol Error! Message from peer does not contain `type` field."
92
+ )
93
+ return RLlink(message.pop("type")), message
94
+ except Exception as e:
95
+ raise ConnectionError(
96
+ f"Error receiving message from peer on socket {sock_}! "
97
+ f"Original error was: {e}"
98
+ )
99
+
100
+
101
+ def _get_num_bytes(sock_, num_bytes):
102
+ """Helper function to receive a specific number of bytes."""
103
+ data = b""
104
+ while len(data) < num_bytes:
105
+ packet = sock_.recv(num_bytes - len(data))
106
+ if not packet:
107
+ raise ConnectionError(f"No data received from socket {sock_}!")
108
+ data += packet
109
+ return data
tool_server/.venv/lib/python3.12/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
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (4.19 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/external_env_protocol.cpython-312.pyc ADDED
Binary file (470 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/__pycache__/infinite_lookback_buffer.cpython-312.pyc ADDED
Binary file (29 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/external_env_protocol.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from ray.rllib.env.external.rllink import RLlink # noqa
2
+ from ray.rllib.utils.deprecation import deprecation_warning
3
+
4
+ deprecation_warning(
5
+ old="ray.rllib.env.utils.external_env_protocol",
6
+ new="ray.rllib.env.external.rllink",
7
+ error=False,
8
+ )
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/utils/infinite_lookback_buffer.py ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from ray.util.annotations import DeveloperAPI
17
+
18
+
19
+ @DeveloperAPI
20
+ class InfiniteLookbackBuffer:
21
+ @property
22
+ def space(self):
23
+ return self._space
24
+
25
+ @space.setter
26
+ def space(self, value):
27
+ self._space = value
28
+ self.space_struct = get_base_struct_from_space(value)
29
+
30
+ def __init__(
31
+ self,
32
+ data: Optional[Union[List, np.ndarray]] = None,
33
+ lookback: int = 0,
34
+ space: Optional[gym.Space] = None,
35
+ ):
36
+ self.data = data if data is not None else []
37
+ self.lookback = min(lookback, len(self.data))
38
+ self.finalized = not isinstance(self.data, list)
39
+ self.space_struct = None
40
+ self.space = space
41
+
42
+ def __eq__(
43
+ self,
44
+ other: "InfiniteLookbackBuffer",
45
+ ) -> bool:
46
+ """Compares two `InfiniteLookbackBuffers.
47
+
48
+ Args:
49
+ other: Another object. If another `LookbackBuffer` instance all
50
+ their attributes are compared.
51
+
52
+ Returns:
53
+ `True`, if `other` is an `InfiniteLookbackBuffer` instance and all
54
+ attributes are identical. Otherwise, returns `False`.
55
+ """
56
+ if isinstance(other, InfiniteLookbackBuffer):
57
+ if (
58
+ self.data == other.data
59
+ and self.lookback == other.lookback
60
+ and self.finalized == other.finalized
61
+ and self.space_struct == other.space_struct
62
+ and self.space == other.space
63
+ ):
64
+ return True
65
+ return False
66
+
67
+ def get_state(self) -> Dict[str, Any]:
68
+ """Returns the pickable state of a buffer.
69
+
70
+ The data in the buffer is stored into a dictionary. Note that
71
+ buffers can also be generated from pickable states (see
72
+ `InfiniteLookbackBuffer.from_state`)
73
+
74
+ Returns:
75
+ A dict containing all the data and metadata from the buffer.
76
+ """
77
+ return {
78
+ "data": to_jsonable_if_needed(self.data, self.space)
79
+ if self.space
80
+ else self.data,
81
+ "lookback": self.lookback,
82
+ "finalized": self.finalized,
83
+ "space": gym_space_to_dict(self.space) if self.space else self.space,
84
+ }
85
+
86
+ @staticmethod
87
+ def from_state(state: Dict[str, Any]) -> None:
88
+ """Creates a new `InfiniteLookbackBuffer` from a state dict.
89
+
90
+ Args:
91
+ state: The state dict, as returned by `self.get_state`.
92
+
93
+ Returns:
94
+ A new `InfiniteLookbackBuffer` instance with the data and metadata
95
+ from the state dict.
96
+ """
97
+ buffer = InfiniteLookbackBuffer()
98
+ buffer.lookback = state["lookback"]
99
+ buffer.finalized = state["finalized"]
100
+ buffer.space = gym_space_from_dict(state["space"]) if state["space"] else None
101
+ buffer.space_struct = (
102
+ get_base_struct_from_space(buffer.space) if buffer.space else None
103
+ )
104
+ buffer.data = (
105
+ from_jsonable_if_needed(state["data"], buffer.space)
106
+ if buffer.space
107
+ else state["data"]
108
+ )
109
+
110
+ return buffer
111
+
112
+ def append(self, item) -> None:
113
+ """Appends the given item to the end of this buffer."""
114
+ if self.finalized:
115
+ self.data = tree.map_structure(
116
+ lambda d, i: np.concatenate([d, [i]], axis=0), self.data, item
117
+ )
118
+ else:
119
+ self.data.append(item)
120
+
121
+ def extend(self, items) -> None:
122
+ """Appends all items in `items` to the end of this buffer."""
123
+ if self.finalized:
124
+ # TODO (sven): When extending with a list of structs, we should
125
+ # probably rather do: `tree.map_structure(..., self.data,
126
+ # tree.map_structure(lambda *s: np.array(*s), *items)`)??
127
+ self.data = tree.map_structure(
128
+ lambda d, i: np.concatenate([d, i], axis=0),
129
+ self.data,
130
+ # Note, we could have dictionaries here.
131
+ np.array(items) if isinstance(items, list) else items,
132
+ )
133
+ else:
134
+ for item in items:
135
+ self.append(item)
136
+
137
+ def concat(self, other: "InfiniteLookbackBuffer") -> None:
138
+ """Concatenates the data of `other` (w/o its lookback) to `self`.
139
+
140
+ Args:
141
+ other: The other InfiniteLookbackBuffer to be concatenated to self.
142
+ """
143
+ self.data.extend(other.get())
144
+
145
+ def pop(self, index: int = -1) -> None:
146
+ """Removes the item at `index` from this buffer, but does NOT return it.
147
+
148
+ Args:
149
+ index: The index to pop out of this buffer (w/o returning it from this
150
+ method).
151
+ """
152
+ if self.finalized:
153
+ self.data = tree.map_structure(
154
+ lambda s: np.delete(s, index, axis=0), self.data
155
+ )
156
+ else:
157
+ self.data.pop(index)
158
+
159
+ def finalize(self) -> None:
160
+ """Finalizes this buffer by converting internal data lists into numpy arrays.
161
+
162
+ Thereby, if the individual items in the list are nested structures, the
163
+ resulting buffer content will be a nested struct of np.ndarrays (leafs).
164
+ """
165
+ if not self.finalized:
166
+ self.data = batch(self.data)
167
+ self.finalized = True
168
+
169
+ def get(
170
+ self,
171
+ indices: Optional[Union[int, slice, List[int]]] = None,
172
+ *,
173
+ neg_index_as_lookback: bool = False,
174
+ fill: Optional[Any] = None,
175
+ one_hot_discrete: bool = False,
176
+ _ignore_last_ts: bool = False,
177
+ _add_last_ts_value: Optional[Any] = None,
178
+ ) -> Any:
179
+ """Returns data, based on the given args, from this buffer.
180
+
181
+ Args:
182
+ indices: A single int is interpreted as an index, from which to return the
183
+ individual data stored at this index.
184
+ A list of ints is interpreted as a list of indices from which to gather
185
+ individual data in a batch of size len(indices).
186
+ A slice object is interpreted as a range of data to be returned.
187
+ Thereby, negative indices by default are interpreted as "before the end"
188
+ unless the `neg_index_as_lookback=True` option is used, in which case
189
+ negative indices are interpreted as "before ts=0", meaning going back
190
+ into the lookback buffer.
191
+ neg_index_as_lookback: If True, negative values in `indices` are
192
+ interpreted as "before ts=0", meaning going back into the lookback
193
+ buffer. For example, a buffer with data [4, 5, 6, 7, 8, 9],
194
+ where [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will
195
+ respond to `get(-1, neg_index_as_lookback=True)` with `6` and to
196
+ `get(slice(-2, 1), neg_index_as_lookback=True)` with `[5, 6, 7]`.
197
+ fill: An optional float value to use for filling up the returned results at
198
+ the boundaries. This filling only happens if the requested index range's
199
+ start/stop boundaries exceed the buffer's boundaries (including the
200
+ lookback buffer on the left side). This comes in very handy, if users
201
+ don't want to worry about reaching such boundaries and want to zero-pad.
202
+ For example, a buffer with data [10, 11, 12, 13, 14] and lookback
203
+ buffer size of 2 (meaning `10` and `11` are part of the lookback buffer)
204
+ will respond to `get(slice(-7, -2), fill=0.0)`
205
+ with `[0.0, 0.0, 10, 11, 12]`.
206
+ one_hot_discrete: If True, will return one-hot vectors (instead of
207
+ int-values) for those sub-components of a (possibly complex) space
208
+ that are Discrete or MultiDiscrete. Note that if `fill=0` and the
209
+ requested `indices` are out of the range of our data, the returned
210
+ one-hot vectors will actually be zero-hot (all slots zero).
211
+ _ignore_last_ts: Whether to ignore the last record in our internal
212
+ `self.data` when getting the provided indices.
213
+ _add_last_ts_value: Whether to add the value of this arg to the end of
214
+ the internal `self.data` buffer (just for the duration of this get
215
+ operation, not permanently).
216
+ """
217
+ if indices is None:
218
+ data = self._get_all_data(
219
+ one_hot_discrete=one_hot_discrete,
220
+ _ignore_last_ts=_ignore_last_ts,
221
+ )
222
+ elif isinstance(indices, slice):
223
+ data = self._get_slice(
224
+ indices,
225
+ fill=fill,
226
+ neg_index_as_lookback=neg_index_as_lookback,
227
+ one_hot_discrete=one_hot_discrete,
228
+ _ignore_last_ts=_ignore_last_ts,
229
+ _add_last_ts_value=_add_last_ts_value,
230
+ )
231
+ elif isinstance(indices, list):
232
+ data = [
233
+ self._get_int_index(
234
+ idx,
235
+ fill=fill,
236
+ neg_index_as_lookback=neg_index_as_lookback,
237
+ one_hot_discrete=one_hot_discrete,
238
+ _ignore_last_ts=_ignore_last_ts,
239
+ _add_last_ts_value=_add_last_ts_value,
240
+ )
241
+ for idx in indices
242
+ ]
243
+ if self.finalized:
244
+ data = batch(data)
245
+ else:
246
+ assert isinstance(indices, int)
247
+ data = self._get_int_index(
248
+ indices,
249
+ fill=fill,
250
+ neg_index_as_lookback=neg_index_as_lookback,
251
+ one_hot_discrete=one_hot_discrete,
252
+ _ignore_last_ts=_ignore_last_ts,
253
+ _add_last_ts_value=_add_last_ts_value,
254
+ )
255
+
256
+ return data
257
+
258
+ def __add__(
259
+ self, other: Union[List, "InfiniteLookbackBuffer", int, float, complex]
260
+ ) -> "InfiniteLookbackBuffer":
261
+ """Adds another InfiniteLookbackBuffer object or list to the end of this one.
262
+
263
+ Args:
264
+ other: Another `InfiniteLookbackBuffer` or a `list` or a number.
265
+ If a `InfiniteLookbackBuffer` its data (w/o its lookback buffer) gets
266
+ concatenated to self's data. If a `list`, we concat it to self's data.
267
+ If a number, we add this number to each element of self (if possible).
268
+
269
+ Returns:
270
+ A new `InfiniteLookbackBuffer` instance `self.data` containing
271
+ concatenated data from `self` and `other` (or adding `other` to each element
272
+ in self's data).
273
+ """
274
+
275
+ if self.finalized:
276
+ raise RuntimeError(f"Cannot `add` to a finalized {type(self).__name__}.")
277
+ else:
278
+ # If `other` is an int, simply add it to all our values (if possible) and
279
+ # use the result as the underlying data for the returned buffer.
280
+ if isinstance(other, (int, float, complex)):
281
+ data = [
282
+ (d + other) if isinstance(d, (int, float, complex)) else d
283
+ for d in self.data
284
+ ]
285
+ # If `other` is a InfiniteLookbackBuffer itself, do NOT include its
286
+ # lookback buffer anymore. We assume that `other`'s lookback buffer i
287
+ # already at the end of `self`.
288
+ elif isinstance(other, InfiniteLookbackBuffer):
289
+ data = self.data + other.data[other.lookback :]
290
+ # `other` is a list, simply concat the two lists and use the result as
291
+ # the underlying data for the returned buffer.
292
+ else:
293
+ data = self.data + other
294
+
295
+ return InfiniteLookbackBuffer(
296
+ data=data,
297
+ lookback=self.lookback,
298
+ space=self.space,
299
+ )
300
+
301
+ def __getitem__(self, item):
302
+ """Support squared bracket syntax, e.g. buffer[:5]."""
303
+ return self.get(item)
304
+
305
+ def __setitem__(self, key, value):
306
+ self.set(new_data=value, at_indices=key)
307
+
308
+ def set(
309
+ self,
310
+ new_data,
311
+ *,
312
+ at_indices: Optional[Union[int, slice, List[int]]] = None,
313
+ neg_index_as_lookback: bool = False,
314
+ ) -> None:
315
+ """Overwrites all or some of the data in this buffer with the provided data.
316
+
317
+ Args:
318
+ new_data: The new data to overwrite existing records with.
319
+ at_indices: A single int is interpreted as an index, at which to overwrite
320
+ the individual record stored at this index with `new_data`.
321
+ A list of ints is interpreted as a list of indices, which to overwrite
322
+ with `new_data`, which must be a batch of size `len(at_indices)`.
323
+ A slice object is interpreted as a range, which to overwrite with
324
+ `new_data`. Thereby, negative indices by default are interpreted as
325
+ "before the end" unless the `neg_index_as_lookback=True` option is
326
+ used, in which case negative indices are interpreted as
327
+ "before ts=0", meaning going back into the lookback buffer.
328
+ neg_index_as_lookback: If True, negative values in `at_indices` are
329
+ interpreted as "before ts=0", meaning going back into the lookback
330
+ buffer. For example, a buffer with data [4, 5, 6, 7, 8, 9],
331
+ where [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will
332
+ handle a call `set(99, at_indices=-1, neg_index_as_lookback=True)`
333
+ with `6` being replaced by 99 and to `set([98, 99, 100],
334
+ at_indices=slice(-2, 1), neg_index_as_lookback=True)` with
335
+ `[5, 6, 7]` being replaced by `[98, 99, 100]`.
336
+ """
337
+ # `at_indices` is None -> Override all our data (excluding the lookback buffer).
338
+ if at_indices is None:
339
+ self._set_all_data(new_data)
340
+
341
+ elif isinstance(at_indices, slice):
342
+ self._set_slice(
343
+ new_data,
344
+ slice_=at_indices,
345
+ neg_index_as_lookback=neg_index_as_lookback,
346
+ )
347
+ elif isinstance(at_indices, list):
348
+ for i, idx in enumerate(at_indices):
349
+ self._set_int_index(
350
+ new_data[i],
351
+ idx=idx,
352
+ neg_index_as_lookback=neg_index_as_lookback,
353
+ )
354
+ else:
355
+ assert isinstance(at_indices, int)
356
+ self._set_int_index(
357
+ new_data,
358
+ idx=at_indices,
359
+ neg_index_as_lookback=neg_index_as_lookback,
360
+ )
361
+
362
+ def __len__(self):
363
+ """Return the length of our data, excluding the lookback buffer."""
364
+ len_ = self.len_incl_lookback()
365
+ # Only count the data after the lookback.
366
+ return max(len_ - self.lookback, 0)
367
+
368
+ def len_incl_lookback(self):
369
+ if self.finalized:
370
+ return len(tree.flatten(self.data)[0])
371
+ else:
372
+ return len(self.data)
373
+
374
+ def __repr__(self):
375
+ return (
376
+ f"{type(self).__name__}({self.data[:self.lookback]} <- "
377
+ f"lookback({self.lookback}) | {self.data[self.lookback:]})"
378
+ )
379
+
380
+ def _get_all_data(self, one_hot_discrete=False, _ignore_last_ts=False):
381
+ data = self[: (None if not _ignore_last_ts else -1)]
382
+ if one_hot_discrete:
383
+ data = self._one_hot(data, space_struct=self.space_struct)
384
+ return data
385
+
386
+ def _set_all_data(self, new_data):
387
+ self._set_slice(new_data, slice(0, None))
388
+
389
+ def _get_slice(
390
+ self,
391
+ slice_,
392
+ fill=None,
393
+ neg_index_as_lookback=False,
394
+ one_hot_discrete=False,
395
+ _ignore_last_ts=False,
396
+ _add_last_ts_value=None,
397
+ ):
398
+ data_to_use = self.data
399
+ if _ignore_last_ts:
400
+ if self.finalized:
401
+ data_to_use = tree.map_structure(lambda s: s[:-1], self.data)
402
+ else:
403
+ data_to_use = self.data[:-1]
404
+ if _add_last_ts_value is not None:
405
+ if self.finalized:
406
+ data_to_use = tree.map_structure(
407
+ lambda s, t: np.append(s, t),
408
+ data_to_use.copy(),
409
+ _add_last_ts_value,
410
+ )
411
+ else:
412
+ data_to_use = np.append(data_to_use.copy(), _add_last_ts_value)
413
+
414
+ slice_, slice_len, fill_left_count, fill_right_count = self._interpret_slice(
415
+ slice_,
416
+ neg_index_as_lookback,
417
+ len_self_plus_lookback=(
418
+ self.len_incl_lookback()
419
+ + int(_add_last_ts_value is not None)
420
+ - int(_ignore_last_ts)
421
+ ),
422
+ )
423
+
424
+ # Perform the actual slice.
425
+ data_slice = None
426
+ if slice_len > 0:
427
+ if self.finalized:
428
+ data_slice = tree.map_structure(lambda s: s[slice_], data_to_use)
429
+ else:
430
+ data_slice = data_to_use[slice_]
431
+
432
+ if one_hot_discrete:
433
+ data_slice = self._one_hot(data_slice, space_struct=self.space_struct)
434
+
435
+ # Data is shorter than the range requested -> Fill the rest with `fill` data.
436
+ if fill is not None and (fill_right_count > 0 or fill_left_count > 0):
437
+ if self.finalized:
438
+ if fill_left_count:
439
+ if self.space is None:
440
+ fill_batch = np.array([fill] * fill_left_count)
441
+ else:
442
+ fill_batch = get_dummy_batch_for_space(
443
+ self.space,
444
+ fill_value=fill,
445
+ batch_size=fill_left_count,
446
+ one_hot_discrete=one_hot_discrete,
447
+ )
448
+ if data_slice is not None:
449
+ data_slice = tree.map_structure(
450
+ lambda s0, s: np.concatenate([s0, s]),
451
+ fill_batch,
452
+ data_slice,
453
+ )
454
+ else:
455
+ data_slice = fill_batch
456
+ if fill_right_count:
457
+ if self.space is None:
458
+ fill_batch = np.array([fill] * fill_right_count)
459
+ else:
460
+ fill_batch = get_dummy_batch_for_space(
461
+ self.space,
462
+ fill_value=fill,
463
+ batch_size=fill_right_count,
464
+ one_hot_discrete=one_hot_discrete,
465
+ )
466
+ if data_slice is not None:
467
+ data_slice = tree.map_structure(
468
+ lambda s0, s: np.concatenate([s, s0]),
469
+ fill_batch,
470
+ data_slice,
471
+ )
472
+ else:
473
+ data_slice = fill_batch
474
+
475
+ else:
476
+ if self.space is None:
477
+ fill_batch = [fill]
478
+ else:
479
+ fill_batch = [
480
+ get_dummy_batch_for_space(
481
+ self.space,
482
+ fill_value=fill,
483
+ batch_size=0,
484
+ one_hot_discrete=one_hot_discrete,
485
+ )
486
+ ]
487
+ data_slice = (
488
+ fill_batch * fill_left_count
489
+ + (data_slice if data_slice is not None else [])
490
+ + fill_batch * fill_right_count
491
+ )
492
+
493
+ if data_slice is None:
494
+ if self.finalized:
495
+ return tree.map_structure(lambda s: s[slice_], data_to_use)
496
+ else:
497
+ return data_to_use[slice_]
498
+ return data_slice
499
+
500
+ def _set_slice(
501
+ self,
502
+ new_data,
503
+ slice_,
504
+ neg_index_as_lookback=False,
505
+ ):
506
+ slice_, _, _, _ = self._interpret_slice(slice_, neg_index_as_lookback)
507
+
508
+ # Check, whether the setting to new_data changes the length of self
509
+ # (it shouldn't). If it does, raise an error.
510
+ try:
511
+ if self.finalized:
512
+
513
+ def __set(s, n):
514
+ if self.space:
515
+ assert self.space.contains(n[0])
516
+ assert len(s[slice_]) == len(n)
517
+ s[slice_] = n
518
+
519
+ tree.map_structure(__set, self.data, new_data)
520
+ else:
521
+ assert len(self.data[slice_]) == len(new_data)
522
+ self.data[slice_] = new_data
523
+ except AssertionError:
524
+ raise IndexError(
525
+ f"Cannot `set()` value via at_indices={slice_} (option "
526
+ f"neg_index_as_lookback={neg_index_as_lookback})! Slice of data "
527
+ "does NOT have the same size as `new_data`."
528
+ )
529
+
530
+ def _get_int_index(
531
+ self,
532
+ idx: int,
533
+ fill=None,
534
+ neg_index_as_lookback=False,
535
+ one_hot_discrete=False,
536
+ _ignore_last_ts=False,
537
+ _add_last_ts_value=None,
538
+ ):
539
+ data_to_use = self.data
540
+ if _ignore_last_ts:
541
+ if self.finalized:
542
+ data_to_use = tree.map_structure(lambda s: s[:-1], self.data)
543
+ else:
544
+ data_to_use = self.data[:-1]
545
+ if _add_last_ts_value is not None:
546
+ if self.finalized:
547
+ data_to_use = tree.map_structure(
548
+ lambda s, last: np.append(s, last), data_to_use, _add_last_ts_value
549
+ )
550
+ else:
551
+ data_to_use = data_to_use.copy()
552
+ data_to_use.append(_add_last_ts_value)
553
+
554
+ # If index >= 0 -> Ignore lookback buffer.
555
+ # Otherwise, include lookback buffer.
556
+ if idx >= 0 or neg_index_as_lookback:
557
+ idx = self.lookback + idx
558
+ # Negative indices mean: Go to left into lookback buffer starting from idx=0.
559
+ # But if we pass the lookback buffer, the index should be invalid and we will
560
+ # have to fill, if required. Invalidate the index by setting it to one larger
561
+ # than max.
562
+ if neg_index_as_lookback and idx < 0:
563
+ idx = len(self) + self.lookback - (_ignore_last_ts is True)
564
+
565
+ try:
566
+ if self.finalized:
567
+ data = tree.map_structure(lambda s: s[idx], data_to_use)
568
+ else:
569
+ data = data_to_use[idx]
570
+ # Out of range index -> If `fill`, use a fill dummy (B=0), if not, error out.
571
+ except IndexError as e:
572
+ if fill is not None:
573
+ if self.space is None:
574
+ return fill
575
+ return get_dummy_batch_for_space(
576
+ self.space,
577
+ fill_value=fill,
578
+ batch_size=0,
579
+ one_hot_discrete=one_hot_discrete,
580
+ )
581
+ else:
582
+ raise e
583
+
584
+ # Convert discrete/multi-discrete components to one-hot vectors, if required.
585
+ if one_hot_discrete:
586
+ data = self._one_hot(data, self.space_struct)
587
+ return data
588
+
589
+ def _set_int_index(self, new_data, idx, neg_index_as_lookback):
590
+ actual_idx = idx
591
+ # If index >= 0 -> Ignore lookback buffer.
592
+ # Otherwise, include lookback buffer.
593
+ if actual_idx >= 0 or neg_index_as_lookback:
594
+ actual_idx = self.lookback + actual_idx
595
+ # Negative indices mean: Go to left into lookback buffer starting from idx=0.
596
+ # But if we pass the lookback buffer, the index should be invalid and we will
597
+ # have to fill, if required. Invalidate the index by setting it to one larger
598
+ # than max.
599
+ if neg_index_as_lookback and actual_idx < 0:
600
+ actual_idx = len(self) + self.lookback
601
+
602
+ try:
603
+ if self.finalized:
604
+
605
+ def __set(s, n):
606
+ if self.space:
607
+ assert self.space.contains(n), n
608
+ s[actual_idx] = n
609
+
610
+ tree.map_structure(__set, self.data, new_data)
611
+ else:
612
+ self.data[actual_idx] = new_data
613
+ except IndexError:
614
+ raise IndexError(
615
+ f"Cannot `set()` value at index {idx} (option "
616
+ f"neg_index_as_lookback={neg_index_as_lookback})! Out of range "
617
+ f"of buffer data."
618
+ )
619
+
620
+ def _interpret_slice(
621
+ self,
622
+ slice_,
623
+ neg_index_as_lookback,
624
+ len_self_plus_lookback=None,
625
+ ):
626
+ if len_self_plus_lookback is None:
627
+ len_self_plus_lookback = len(self) + self.lookback
628
+
629
+ # Re-interpret slice bounds as absolute positions (>=0) within our
630
+ # internal data.
631
+ start = slice_.start
632
+ stop = slice_.stop
633
+
634
+ # Start is None -> Exclude lookback buffer.
635
+ if start is None:
636
+ start = self.lookback
637
+ # Start is negative.
638
+ elif start < 0:
639
+ # `neg_index_as_lookback=True` -> User wants to index into the lookback
640
+ # range.
641
+ if neg_index_as_lookback:
642
+ start = self.lookback + start
643
+ # Interpret index as counting "from end".
644
+ else:
645
+ start = len_self_plus_lookback + start
646
+ # Start is 0 or positive -> timestep right after lookback is interpreted as 0.
647
+ else:
648
+ start = self.lookback + start
649
+
650
+ # Stop is None -> Set stop to very last index + 1 of our internal data.
651
+ if stop is None:
652
+ stop = len_self_plus_lookback
653
+ # Stop is negative.
654
+ elif stop < 0:
655
+ # `neg_index_as_lookback=True` -> User wants to index into the lookback
656
+ # range. Set to 0 (beginning of lookback buffer) if result is a negative
657
+ # index.
658
+ if neg_index_as_lookback:
659
+ stop = self.lookback + stop
660
+ # Interpret index as counting "from end". Set to 0 (beginning of actual
661
+ # episode) if result is a negative index.
662
+ else:
663
+ stop = len_self_plus_lookback + stop
664
+ # Stop is positive -> Add lookback range to it.
665
+ else:
666
+ stop = self.lookback + stop
667
+
668
+ fill_left_count = fill_right_count = 0
669
+ # Both start and stop are on left side.
670
+ if start < 0 and stop < 0:
671
+ fill_left_count = abs(start - stop)
672
+ fill_right_count = 0
673
+ start = stop = 0
674
+ # Both start and stop are on right side.
675
+ elif start >= len_self_plus_lookback and stop >= len_self_plus_lookback:
676
+ fill_right_count = abs(start - stop)
677
+ fill_left_count = 0
678
+ start = stop = len_self_plus_lookback
679
+ # Set to 0 (beginning of actual episode) if result is a negative index.
680
+ elif start < 0:
681
+ fill_left_count = -start
682
+ start = 0
683
+ elif stop >= len_self_plus_lookback:
684
+ fill_right_count = stop - len_self_plus_lookback
685
+ stop = len_self_plus_lookback
686
+ # Only `stop` might be < 0, when slice has negative step and start is > 0.
687
+ elif stop < 0:
688
+ if start >= len_self_plus_lookback:
689
+ fill_left_count = start - len_self_plus_lookback + 1
690
+ start = len_self_plus_lookback - 1
691
+ fill_right_count = -stop - 1
692
+ stop = -LARGE_INTEGER
693
+
694
+ assert start >= 0 and (stop >= 0 or stop == -LARGE_INTEGER), (start, stop)
695
+
696
+ step = slice_.step if slice_.step is not None else 1
697
+ slice_ = slice(start, stop, step)
698
+ slice_len = max(0, (stop - start + (step - (1 if step > 0 else -1))) // step)
699
+ return slice_, slice_len, fill_left_count, fill_right_count
700
+
701
+ def _one_hot(self, data, space_struct):
702
+ if space_struct is None:
703
+ raise ValueError(
704
+ f"Cannot `one_hot` data in `{type(self).__name__}` if a "
705
+ "gym.Space was NOT provided during construction!"
706
+ )
707
+
708
+ def _convert(dat_, space):
709
+ if isinstance(space, gym.spaces.Discrete):
710
+ return one_hot(dat_, depth=space.n)
711
+ elif isinstance(space, gym.spaces.MultiDiscrete):
712
+ return one_hot_multidiscrete(dat_, depths=space.nvec)
713
+ return dat_
714
+
715
+ if isinstance(data, list):
716
+ data = [
717
+ tree.map_structure(_convert, dslice, space_struct) for dslice in data
718
+ ]
719
+ else:
720
+ data = tree.map_structure(_convert, data, space_struct)
721
+ return data
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__init__.py ADDED
File without changes
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (190 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/registration.cpython-312.pyc ADDED
Binary file (3.81 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/sync_vector_multi_agent_env.cpython-312.pyc ADDED
Binary file (12.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/__pycache__/vector_multi_agent_env.cpython-312.pyc ADDED
Binary file (4.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/registration.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import gymnasium as gym
3
+ import logging
4
+
5
+ from gymnasium.envs.registration import VectorizeMode
6
+ from typing import Any, Dict, Optional
7
+
8
+ from ray.rllib.env.multi_agent_env import MultiAgentEnv
9
+ from ray.rllib.env.vector.sync_vector_multi_agent_env import SyncVectorMultiAgentEnv
10
+ from ray.rllib.env.vector.vector_multi_agent_env import VectorMultiAgentEnv
11
+
12
+ logger = logging.getLogger(__file__)
13
+
14
+
15
+ def make_vec(
16
+ id: str,
17
+ num_envs: int = 1,
18
+ vectorization_mode: Optional[VectorizeMode] = None,
19
+ vector_kwargs: Optional[Dict[str, Any]] = None,
20
+ # TODO (simon): Add wrappers?
21
+ **kwargs,
22
+ ) -> VectorMultiAgentEnv:
23
+
24
+ if vector_kwargs is None:
25
+ vector_kwargs = {}
26
+
27
+ if vectorization_mode is None:
28
+ vectorization_mode = "sync"
29
+
30
+ # Create an `gymnasium.envs.registration.EnvSpec` to properly
31
+ # initialize the sub-environments.
32
+ if isinstance(id, gym.envs.registration.EnvSpec):
33
+ env_spec = id
34
+ elif isinstance(id, str):
35
+ env_spec = gym.envs.registration._find_spec(id)
36
+ else:
37
+ raise ValueError(f"Invalid id type: {type(id)}. Expected `str` or `EnvSpec`.")
38
+
39
+ env_spec = copy.deepcopy(env_spec)
40
+ env_spec_kwargs = env_spec.kwargs
41
+ env_spec.kwargs = dict()
42
+
43
+ num_envs = env_spec.kwargs.get("num_envs", num_envs)
44
+ vectorization_mode = env_spec_kwargs.pop("vectorization_mode", vectorization_mode)
45
+ vector_kwargs = env_spec_kwargs.pop("vector_kwargs", vector_kwargs)
46
+ env_spec_kwargs.update(kwargs)
47
+
48
+ # Specify the vectorization mode.
49
+ if vectorization_mode is None:
50
+ vectorization_mode = VectorizeMode.SYNC
51
+ else:
52
+ try:
53
+ vectorization_mode = VectorizeMode(vectorization_mode)
54
+ except ValueError:
55
+ raise ValueError(
56
+ f"Invalid vectorization mode: {vectorization_mode!r}, "
57
+ f"valid modes: {[mode.value for mode in VectorizeMode]}."
58
+ )
59
+ assert isinstance(vectorization_mode, VectorizeMode)
60
+
61
+ def create_single_env() -> MultiAgentEnv:
62
+ single_env = gym.make(env_spec, **env_spec_kwargs.copy())
63
+
64
+ return single_env
65
+
66
+ # Check, the vectorization mode.
67
+ if vectorization_mode == VectorizeMode.SYNC:
68
+ # Create the synchronized vector environemnt.
69
+ env = SyncVectorMultiAgentEnv(
70
+ env_fns=(create_single_env for _ in range(num_envs)),
71
+ **vector_kwargs,
72
+ )
73
+ # Other modes are not implemented, yet.
74
+ else:
75
+ raise ValueError(
76
+ "For `MultiAgentEnv` only synchronous environment vectorization "
77
+ "is implemented. Use `gym_env_vectorize_mode='sync'`."
78
+ )
79
+
80
+ # Add all creation specifications to the environment.
81
+ copied_id_spec = copy.deepcopy(env_spec)
82
+ copied_id_spec.kwargs = env_spec_kwargs.copy()
83
+ if num_envs != 1:
84
+ copied_id_spec.kwargs["num_envs"] = num_envs
85
+ copied_id_spec.kwargs["vectorization_mode"] = vectorization_mode.value
86
+ if len(vector_kwargs) > 0:
87
+ copied_id_spec.kwargs["vector_kwargs"] = vector_kwargs
88
+ env.unwrapped.spec = copied_id_spec
89
+
90
+ # Return the `VectorMultiAgentEnv`.
91
+ return env
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/sync_vector_multi_agent_env.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gymnasium as gym
2
+ import numpy as np
3
+
4
+ from copy import deepcopy
5
+ from gymnasium.core import ActType, RenderFrame
6
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, Union
7
+
8
+ from ray.rllib.env.multi_agent_env import MultiAgentEnv
9
+ from ray.rllib.env.vector.vector_multi_agent_env import ArrayType, VectorMultiAgentEnv
10
+ from ray.rllib.utils.typing import AgentID
11
+
12
+
13
+ class SyncVectorMultiAgentEnv(VectorMultiAgentEnv):
14
+ def __init__(
15
+ self,
16
+ env_fns: Union[
17
+ Iterator[Callable[[], MultiAgentEnv]], Sequence[Callable[[], MultiAgentEnv]]
18
+ ],
19
+ copy: bool = True,
20
+ autoreset_mode: str = "next_step",
21
+ ):
22
+ super().__init__()
23
+
24
+ self.env_fns = env_fns
25
+ self.copy = copy
26
+ self.autoreset_mode = autoreset_mode
27
+
28
+ # Initialize all sub-environments.
29
+ self.envs = [env_fn() for env_fn in self.env_fns]
30
+
31
+ self.num_envs = len(self.envs)
32
+ self.metadata = self.envs[0].metadata
33
+ self.metadata["autoreset_mode"] = self.autoreset_mode
34
+ self.render_mode = self.envs[0].render_mode
35
+
36
+ if self.envs[0].unwrapped.observation_spaces is not None:
37
+ self.single_observation_spaces = self.envs[0].unwrapped.observation_spaces
38
+ elif self.envs[0].unwrapped.observation_space is not None:
39
+ self.single_observation_spaces = dict(
40
+ self.envs[0].unwrapped.observation_space
41
+ )
42
+ else:
43
+ self.single_observation_spaces = {
44
+ aid: self.envs[0].unwrapped.get_observation_space(aid)
45
+ for aid in self.envs[0].unwrapped.possible_agents
46
+ }
47
+ self.single_observation_space = gym.spaces.Dict(self.single_observation_spaces)
48
+
49
+ if self.envs[0].unwrapped.action_spaces is not None:
50
+ self.single_action_spaces = self.envs[0].unwrapped.action_spaces
51
+ elif self.envs[0].unwrapped.action_space is not None:
52
+ self.single_action_spaces = dict(self.envs[0].unwrapped.action_space)
53
+ else:
54
+ self.single_action_spaces = {
55
+ aid: self.envs[0].unwrapped.get_action_space(aid)
56
+ for aid in self.envs[0].unwrapped.possible_agents
57
+ }
58
+ self.single_action_space = gym.spaces.Dict(self.single_action_spaces)
59
+
60
+ # TODO (simon): Decide if we want to include a spaces check here.
61
+
62
+ # Note, if `single_observation_spaces` are not defined, this will
63
+ # raise an error.
64
+ self._observations = self.create_empty_array(
65
+ self.single_observation_spaces,
66
+ n=self.num_envs,
67
+ )
68
+ self._rewards = [{} for _ in range(self.num_envs)]
69
+ self._terminations = [{} for _ in range(self.num_envs)]
70
+ self._truncations = [{} for _ in range(self.num_envs)]
71
+ self._infos = [{} for _ in range(self.num_envs)]
72
+
73
+ def reset(
74
+ self, *, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None
75
+ ) -> Tuple[ArrayType, ArrayType]:
76
+
77
+ # Check the `seed`.
78
+ if seed is None:
79
+ seed = [None for _ in range(self.num_envs)]
80
+ elif isinstance(seed, int):
81
+ seed = [seed + i for i in range(self.num_envs)]
82
+ # If `seed` is a sequence, check if length is correct.
83
+ else:
84
+ assert len(seed) == self.num_envs, (
85
+ f"If seeds are passed as a list the length must match num_envs={self.num_envs} "
86
+ f"but got length={len(seed)}.",
87
+ )
88
+
89
+ # Set auto-reset to `False` for all sub-environments. This will be
90
+ # set to `True` during `VectorMultiAgentEnv.step`.
91
+ self._autoreset_envs = np.zeros((self.num_envs,), dtype=np.bool_)
92
+
93
+ # Force reset on all sub-environments.
94
+ for i, (env, single_seed) in enumerate(zip(self.envs, seed)):
95
+ self._observations[i], self._infos[i] = env.reset(
96
+ seed=single_seed, options=options
97
+ )
98
+
99
+ return (
100
+ deepcopy(self._observations) if self.copy else self._observations,
101
+ self._infos,
102
+ )
103
+
104
+ def step(
105
+ self, actions: List[Dict[AgentID, ActType]]
106
+ ) -> Tuple[ArrayType, ArrayType, ArrayType, ArrayType, ArrayType]:
107
+
108
+ for i, action in enumerate(actions):
109
+ # Note, this will be a feature coming in `gymnasium`s next release.
110
+ if self.autoreset_mode == "next_step":
111
+ # Auto-reset environments that terminated or truncated.
112
+ if self._autoreset_envs[i]:
113
+ self._observations[i], self._infos[i] = self.envs[i].reset()
114
+
115
+ self._rewards[i] = {
116
+ aid: 0.0 for aid in self.envs[i].unwrapped.possible_agents
117
+ }
118
+ self._terminations[i] = {
119
+ aid: False for aid in self.envs[i].unwrapped.possible_agents
120
+ }
121
+ self._truncations[i] = {
122
+ aid: False for aid in self.envs[i].unwrapped.possible_agents
123
+ }
124
+ # Note, this needs to be added for `MultiAgentEpisode`s to work.
125
+ self._terminations[i].update({"__all__": False})
126
+ self._truncations[i].update({"__all__": False})
127
+ # Otherwise make a regular step.
128
+ else:
129
+ (
130
+ self._observations[i],
131
+ self._rewards[i],
132
+ self._terminations[i],
133
+ self._truncations[i],
134
+ self._infos[i],
135
+ ) = self.envs[i].step(action)
136
+ # Other autoreset modes are not implemented, yet.
137
+ else:
138
+ raise ValueError(f"Unexpected autoreset mode: {self.autoreset_mode}")
139
+
140
+ # Is any sub-environment terminated or truncated?
141
+ self._autoreset_envs = np.logical_or(
142
+ np.array([t["__all__"] for t in self._terminations]),
143
+ # Note, some environments just return `terminated`.
144
+ np.array([t.get("__all__", False) for t in self._truncations]),
145
+ )
146
+
147
+ return (
148
+ deepcopy(self._observations) if self.copy else self._observations,
149
+ np.copy(self._rewards),
150
+ np.copy(self._terminations),
151
+ np.copy(self._truncations),
152
+ np.copy(self._infos),
153
+ )
154
+
155
+ def render(self) -> Optional[Tuple[RenderFrame, ...]]:
156
+ """Returns the rendered frames from all environments."""
157
+ return tuple(env.render() for env in self.envs)
158
+
159
+ def call(self, name: str, *args: Any, **kwargs: Any) -> tuple[Any, ...]:
160
+ """Calls a sub-environment method with name and applies args and kwargs.
161
+
162
+ Args:
163
+ name: The method name
164
+ *args: The method args
165
+ **kwargs: The method kwargs
166
+
167
+ Returns:
168
+ Tuple of results
169
+ """
170
+ results = []
171
+ for env in self.envs:
172
+ function = env.get_wrapper_attr(name)
173
+
174
+ if callable(function):
175
+ results.append(function(*args, **kwargs))
176
+ else:
177
+ results.append(function)
178
+
179
+ return tuple(results)
180
+
181
+ def get_attr(self, name: str) -> tuple[Any, ...]:
182
+ """Get a property from each parallel environment.
183
+
184
+ Args:
185
+ name: Name of the property to get from each individual environment.
186
+
187
+ Returns:
188
+ The property with name
189
+ """
190
+ return self.call(name)
191
+
192
+ def close_extras(self, **kwargs):
193
+ """Close all environments."""
194
+ if hasattr(self, "envs"):
195
+ [env.close() for env in self.envs]
196
+
197
+ @property
198
+ def np_random_seed(self) -> Tuple[int, ...]:
199
+ """Returns a tuple of random seeds for the wrapped envs."""
200
+ return self.get_attr("np_random_seed")
201
+
202
+ @property
203
+ def np_random(self) -> Tuple[np.random.Generator, ...]:
204
+ """Returns a tuple of numpy random generators for the wrapped envs."""
205
+ return self.get_attr("np_random")
206
+
207
+ # TODO (simon): Move to space_utils.
208
+ def create_empty_array(
209
+ self, space: Dict[str, gym.Space], n: int = 1
210
+ ) -> List[Dict[str, gym.Space]]:
211
+
212
+ return [
213
+ {aid: agent_space.sample() for aid, agent_space in space.items()}
214
+ for _ in range(n)
215
+ ]
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector/vector_multi_agent_env.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Tuple, TypeVar
2
+
3
+ import gymnasium as gym
4
+ from gymnasium.core import RenderFrame
5
+ from gymnasium.envs.registration import EnvSpec
6
+ from gymnasium.utils import seeding
7
+ import numpy as np
8
+
9
+
10
+ ArrayType = TypeVar("ArrayType")
11
+
12
+
13
+ class VectorMultiAgentEnv:
14
+
15
+ metadata: Dict[str, Any] = {}
16
+ spec: Optional[EnvSpec] = None
17
+ render_mode: Optional[str] = None
18
+ closed: bool = False
19
+
20
+ envs: Optional[List] = None
21
+
22
+ # TODO (simon, sven): We could think about enabling here different
23
+ # spaces for different envs (e.g. different high/lows). In this
24
+ # case we would need here actually "batched" spaces and not a
25
+ # single on that holds for all sub-envs.
26
+ single_observation_spaces: Optional[Dict[str, gym.Space]] = None
27
+ single_action_spaces: Optional[Dict[str, gym.Space]] = None
28
+ # Note, the proper `gym` spaces are needed for the connector pipeline.
29
+ single_observation_space: Optional[gym.spaces.Dict] = None
30
+ single_action_space: Optional[gym.spaces.Dict] = None
31
+
32
+ num_envs: int
33
+
34
+ _np_random: Optional[np.random.Generator] = None
35
+ _np_random_seed: Optional[int] = None
36
+
37
+ # @OldAPIStack, use `observation_spaces` and `action_spaces`, instead.
38
+ observation_space: Optional[gym.Space] = None
39
+ action_space: Optional[gym.Space] = None
40
+
41
+ # TODO (simon): Add docstrings, when final design is clear.
42
+ def reset(
43
+ self, *, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None
44
+ ) -> Tuple[ArrayType, ArrayType]:
45
+ # Set random generators with the provided seeds.
46
+ if seed is not None:
47
+ self._np_random, self._np_random_seed = seeding.np_random(seed)
48
+
49
+ def step(
50
+ self, actions: ArrayType
51
+ ) -> Tuple[ArrayType, ArrayType, ArrayType, ArrayType, ArrayType]:
52
+ raise NotImplementedError(f"{self.__str__()} step function is not implemented.")
53
+
54
+ def render(self) -> Optional[Tuple[RenderFrame, ...]]:
55
+ raise NotImplementedError(
56
+ f"{self.__str__()} render function is not implemented."
57
+ )
58
+
59
+ def close(self, **kwargs: Any):
60
+
61
+ # If already closed, there is nothing more to do.
62
+ if self.closed:
63
+ return
64
+
65
+ # Otherwise close environments gracefully.
66
+ self.close_extras(**kwargs)
67
+ self.closed = True
68
+
69
+ def close_extras(self, **kwargs: Any):
70
+ # Users must not implement this.
71
+ pass
72
+
73
+ @property
74
+ def unwrapped(self):
75
+ return self
76
+
77
+ def __del__(self):
78
+ # Close environemnts, if necessary when deleting instances.
79
+ if not getattr(self, "closed", True):
80
+ self.close()
81
+
82
+ def __repr__(self):
83
+ if self.spec is None:
84
+ return f"{self.__class__.__name__}(num_envs={self.num_envs})"
85
+ else:
86
+ return (
87
+ f"{self.__class__.__name__}({self.spec.id}, num_envs={self.num_envs})"
88
+ )
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__init__.py ADDED
File without changes
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (192 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/atari_wrappers.cpython-312.pyc ADDED
Binary file (21.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_control_wrapper.cpython-312.pyc ADDED
Binary file (12.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/dm_env_wrapper.cpython-312.pyc ADDED
Binary file (5.01 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/group_agents_wrapper.cpython-312.pyc ADDED
Binary file (7.26 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/multi_agent_env_compatibility.cpython-312.pyc ADDED
Binary file (3.84 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/open_spiel.cpython-312.pyc ADDED
Binary file (6.92 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/pettingzoo_env.cpython-312.pyc ADDED
Binary file (10.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/__pycache__/unity3d_env.cpython-312.pyc ADDED
Binary file (12 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/wrappers/atari_wrappers.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ import gymnasium as gym
3
+ from gymnasium import spaces
4
+ import numpy as np
5
+ from typing import Optional, Union
6
+
7
+ from ray.rllib.utils.annotations import PublicAPI
8
+ from ray.rllib.utils.images import rgb2gray, resize
9
+
10
+
11
+ @PublicAPI
12
+ def is_atari(env: Union[gym.Env, str]) -> bool:
13
+ """Returns, whether a given env object or env descriptor (str) is an Atari env.
14
+
15
+ Args:
16
+ env: The gym.Env object or a string descriptor of the env (for example,
17
+ "ale_py:ALE/Pong-v5").
18
+
19
+ Returns:
20
+ Whether `env` is an Atari environment.
21
+ """
22
+ # If a gym.Env, check proper spaces as well as occurrence of the "Atari<ALE" string
23
+ # in the class name.
24
+ if not isinstance(env, str):
25
+ if (
26
+ hasattr(env.observation_space, "shape")
27
+ and env.observation_space.shape is not None
28
+ and len(env.observation_space.shape) <= 2
29
+ ):
30
+ return False
31
+ return "AtariEnv<ALE" in str(env)
32
+ # If string, check for "ale_py:ALE/" prefix.
33
+ else:
34
+ return env.startswith("ALE/") or env.startswith("ale_py:")
35
+
36
+
37
+ @PublicAPI
38
+ def get_wrapper_by_cls(env, cls):
39
+ """Returns the gym env wrapper of the given class, or None."""
40
+ currentenv = env
41
+ while True:
42
+ if isinstance(currentenv, cls):
43
+ return currentenv
44
+ elif isinstance(currentenv, gym.Wrapper):
45
+ currentenv = currentenv.env
46
+ else:
47
+ return None
48
+
49
+
50
+ @PublicAPI
51
+ class ClipRewardEnv(gym.RewardWrapper):
52
+ def __init__(self, env):
53
+ gym.RewardWrapper.__init__(self, env)
54
+
55
+ def reward(self, reward):
56
+ """Bin reward to {+1, 0, -1} by its sign."""
57
+ return np.sign(reward)
58
+
59
+
60
+ @PublicAPI
61
+ class EpisodicLifeEnv(gym.Wrapper):
62
+ def __init__(self, env):
63
+ """Make end-of-life == end-of-episode, but only reset on true game over.
64
+ Done by DeepMind for the DQN and co. since it helps value estimation.
65
+ """
66
+ gym.Wrapper.__init__(self, env)
67
+ self.lives = 0
68
+ self.was_real_terminated = True
69
+
70
+ def step(self, action):
71
+ obs, reward, terminated, truncated, info = self.env.step(action)
72
+ self.was_real_terminated = terminated
73
+ # check current lives, make loss of life terminal,
74
+ # then update lives to handle bonus lives
75
+ lives = self.env.unwrapped.ale.lives()
76
+ if lives < self.lives and lives > 0:
77
+ # for Qbert sometimes we stay in lives == 0 condtion for a few fr
78
+ # so its important to keep lives > 0, so that we only reset once
79
+ # the environment advertises `terminated`.
80
+ terminated = True
81
+ self.lives = lives
82
+ return obs, reward, terminated, truncated, info
83
+
84
+ def reset(self, **kwargs):
85
+ """Reset only when lives are exhausted.
86
+ This way all states are still reachable even though lives are episodic,
87
+ and the learner need not know about any of this behind-the-scenes.
88
+ """
89
+ if self.was_real_terminated:
90
+ obs, info = self.env.reset(**kwargs)
91
+ else:
92
+ # no-op step to advance from terminal/lost life state
93
+ obs, _, _, _, info = self.env.step(0)
94
+ self.lives = self.env.unwrapped.ale.lives()
95
+ return obs, info
96
+
97
+
98
+ @PublicAPI
99
+ class FireResetEnv(gym.Wrapper):
100
+ def __init__(self, env):
101
+ """Take action on reset.
102
+
103
+ For environments that are fixed until firing."""
104
+ gym.Wrapper.__init__(self, env)
105
+ assert env.unwrapped.get_action_meanings()[1] == "FIRE"
106
+ assert len(env.unwrapped.get_action_meanings()) >= 3
107
+
108
+ def reset(self, **kwargs):
109
+ self.env.reset(**kwargs)
110
+ obs, _, terminated, truncated, _ = self.env.step(1)
111
+ if terminated or truncated:
112
+ self.env.reset(**kwargs)
113
+ obs, _, terminated, truncated, info = self.env.step(2)
114
+ if terminated or truncated:
115
+ self.env.reset(**kwargs)
116
+ return obs, info
117
+
118
+ def step(self, ac):
119
+ return self.env.step(ac)
120
+
121
+
122
+ @PublicAPI
123
+ class FrameStack(gym.Wrapper):
124
+ def __init__(self, env, k):
125
+ """Stack k last frames."""
126
+ gym.Wrapper.__init__(self, env)
127
+ self.k = k
128
+ self.frames = deque([], maxlen=k)
129
+ shp = env.observation_space.shape
130
+ self.observation_space = spaces.Box(
131
+ low=np.repeat(env.observation_space.low, repeats=k, axis=-1),
132
+ high=np.repeat(env.observation_space.high, repeats=k, axis=-1),
133
+ shape=(shp[0], shp[1], shp[2] * k),
134
+ dtype=env.observation_space.dtype,
135
+ )
136
+
137
+ def reset(self, *, seed=None, options=None):
138
+ ob, infos = self.env.reset(seed=seed, options=options)
139
+ for _ in range(self.k):
140
+ self.frames.append(ob)
141
+ return self._get_ob(), infos
142
+
143
+ def step(self, action):
144
+ ob, reward, terminated, truncated, info = self.env.step(action)
145
+ self.frames.append(ob)
146
+ return self._get_ob(), reward, terminated, truncated, info
147
+
148
+ def _get_ob(self):
149
+ assert len(self.frames) == self.k
150
+ return np.concatenate(self.frames, axis=2)
151
+
152
+
153
+ @PublicAPI
154
+ class FrameStackTrajectoryView(gym.ObservationWrapper):
155
+ def __init__(self, env):
156
+ """No stacking. Trajectory View API takes care of this."""
157
+ gym.Wrapper.__init__(self, env)
158
+ shp = env.observation_space.shape
159
+ assert shp[2] == 1
160
+ self.observation_space = spaces.Box(
161
+ low=0, high=255, shape=(shp[0], shp[1]), dtype=env.observation_space.dtype
162
+ )
163
+
164
+ def observation(self, observation):
165
+ return np.squeeze(observation, axis=-1)
166
+
167
+
168
+ @PublicAPI
169
+ class MaxAndSkipEnv(gym.Wrapper):
170
+ def __init__(self, env, skip=4):
171
+ """Return only every `skip`-th frame"""
172
+ gym.Wrapper.__init__(self, env)
173
+ # most recent raw observations (for max pooling across time steps)
174
+ self._obs_buffer = np.zeros(
175
+ (2,) + env.observation_space.shape, dtype=env.observation_space.dtype
176
+ )
177
+ self._skip = skip
178
+
179
+ def step(self, action):
180
+ """Repeat action, sum reward, and max over last observations."""
181
+ total_reward = 0.0
182
+ terminated = truncated = info = None
183
+ for i in range(self._skip):
184
+ obs, reward, terminated, truncated, info = self.env.step(action)
185
+ if i == self._skip - 2:
186
+ self._obs_buffer[0] = obs
187
+ if i == self._skip - 1:
188
+ self._obs_buffer[1] = obs
189
+ total_reward += reward
190
+ if terminated or truncated:
191
+ break
192
+ # Note that the observation on the terminated|truncated=True frame
193
+ # doesn't matter
194
+ max_frame = self._obs_buffer.max(axis=0)
195
+
196
+ return max_frame, total_reward, terminated, truncated, info
197
+
198
+ def reset(self, **kwargs):
199
+ return self.env.reset(**kwargs)
200
+
201
+
202
+ @PublicAPI
203
+ class MonitorEnv(gym.Wrapper):
204
+ def __init__(self, env=None):
205
+ """Record episodes stats prior to EpisodicLifeEnv, etc."""
206
+ gym.Wrapper.__init__(self, env)
207
+ self._current_reward = None
208
+ self._num_steps = None
209
+ self._total_steps = None
210
+ self._episode_rewards = []
211
+ self._episode_lengths = []
212
+ self._num_episodes = 0
213
+ self._num_returned = 0
214
+
215
+ def reset(self, **kwargs):
216
+ obs, info = self.env.reset(**kwargs)
217
+
218
+ if self._total_steps is None:
219
+ self._total_steps = sum(self._episode_lengths)
220
+
221
+ if self._current_reward is not None:
222
+ self._episode_rewards.append(self._current_reward)
223
+ self._episode_lengths.append(self._num_steps)
224
+ self._num_episodes += 1
225
+
226
+ self._current_reward = 0
227
+ self._num_steps = 0
228
+
229
+ return obs, info
230
+
231
+ def step(self, action):
232
+ obs, rew, terminated, truncated, info = self.env.step(action)
233
+ self._current_reward += rew
234
+ self._num_steps += 1
235
+ self._total_steps += 1
236
+ return obs, rew, terminated, truncated, info
237
+
238
+ def get_episode_rewards(self):
239
+ return self._episode_rewards
240
+
241
+ def get_episode_lengths(self):
242
+ return self._episode_lengths
243
+
244
+ def get_total_steps(self):
245
+ return self._total_steps
246
+
247
+ def next_episode_results(self):
248
+ for i in range(self._num_returned, len(self._episode_rewards)):
249
+ yield (self._episode_rewards[i], self._episode_lengths[i])
250
+ self._num_returned = len(self._episode_rewards)
251
+
252
+
253
+ @PublicAPI
254
+ class NoopResetEnv(gym.Wrapper):
255
+ def __init__(self, env, noop_max=30):
256
+ """Sample initial states by taking random number of no-ops on reset.
257
+ No-op is assumed to be action 0.
258
+ """
259
+ gym.Wrapper.__init__(self, env)
260
+ self.noop_max = noop_max
261
+ self.override_num_noops = None
262
+ self.noop_action = 0
263
+ assert env.unwrapped.get_action_meanings()[0] == "NOOP"
264
+
265
+ def reset(self, **kwargs):
266
+ """Do no-op action for a number of steps in [1, noop_max]."""
267
+ self.env.reset(**kwargs)
268
+ if self.override_num_noops is not None:
269
+ noops = self.override_num_noops
270
+ else:
271
+ # This environment now uses the pcg64 random number generator which
272
+ # does not have `randint` as an attribute only has `integers`.
273
+ try:
274
+ noops = self.unwrapped.np_random.integers(1, self.noop_max + 1)
275
+ # Also still support older versions.
276
+ except AttributeError:
277
+ noops = self.unwrapped.np_random.randint(1, self.noop_max + 1)
278
+ assert noops > 0
279
+ obs = None
280
+ for _ in range(noops):
281
+ obs, _, terminated, truncated, info = self.env.step(self.noop_action)
282
+ if terminated or truncated:
283
+ obs, info = self.env.reset(**kwargs)
284
+ return obs, info
285
+
286
+ def step(self, ac):
287
+ return self.env.step(ac)
288
+
289
+
290
+ @PublicAPI
291
+ class NormalizedImageEnv(gym.ObservationWrapper):
292
+ def __init__(self, *args, **kwargs):
293
+ super().__init__(*args, **kwargs)
294
+ self.observation_space = gym.spaces.Box(
295
+ -1.0,
296
+ 1.0,
297
+ shape=self.observation_space.shape,
298
+ dtype=np.float32,
299
+ )
300
+
301
+ # Divide by scale and center around 0.0, such that observations are in the range
302
+ # of -1.0 and 1.0.
303
+ def observation(self, observation):
304
+ return (observation.astype(np.float32) / 128.0) - 1.0
305
+
306
+
307
+ @PublicAPI
308
+ class GrayScaleAndResize(gym.ObservationWrapper):
309
+ def __init__(self, env, dim, grayscale: bool = True):
310
+ """Warp frames to the specified size (dim x dim)."""
311
+ gym.ObservationWrapper.__init__(self, env)
312
+ self.width = dim
313
+ self.height = dim
314
+ self.grayscale = grayscale
315
+ self.observation_space = spaces.Box(
316
+ low=0,
317
+ high=255,
318
+ shape=(self.height, self.width, 1 if grayscale else 3),
319
+ dtype=np.uint8,
320
+ )
321
+
322
+ def observation(self, frame):
323
+ if self.grayscale:
324
+ frame = rgb2gray(frame)
325
+ frame = resize(frame, height=self.height, width=self.width)
326
+ return frame[:, :, None]
327
+ else:
328
+ return resize(frame, height=self.height, width=self.width)
329
+
330
+
331
+ WarpFrame = GrayScaleAndResize
332
+
333
+
334
+ @PublicAPI
335
+ def wrap_atari_for_new_api_stack(
336
+ env: gym.Env,
337
+ dim: int = 64,
338
+ frameskip: int = 4,
339
+ framestack: Optional[int] = None,
340
+ grayscale: bool = True,
341
+ # TODO (sven): Add option to NOT grayscale, in which case framestack must be None
342
+ # (b/c we are using the 3 color channels already as stacking frames).
343
+ ) -> gym.Env:
344
+ """Wraps `env` for new-API-stack-friendly RLlib Atari experiments.
345
+
346
+ Note that we assume reward clipping is done outside the wrapper.
347
+
348
+ Args:
349
+ env: The env object to wrap.
350
+ dim: Dimension to resize observations to (dim x dim).
351
+ frameskip: Whether to skip n frames and max over them (keep brightest pixels).
352
+ framestack: Whether to stack the last n (grayscaled) frames. Note that this
353
+ step happens after(!) a possible frameskip step, meaning that if
354
+ frameskip=4 and framestack=2, we would perform the following over this
355
+ trajectory:
356
+ actual env timesteps: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -> ...
357
+ frameskip: ( max ) ( max ) ( max ) ( max )
358
+ framestack: ( stack ) (stack )
359
+
360
+ Returns:
361
+ The wrapped gym.Env.
362
+ """
363
+ # Time limit.
364
+ env = gym.wrappers.TimeLimit(env, max_episode_steps=108000)
365
+ # Grayscale + resize.
366
+ env = WarpFrame(env, dim=dim, grayscale=grayscale)
367
+ # Normalize the image.
368
+ env = NormalizedImageEnv(env)
369
+ # Frameskip: Take max over these n frames.
370
+ if frameskip > 1:
371
+ assert env.spec is not None
372
+ env = MaxAndSkipEnv(env, skip=frameskip)
373
+ # Send n noop actions into env after reset to increase variance in the
374
+ # "start states" of the trajectories. These dummy steps are NOT included in the
375
+ # sampled data used for learning.
376
+ env = NoopResetEnv(env, noop_max=30)
377
+ # Each life is one episode.
378
+ env = EpisodicLifeEnv(env)
379
+ # Some envs only start playing after pressing fire. Unblock those.
380
+ if "FIRE" in env.unwrapped.get_action_meanings():
381
+ env = FireResetEnv(env)
382
+ # Framestack.
383
+ if framestack:
384
+ env = FrameStack(env, k=framestack)
385
+ return env
386
+
387
+
388
+ @PublicAPI
389
+ def wrap_deepmind(env, dim=84, framestack=True, noframeskip=False):
390
+ """Configure environment for DeepMind-style Atari.
391
+
392
+ Note that we assume reward clipping is done outside the wrapper.
393
+
394
+ Args:
395
+ env: The env object to wrap.
396
+ dim: Dimension to resize observations to (dim x dim).
397
+ framestack: Whether to framestack observations.
398
+ """
399
+ env = MonitorEnv(env)
400
+ env = NoopResetEnv(env, noop_max=30)
401
+ if env.spec is not None and noframeskip is True:
402
+ env = MaxAndSkipEnv(env, skip=4)
403
+ env = EpisodicLifeEnv(env)
404
+ if "FIRE" in env.unwrapped.get_action_meanings():
405
+ env = FireResetEnv(env)
406
+ env = WarpFrame(env, dim)
407
+ # env = ClipRewardEnv(env) # reward clipping is handled by policy eval
408
+ # 4x image framestacking.
409
+ if framestack is True:
410
+ env = FrameStack(env, 4)
411
+ return env