-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec_env.py
88 lines (77 loc) · 2.91 KB
/
vec_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
import numpy as np
from multiprocessing import Process, Pipe
from env import JerichoEnv
def worker(remote, parent_remote, env):
env = JerichoEnv(*env)
parent_remote.close()
try:
done = False
while True:
cmd, data = remote.recv()
if cmd == 'step':
if done:
ob, info = env.reset()
reward = 0
done = False
else:
ob, reward, done, info = env.step(data)
remote.send((ob, reward, done, info))
elif cmd == 'reset':
ob, info = env.reset()
remote.send((ob, info))
elif cmd == 'get_end_scores':
remote.send(env.get_end_scores(last=100))
elif cmd == 'close':
env.close()
break
else:
raise NotImplementedError
except KeyboardInterrupt:
print('SubprocVecEnv worker: got KeyboardInterrupt')
finally:
env.close()
class VecEnv:
def __init__(self, num_envs, env):
self.closed = False
self.num_envs = num_envs
self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(num_envs)])
self.ps = [Process(target=worker, args=(work_remote, remote, env))
for (work_remote, remote) in zip(self.work_remotes, self.remotes)]
for p in self.ps:
# p.daemon = True # if the main process crashes, we should not cause things to hang
p.start()
for remote in self.work_remotes:
remote.close()
def __del__(self):
for p in self.ps:
p.kill()
def step(self, actions):
self._assert_not_closed()
assert len(actions) == self.num_envs, "Error: incorrect number of actions."
for remote, action in zip(self.remotes, actions):
remote.send(('step', action))
results = [remote.recv() for remote in self.remotes]
self.waiting = False
obs, rewards, dones, infos = zip(*results)
return np.stack(obs), np.stack(rewards), np.stack(dones), infos
def reset(self):
self._assert_not_closed()
for remote in self.remotes:
remote.send(('reset', None))
results = [remote.recv() for remote in self.remotes]
obs, infos = zip(*results)
return np.stack(obs), infos
def get_end_scores(self):
self._assert_not_closed()
for remote in self.remotes:
remote.send(('get_end_scores', None))
results = [remote.recv() for remote in self.remotes]
return np.stack(results)
def close_extras(self):
self.closed = True
for remote in self.remotes:
remote.send(('close', None))
for p in self.ps:
p.join()
def _assert_not_closed(self):
assert not self.closed, "Trying to operate on a SubprocVecEnv after calling close()"