-
Notifications
You must be signed in to change notification settings - Fork 188
/
batch_env.py
284 lines (219 loc) · 8.59 KB
/
batch_env.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
import multiprocessing as mp
from typing import Tuple, List, Dict
import numpy as np
from textworld.core import Environment
def _list_of_dicts_to_dict_of_lists(list_: List[Dict]) -> Dict[str, List]:
# Convert List[Dict] to Dict[List]
keys = set(key for dict_ in list_ for key in dict_)
return {key: [dict_.get(key) for dict_ in list_] for key in keys}
def _child(env_fn, parent_pipe, pipe):
"""
Event loop run by the child processes
"""
try:
parent_pipe.close()
env = env_fn()
while True:
command = pipe.recv()
# command is a tuple like ("call" | "get", "name.of.attr", extra args...)
obj = env
attrs = command[1].split(".")
for attr in attrs[:-1]:
obj = getattr(obj, attr)
if command[0] == "call":
fct = getattr(obj, attrs[-1])
result = fct(*command[2])
elif command[0] == "get":
result = getattr(obj, attrs[-1])
elif command[0] == "hasattr":
result = hasattr(obj, attrs[-1])
elif command[0] == "close":
break
pipe.send(result)
finally:
env.close()
pipe.close()
class _ChildEnv:
"""
Wrapper for an env in a child process.
"""
def __init__(self, env_fn):
self._pipe, child_pipe = mp.Pipe()
self._process = mp.Process(target=_child, args=(env_fn, self._pipe, child_pipe))
self._process.daemon = True
self._process.start()
child_pipe.close()
def call(self, method, *args):
self._pipe.send(("call", method, args))
def get(self, attr):
self._pipe.send(("get", attr))
def hasattr(self, attr):
self._pipe.send(("hasattr", attr))
def result(self):
return self._pipe.recv()
def call_sync(self, *args):
self.call(*args)
return self.result()
def get_sync(self, *args):
self.get(*args)
return self.result()
def hasattr_sync(self, *args):
self.hasattr(*args)
return self.result()
def __del__(self):
self.call_sync("close")
self._pipe.close()
self._process.terminate()
self._process.join()
class AsyncBatchEnv(Environment):
""" Environment to run multiple games in parallel asynchronously. """
def __init__(self, env_fns: List[callable], auto_reset: bool = False):
"""
Parameters
----------
env_fns : iterable of callable
Functions that create the environments.
"""
self.env_fns = env_fns
self.auto_reset = auto_reset
self.batch_size = len(self.env_fns)
self.envs = []
for env_fn in self.env_fns:
self.envs.append(_ChildEnv(env_fn))
def load(self, game_files: List[str]) -> None:
assert len(game_files) == len(self.envs)
for env, game_file in zip(self.envs, game_files):
env.call("load", game_file)
# Join
for env in self.envs:
env.result()
def seed(self, seed=None):
seeds = seed
if seeds is None or isinstance(seeds, int):
# Use a different seed for each env to decorrelate batch examples.
rng = np.random.RandomState(seeds)
seeds = list(rng.randint(65635, size=self.batch_size))
for env, seed in zip(self.envs, seeds):
env.call_sync("seed", seed)
return seeds
def reset(self) -> Tuple[List[str], Dict[str, List[str]]]:
"""
Reset all environments of the batch.
Returns:
obs: Text observations, i.e. command's feedback.
infos: Information requested when creating the environments.
"""
self.last = [None] * self.batch_size
for env in self.envs:
env.call("reset")
results = [env.result() for env in self.envs]
obs, infos = zip(*results)
infos = _list_of_dicts_to_dict_of_lists(infos)
return obs, infos
def step(self, actions: List[str]) -> Tuple[List[str], int, bool, Dict[str, List[str]]]:
"""
Perform one action per environment of the batch.
Returns:
obs: Text observations, i.e. command's feedback.
reward: Current game score.
done: Whether the game is over or not.
infos: Information requested when creating the environments.
"""
assert isinstance(actions, (list, tuple)), "Expected a list of actions."
assert len(actions) == len(self.envs), "Expected one action per environment."
results = []
for i, (env, action) in enumerate(zip(self.envs, actions)):
if self.last[i] is not None and self.last[i][2]: # Game has ended on the last step.
obs, reward, done, infos = self.last[i] # Copy last state over.
if self.auto_reset:
reward, done = 0., False
obs, infos = env.call_sync("reset")
results.append((obs, reward, done, infos))
else:
env.call("step", action)
results.append(None)
results = [result or env.result() for env, result in zip(self.envs, results)]
obs, rewards, dones, infos = zip(*results)
self.last = results
infos = _list_of_dicts_to_dict_of_lists(infos)
return obs, rewards, dones, infos
def render(self, mode='human'):
for env in self.envs:
env.call("render", mode)
return [env.result() for env in self.envs]
def close(self):
for env in self.envs:
env.call("close")
# Join
for env in self.envs:
env.result()
def __del__(self):
self.close()
class SyncBatchEnv(Environment):
""" Environment to run multiple games independently synchronously. """
def __init__(self, env_fns: List[callable], auto_reset: bool = False):
"""
Parameters
----------
env_fns : iterable of callable
Functions that create the environments
"""
self.env_fns = env_fns
self.batch_size = len(self.env_fns)
self.auto_reset = auto_reset
self.envs = [env_fn() for env_fn in self.env_fns]
def load(self, game_files: List[str]) -> None:
assert len(game_files) == len(self.envs)
for env, game_file in zip(self.envs, game_files):
env.load(game_file)
def seed(self, seed=None):
seeds = seed
if seeds is None or isinstance(seeds, int):
# Use a different seed for each env to decorrelate batch examples.
rng = np.random.RandomState(seeds)
seeds = list(rng.randint(65635, size=self.batch_size))
for env, seed in zip(self.envs, seeds):
env.seed(seed)
return seeds
def reset(self):
"""
Reset all environments of the batch.
Returns:
obs: Text observations, i.e. command's feedback.
infos: Information requested when creating the environments.
"""
self.last = [None] * self.batch_size
results = [env.reset() for env in self.envs]
obs, infos = zip(*results)
infos = _list_of_dicts_to_dict_of_lists(infos)
return obs, infos
def step(self, actions):
"""
Perform one action per environment of the batch.
Returns:
obs: Text observations, i.e. command's feedback.
reward: Current game score.
done: Whether the game is over or not.
infos: Information requested when creating the environments.
"""
assert isinstance(actions, (list, tuple)), "Expected a list of actions."
assert len(actions) == len(self.envs), "Expected one action per environment."
results = []
for i, (env, action) in enumerate(zip(self.envs, actions)):
if self.last[i] is not None and self.last[i][2]: # Game has ended on the last step.
obs, reward, done, infos = self.last[i] # Copy last state over.
if self.auto_reset:
reward, done = 0., False
obs, infos = env.reset()
results.append((obs, reward, done, infos))
else:
results.append(env.step(action))
self.last = results
obs, rewards, dones, infos = zip(*results)
infos = _list_of_dicts_to_dict_of_lists(infos)
return obs, rewards, dones, infos
def render(self, mode='human'):
return [env.render(mode=mode) for env in self.envs]
def close(self):
for env in self.envs:
env.close()