forked from ray-project/ray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolicy_client.py
424 lines (359 loc) · 13.9 KB
/
policy_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
"""REST client to interact with a policy server.
This client supports both local and remote policy inference modes. Local
inference is faster but causes more compute to be done on the client.
"""
import logging
import threading
import time
from typing import Union, Optional
from enum import Enum
import ray.cloudpickle as pickle
from ray.rllib.env.external_env import ExternalEnv
from ray.rllib.env.external_multi_agent_env import ExternalMultiAgentEnv
from ray.rllib.env.multi_agent_env import MultiAgentEnv
from ray.rllib.policy.sample_batch import MultiAgentBatch
from ray.rllib.utils.annotations import PublicAPI
from ray.rllib.utils.typing import (
MultiAgentDict,
EnvInfoDict,
EnvObsType,
EnvActionType,
)
logger = logging.getLogger(__name__)
try:
import requests # `requests` is not part of stdlib.
except ImportError:
requests = None
logger.warning(
"Couldn't import `requests` library. Be sure to install it on"
" the client side."
)
@PublicAPI
class Commands(Enum):
# Generic commands (for both modes).
ACTION_SPACE = "ACTION_SPACE"
OBSERVATION_SPACE = "OBSERVATION_SPACE"
# Commands for local inference mode.
GET_WORKER_ARGS = "GET_WORKER_ARGS"
GET_WEIGHTS = "GET_WEIGHTS"
REPORT_SAMPLES = "REPORT_SAMPLES"
# Commands for remote inference mode.
START_EPISODE = "START_EPISODE"
GET_ACTION = "GET_ACTION"
LOG_ACTION = "LOG_ACTION"
LOG_RETURNS = "LOG_RETURNS"
END_EPISODE = "END_EPISODE"
@PublicAPI
class PolicyClient:
"""REST client to interact with an RLlib policy server."""
@PublicAPI
def __init__(
self,
address: str,
inference_mode: str = "local",
update_interval: float = 10.0,
session: Optional[requests.Session] = None,
):
"""Create a PolicyClient instance.
Args:
address: Server to connect to (e.g., "localhost:9090").
inference_mode: Whether to use 'local' or 'remote' policy
inference for computing actions.
update_interval (float or None): If using 'local' inference mode,
the policy is refreshed after this many seconds have passed,
or None for manual control via client.
session (requests.Session or None): If available the session object
is used to communicate with the policy server. Using a session
can lead to speedups as connections are reused. It is the
responsibility of the creator of the session to close it.
"""
self.address = address
self.session = session
self.env: ExternalEnv = None
if inference_mode == "local":
self.local = True
self._setup_local_rollout_worker(update_interval)
elif inference_mode == "remote":
self.local = False
else:
raise ValueError("inference_mode must be either 'local' or 'remote'")
@PublicAPI
def start_episode(
self, episode_id: Optional[str] = None, training_enabled: bool = True
) -> str:
"""Record the start of one or more episode(s).
Args:
episode_id (Optional[str]): Unique string id for the episode or
None for it to be auto-assigned.
training_enabled: Whether to use experiences for this
episode to improve the policy.
Returns:
episode_id: Unique string id for the episode.
"""
if self.local:
self._update_local_policy()
return self.env.start_episode(episode_id, training_enabled)
return self._send(
{
"episode_id": episode_id,
"command": Commands.START_EPISODE,
"training_enabled": training_enabled,
}
)["episode_id"]
@PublicAPI
def get_action(
self, episode_id: str, observation: Union[EnvObsType, MultiAgentDict]
) -> Union[EnvActionType, MultiAgentDict]:
"""Record an observation and get the on-policy action.
Args:
episode_id: Episode id returned from start_episode().
observation: Current environment observation.
Returns:
action: Action from the env action space.
"""
if self.local:
self._update_local_policy()
if isinstance(episode_id, (list, tuple)):
actions = {
eid: self.env.get_action(eid, observation[eid])
for eid in episode_id
}
return actions
else:
return self.env.get_action(episode_id, observation)
else:
return self._send(
{
"command": Commands.GET_ACTION,
"observation": observation,
"episode_id": episode_id,
}
)["action"]
@PublicAPI
def log_action(
self,
episode_id: str,
observation: Union[EnvObsType, MultiAgentDict],
action: Union[EnvActionType, MultiAgentDict],
) -> None:
"""Record an observation and (off-policy) action taken.
Args:
episode_id: Episode id returned from start_episode().
observation: Current environment observation.
action: Action for the observation.
"""
if self.local:
self._update_local_policy()
return self.env.log_action(episode_id, observation, action)
self._send(
{
"command": Commands.LOG_ACTION,
"observation": observation,
"action": action,
"episode_id": episode_id,
}
)
@PublicAPI
def log_returns(
self,
episode_id: str,
reward: float,
info: Union[EnvInfoDict, MultiAgentDict] = None,
multiagent_done_dict: Optional[MultiAgentDict] = None,
) -> None:
"""Record returns from the environment.
The reward will be attributed to the previous action taken by the
episode. Rewards accumulate until the next action. If no reward is
logged before the next action, a reward of 0.0 is assumed.
Args:
episode_id: Episode id returned from start_episode().
reward: Reward from the environment.
info: Extra info dict.
multiagent_done_dict: Multi-agent done information.
"""
if self.local:
self._update_local_policy()
if multiagent_done_dict is not None:
assert isinstance(reward, dict)
return self.env.log_returns(
episode_id, reward, info, multiagent_done_dict
)
return self.env.log_returns(episode_id, reward, info)
self._send(
{
"command": Commands.LOG_RETURNS,
"reward": reward,
"info": info,
"episode_id": episode_id,
"done": multiagent_done_dict,
}
)
@PublicAPI
def end_episode(
self, episode_id: str, observation: Union[EnvObsType, MultiAgentDict]
) -> None:
"""Record the end of an episode.
Args:
episode_id: Episode id returned from start_episode().
observation: Current environment observation.
"""
if self.local:
self._update_local_policy()
return self.env.end_episode(episode_id, observation)
self._send(
{
"command": Commands.END_EPISODE,
"observation": observation,
"episode_id": episode_id,
}
)
@PublicAPI
def update_policy_weights(self) -> None:
"""Query the server for new policy weights, if local inference is enabled."""
self._update_local_policy(force=True)
def _send(self, data):
payload = pickle.dumps(data)
if self.session is None:
response = requests.post(self.address, data=payload)
else:
response = self.session.post(self.address, data=payload)
if response.status_code != 200:
logger.error("Request failed {}: {}".format(response.text, data))
response.raise_for_status()
parsed = pickle.loads(response.content)
return parsed
def _setup_local_rollout_worker(self, update_interval):
self.update_interval = update_interval
self.last_updated = 0
logger.info("Querying server for rollout worker settings.")
kwargs = self._send(
{
"command": Commands.GET_WORKER_ARGS,
}
)["worker_args"]
(self.rollout_worker, self.inference_thread) = _create_embedded_rollout_worker(
kwargs, self._send
)
self.env = self.rollout_worker.env
def _update_local_policy(self, force=False):
assert self.inference_thread.is_alive()
if (
self.update_interval
and time.time() - self.last_updated > self.update_interval
) or force:
logger.info("Querying server for new policy weights.")
resp = self._send(
{
"command": Commands.GET_WEIGHTS,
}
)
weights = resp["weights"]
global_vars = resp["global_vars"]
logger.info(
"Updating rollout worker weights and global vars {}.".format(
global_vars
)
)
self.rollout_worker.set_weights(weights, global_vars)
self.last_updated = time.time()
class _LocalInferenceThread(threading.Thread):
"""Thread that handles experience generation (worker.sample() loop)."""
def __init__(self, rollout_worker, send_fn):
super().__init__()
self.daemon = True
self.rollout_worker = rollout_worker
self.send_fn = send_fn
def run(self):
try:
while True:
logger.info("Generating new batch of experiences.")
samples = self.rollout_worker.sample()
metrics = self.rollout_worker.get_metrics()
if isinstance(samples, MultiAgentBatch):
logger.info(
"Sending batch of {} env steps ({} agent steps) to "
"server.".format(samples.env_steps(), samples.agent_steps())
)
else:
logger.info(
"Sending batch of {} steps back to server.".format(
samples.count
)
)
self.send_fn(
{
"command": Commands.REPORT_SAMPLES,
"samples": samples,
"metrics": metrics,
}
)
except Exception as e:
logger.error("Error: inference worker thread died!", e)
def _auto_wrap_external(real_env_creator):
"""Wrap an environment in the ExternalEnv interface if needed.
Args:
real_env_creator: Create an env given the env_config.
"""
def wrapped_creator(env_config):
real_env = real_env_creator(env_config)
if not isinstance(real_env, (ExternalEnv, ExternalMultiAgentEnv)):
logger.info(
"The env you specified is not a supported (sub-)type of "
"ExternalEnv. Attempting to convert it automatically to "
"ExternalEnv."
)
if isinstance(real_env, MultiAgentEnv):
external_cls = ExternalMultiAgentEnv
else:
external_cls = ExternalEnv
class _ExternalEnvWrapper(external_cls):
def __init__(self, real_env):
super().__init__(
observation_space=real_env.observation_space,
action_space=real_env.action_space,
)
def run(self):
# Since we are calling methods on this class in the
# client, run doesn't need to do anything.
time.sleep(999999)
return _ExternalEnvWrapper(real_env)
return real_env
return wrapped_creator
def _create_embedded_rollout_worker(kwargs, send_fn):
"""Create a local rollout worker and a thread that samples from it.
Args:
kwargs: Args for the RolloutWorker constructor.
send_fn: Function to send a JSON request to the server.
"""
# Since the server acts as an input datasource, we have to reset the
# input config to the default, which runs env rollouts.
kwargs = kwargs.copy()
kwargs["config"] = kwargs["config"].copy(copy_frozen=False)
config = kwargs["config"]
config.output = None
config.input_ = "sampler"
config.input_config = {}
# If server has no env (which is the expected case):
# Generate a dummy ExternalEnv here using RandomEnv and the
# given observation/action spaces.
if config.env is None:
from ray.rllib.examples.env.random_env import RandomEnv, RandomMultiAgentEnv
env_config = {
"action_space": config.action_space,
"observation_space": config.observation_space,
}
is_ma = config.is_multi_agent()
kwargs["env_creator"] = _auto_wrap_external(
lambda _: (RandomMultiAgentEnv if is_ma else RandomEnv)(env_config)
)
# kwargs["config"].env = True
# Otherwise, use the env specified by the server args.
else:
real_env_creator = kwargs["env_creator"]
kwargs["env_creator"] = _auto_wrap_external(real_env_creator)
logger.info("Creating rollout worker with kwargs={}".format(kwargs))
from ray.rllib.evaluation.rollout_worker import RolloutWorker
rollout_worker = RolloutWorker(**kwargs)
inference_thread = _LocalInferenceThread(rollout_worker, send_fn)
inference_thread.start()
return rollout_worker, inference_thread