forked from NM512/dreamerv3-torch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel.py
209 lines (175 loc) · 6.24 KB
/
parallel.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
import atexit
import os
import sys
import time
import traceback
import enum
from functools import partial as bind
class Parallel:
def __init__(self, ctor, strategy):
self.worker = Worker(bind(self._respond, ctor), strategy, state=True)
self.callables = {}
def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(name)
try:
if name not in self.callables:
self.callables[name] = self.worker(PMessage.CALLABLE, name)()
if self.callables[name]:
return bind(self.worker, PMessage.CALL, name)
else:
return self.worker(PMessage.READ, name)()
except AttributeError:
raise ValueError(name)
def __len__(self):
return self.worker(PMessage.CALL, "__len__")()
def close(self):
self.worker.close()
@staticmethod
def _respond(ctor, state, message, name, *args, **kwargs):
state = state or ctor
if message == PMessage.CALLABLE:
assert not args and not kwargs, (args, kwargs)
result = callable(getattr(state, name))
elif message == PMessage.CALL:
result = getattr(state, name)(*args, **kwargs)
elif message == PMessage.READ:
assert not args and not kwargs, (args, kwargs)
result = getattr(state, name)
return state, result
class PMessage(enum.Enum):
CALLABLE = 2
CALL = 3
READ = 4
class Worker:
initializers = []
def __init__(self, fn, strategy="thread", state=False):
if not state:
fn = lambda s, *args, fn=fn, **kwargs: (s, fn(*args, **kwargs))
inits = self.initializers
self.impl = {
"process": bind(ProcessPipeWorker, initializers=inits),
"daemon": bind(ProcessPipeWorker, initializers=inits, daemon=True),
}[strategy](fn)
self.promise = None
def __call__(self, *args, **kwargs):
self.promise and self.promise() # Raise previous exception if any.
self.promise = self.impl(*args, **kwargs)
return self.promise
def wait(self):
return self.impl.wait()
def close(self):
self.impl.close()
class ProcessPipeWorker:
def __init__(self, fn, initializers=(), daemon=False):
import multiprocessing
import cloudpickle
self._context = multiprocessing.get_context("spawn")
self._pipe, pipe = self._context.Pipe()
fn = cloudpickle.dumps(fn)
initializers = cloudpickle.dumps(initializers)
self._process = self._context.Process(
target=self._loop, args=(pipe, fn, initializers), daemon=daemon
)
self._process.start()
self._nextid = 0
self._results = {}
assert self._submit(Message.OK)()
atexit.register(self.close)
def __call__(self, *args, **kwargs):
return self._submit(Message.RUN, (args, kwargs))
def wait(self):
pass
def close(self):
try:
self._pipe.send((Message.STOP, self._nextid, None))
self._pipe.close()
except (AttributeError, IOError):
pass # The connection was already closed.
try:
self._process.join(0.1)
if self._process.exitcode is None:
try:
os.kill(self._process.pid, 9)
time.sleep(0.1)
except Exception:
pass
except (AttributeError, AssertionError):
pass
def _submit(self, message, payload=None):
callid = self._nextid
self._nextid += 1
self._pipe.send((message, callid, payload))
return Future(self._receive, callid)
def _receive(self, callid):
while callid not in self._results:
try:
message, callid, payload = self._pipe.recv()
except (OSError, EOFError):
raise RuntimeError("Lost connection to worker.")
if message == Message.ERROR:
raise Exception(payload)
assert message == Message.RESULT, message
self._results[callid] = payload
return self._results.pop(callid)
@staticmethod
def _loop(pipe, function, initializers):
try:
callid = None
state = None
import cloudpickle
initializers = cloudpickle.loads(initializers)
function = cloudpickle.loads(function)
[fn() for fn in initializers]
while True:
if not pipe.poll(0.1):
continue # Wake up for keyboard interrupts.
message, callid, payload = pipe.recv()
if message == Message.OK:
pipe.send((Message.RESULT, callid, True))
elif message == Message.STOP:
return
elif message == Message.RUN:
args, kwargs = payload
state, result = function(state, *args, **kwargs)
pipe.send((Message.RESULT, callid, result))
else:
raise KeyError(f"Invalid message: {message}")
except (EOFError, KeyboardInterrupt):
return
except Exception:
stacktrace = "".join(traceback.format_exception(*sys.exc_info()))
print(f"Error inside process worker: {stacktrace}.", flush=True)
pipe.send((Message.ERROR, callid, stacktrace))
return
finally:
try:
pipe.close()
except Exception:
pass
class Message(enum.Enum):
OK = 1
RUN = 2
RESULT = 3
STOP = 4
ERROR = 5
class Future:
def __init__(self, receive, callid):
self._receive = receive
self._callid = callid
self._result = None
self._complete = False
def __call__(self):
if not self._complete:
self._result = self._receive(self._callid)
self._complete = True
return self._result
class Damy:
def __init__(self, env):
self._env = env
def __getattr__(self, name):
return getattr(self._env, name)
def step(self, action):
return lambda: self._env.step(action)
def reset(self):
return lambda: self._env.reset()