-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathlocal.py
291 lines (250 loc) · 9.36 KB
/
local.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
import asyncio
import multiprocessing
import os
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from functools import partial
from typing import Any, Callable, Optional, Sequence
import cloudpickle
import psutil
from networkx import MultiDiGraph
from tenacity import Retrying, stop_after_attempt
from cubed.runtime.asyncio import async_map_dag
from cubed.runtime.backup import use_backups_default
from cubed.runtime.pipeline import visit_nodes
from cubed.runtime.types import Callback, CubedPipeline, DagExecutor, TaskEndEvent
from cubed.runtime.utils import (
asyncio_run,
execution_stats,
execution_timing,
handle_operation_start_callbacks,
profile_memray,
)
from cubed.spec import Spec
def exec_stage_func(input, func=None, config=None, name=None, compute_id=None):
return func(input, config=config)
class SingleThreadedExecutor(DagExecutor):
"""The default execution engine that runs tasks sequentially uses Python loops."""
@property
def name(self) -> str:
return "single-threaded"
def execute_dag(
self,
dag: MultiDiGraph,
callbacks: Optional[Sequence[Callback]] = None,
resume: Optional[bool] = None,
spec: Optional[Spec] = None,
compute_id: Optional[str] = None,
**kwargs,
) -> None:
for name, node in visit_nodes(dag, resume=resume):
handle_operation_start_callbacks(callbacks, name)
pipeline: CubedPipeline = node["pipeline"]
for m in pipeline.mappable:
result = exec_stage_func(
m,
pipeline.function,
config=pipeline.config,
name=name,
compute_id=compute_id,
)
if callbacks is not None:
event = TaskEndEvent(name=name, result=result)
[callback.on_task_end(event) for callback in callbacks]
@execution_timing
def run_func_threads(input, func=None, config=None, name=None, compute_id=None):
return func(input, config=config)
@profile_memray
@execution_stats
def run_func_processes(input, func=None, config=None, name=None, compute_id=None):
return func(input, config=config)
def unpickle_and_call(f, inp, **kwargs):
import cloudpickle
f = cloudpickle.loads(f)
inp = cloudpickle.loads(inp)
kwargs = {k: cloudpickle.loads(v) for k, v in kwargs.items()}
return f(inp, **kwargs)
def check_runtime_memory(spec, max_workers):
allowed_mem = spec.allowed_mem if spec is not None else None
total_mem = psutil.virtual_memory().total
if allowed_mem is not None:
if total_mem < allowed_mem * max_workers:
raise ValueError(
f"Total memory on machine ({total_mem}) is less than allowed_mem * max_workers ({allowed_mem} * {max_workers} = {allowed_mem * max_workers})"
)
def threads_create_futures_func(
concurrent_executor, function: Callable[..., Any], retries: int = 2
):
if retries != 0:
retryer = Retrying(reraise=True, stop=stop_after_attempt(retries + 1))
function = partial(retryer, function)
def create_futures_func(input, **kwargs):
return [
(
i,
asyncio.wrap_future(concurrent_executor.submit(function, i, **kwargs)),
)
for i in input
]
return create_futures_func
class ThreadsExecutor(DagExecutor):
"""An execution engine that uses Python asyncio."""
def __init__(self, **kwargs):
self.kwargs = kwargs
# Tell NumPy to use a single thread
# from https://stackoverflow.com/questions/30791550/limit-number-of-threads-in-numpy
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
@property
def name(self) -> str:
return "threads"
def execute_dag(
self,
dag: MultiDiGraph,
callbacks: Optional[Sequence[Callback]] = None,
resume: Optional[bool] = None,
spec: Optional[Spec] = None,
compute_id: Optional[str] = None,
**kwargs,
) -> None:
merged_kwargs = {**self.kwargs, **kwargs}
asyncio_run(
self._async_execute_dag(
dag,
callbacks=callbacks,
resume=resume,
spec=spec,
compute_id=compute_id,
**merged_kwargs,
)
)
async def _async_execute_dag(
self,
dag: MultiDiGraph,
callbacks: Optional[Sequence[Callback]] = None,
resume: Optional[bool] = None,
spec: Optional[Spec] = None,
compute_arrays_in_parallel: Optional[bool] = None,
**kwargs,
) -> None:
max_workers = kwargs.pop("max_workers", os.cpu_count())
if spec is not None:
check_runtime_memory(spec, max_workers)
if "use_backups" not in kwargs and use_backups_default(spec):
kwargs["use_backups"] = True
concurrent_executor = ThreadPoolExecutor(max_workers=max_workers)
try:
create_futures_func = threads_create_futures_func(
concurrent_executor, run_func_threads, kwargs.pop("retries", 2)
)
await async_map_dag(
create_futures_func,
dag=dag,
callbacks=callbacks,
resume=resume,
compute_arrays_in_parallel=compute_arrays_in_parallel,
**kwargs,
)
finally:
# don't wait for any cancelled tasks
concurrent_executor.shutdown(wait=False)
def processes_create_futures_func(concurrent_executor, function: Callable[..., Any]):
def create_futures_func(input, **kwargs):
# Pickle the function, args, and kwargs using cloudpickle.
# They will be unpickled by unpickle_and_call.
pickled_kwargs = {k: cloudpickle.dumps(v) for k, v in kwargs.items()}
return [
(
i,
asyncio.wrap_future(
concurrent_executor.submit(
unpickle_and_call,
cloudpickle.dumps(function),
cloudpickle.dumps(i),
**pickled_kwargs,
)
),
)
for i in input
]
return create_futures_func
class ProcessesExecutor(DagExecutor):
"""An execution engine that uses local processes."""
def __init__(self, **kwargs):
self.kwargs = kwargs
# Tell NumPy to use a single thread
# from https://stackoverflow.com/questions/30791550/limit-number-of-threads-in-numpy
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
@property
def name(self) -> str:
return "processes"
def execute_dag(
self,
dag: MultiDiGraph,
callbacks: Optional[Sequence[Callback]] = None,
resume: Optional[bool] = None,
spec: Optional[Spec] = None,
compute_id: Optional[str] = None,
**kwargs,
) -> None:
merged_kwargs = {**self.kwargs, **kwargs}
asyncio_run(
self._async_execute_dag(
dag,
callbacks=callbacks,
resume=resume,
spec=spec,
compute_id=compute_id,
**merged_kwargs,
)
)
async def _async_execute_dag(
self,
dag: MultiDiGraph,
callbacks: Optional[Sequence[Callback]] = None,
resume: Optional[bool] = None,
spec: Optional[Spec] = None,
compute_arrays_in_parallel: Optional[bool] = None,
**kwargs,
) -> None:
max_workers = kwargs.pop("max_workers", os.cpu_count())
if spec is not None:
check_runtime_memory(spec, max_workers)
if "use_backups" not in kwargs and use_backups_default(spec):
kwargs["use_backups"] = True
use_processes = kwargs.pop("use_processes", True)
if isinstance(use_processes, str):
context = multiprocessing.get_context(use_processes)
else:
context = multiprocessing.get_context("spawn")
# max_tasks_per_child is only supported from Python 3.11
max_tasks_per_child = kwargs.pop("max_tasks_per_child", None)
if max_tasks_per_child is None:
concurrent_executor = ProcessPoolExecutor(
max_workers=max_workers, mp_context=context
)
else:
concurrent_executor = ProcessPoolExecutor(
max_workers=max_workers,
mp_context=context,
max_tasks_per_child=max_tasks_per_child,
)
try:
create_futures_func = processes_create_futures_func(
concurrent_executor, run_func_processes
)
await async_map_dag(
create_futures_func,
dag=dag,
callbacks=callbacks,
resume=resume,
compute_arrays_in_parallel=compute_arrays_in_parallel,
**kwargs,
)
finally:
# don't wait for any cancelled tasks
concurrent_executor.shutdown(wait=False)