_dask.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. from __future__ import print_function, division, absolute_import
  2. import asyncio
  3. import concurrent.futures
  4. import contextlib
  5. import time
  6. from uuid import uuid4
  7. import weakref
  8. from .parallel import AutoBatchingMixin, ParallelBackendBase, BatchedCalls
  9. from .parallel import parallel_backend
  10. try:
  11. import distributed
  12. except ImportError:
  13. distributed = None
  14. if distributed is not None:
  15. from dask.utils import funcname, itemgetter
  16. from dask.sizeof import sizeof
  17. from dask.distributed import (
  18. Client,
  19. as_completed,
  20. get_client,
  21. secede,
  22. rejoin
  23. )
  24. from distributed.utils import thread_state
  25. try:
  26. # asyncio.TimeoutError, Python3-only error thrown by recent versions of
  27. # distributed
  28. from distributed.utils import TimeoutError as _TimeoutError
  29. except ImportError:
  30. from tornado.gen import TimeoutError as _TimeoutError
  31. def is_weakrefable(obj):
  32. try:
  33. weakref.ref(obj)
  34. return True
  35. except TypeError:
  36. return False
  37. class _WeakKeyDictionary:
  38. """A variant of weakref.WeakKeyDictionary for unhashable objects.
  39. This datastructure is used to store futures for broadcasted data objects
  40. such as large numpy arrays or pandas dataframes that are not hashable and
  41. therefore cannot be used as keys of traditional python dicts.
  42. Futhermore using a dict with id(array) as key is not safe because the
  43. Python is likely to reuse id of recently collected arrays.
  44. """
  45. def __init__(self):
  46. self._data = {}
  47. def __getitem__(self, obj):
  48. ref, val = self._data[id(obj)]
  49. if ref() is not obj:
  50. # In case of a race condition with on_destroy.
  51. raise KeyError(obj)
  52. return val
  53. def __setitem__(self, obj, value):
  54. key = id(obj)
  55. try:
  56. ref, _ = self._data[key]
  57. if ref() is not obj:
  58. # In case of race condition with on_destroy.
  59. raise KeyError(obj)
  60. except KeyError:
  61. # Insert the new entry in the mapping along with a weakref
  62. # callback to automatically delete the entry from the mapping
  63. # as soon as the object used as key is garbage collected.
  64. def on_destroy(_):
  65. del self._data[key]
  66. ref = weakref.ref(obj, on_destroy)
  67. self._data[key] = ref, value
  68. def __len__(self):
  69. return len(self._data)
  70. def clear(self):
  71. self._data.clear()
  72. def _funcname(x):
  73. try:
  74. if isinstance(x, list):
  75. x = x[0][0]
  76. except Exception:
  77. pass
  78. return funcname(x)
  79. def _make_tasks_summary(tasks):
  80. """Summarize of list of (func, args, kwargs) function calls"""
  81. unique_funcs = {func for func, args, kwargs in tasks}
  82. if len(unique_funcs) == 1:
  83. mixed = False
  84. else:
  85. mixed = True
  86. return len(tasks), mixed, _funcname(tasks)
  87. class Batch:
  88. """dask-compatible wrapper that executes a batch of tasks"""
  89. def __init__(self, tasks):
  90. # collect some metadata from the tasks to ease Batch calls
  91. # introspection when debugging
  92. self._num_tasks, self._mixed, self._funcname = _make_tasks_summary(
  93. tasks
  94. )
  95. def __call__(self, tasks=None):
  96. results = []
  97. with parallel_backend('dask'):
  98. for func, args, kwargs in tasks:
  99. results.append(func(*args, **kwargs))
  100. return results
  101. def __repr__(self):
  102. descr = f"batch_of_{self._funcname}_{self._num_tasks}_calls"
  103. if self._mixed:
  104. descr = "mixed_" + descr
  105. return descr
  106. def _joblib_probe_task():
  107. # Noop used by the joblib connector to probe when workers are ready.
  108. pass
  109. class DaskDistributedBackend(AutoBatchingMixin, ParallelBackendBase):
  110. MIN_IDEAL_BATCH_DURATION = 0.2
  111. MAX_IDEAL_BATCH_DURATION = 1.0
  112. supports_timeout = True
  113. def __init__(self, scheduler_host=None, scatter=None,
  114. client=None, loop=None, wait_for_workers_timeout=10,
  115. **submit_kwargs):
  116. super().__init__()
  117. if distributed is None:
  118. msg = ("You are trying to use 'dask' as a joblib parallel backend "
  119. "but dask is not installed. Please install dask "
  120. "to fix this error.")
  121. raise ValueError(msg)
  122. if client is None:
  123. if scheduler_host:
  124. client = Client(scheduler_host, loop=loop,
  125. set_as_default=False)
  126. else:
  127. try:
  128. client = get_client()
  129. except ValueError as e:
  130. msg = ("To use Joblib with Dask first create a Dask Client"
  131. "\n\n"
  132. " from dask.distributed import Client\n"
  133. " client = Client()\n"
  134. "or\n"
  135. " client = Client('scheduler-address:8786')")
  136. raise ValueError(msg) from e
  137. self.client = client
  138. if scatter is not None and not isinstance(scatter, (list, tuple)):
  139. raise TypeError("scatter must be a list/tuple, got "
  140. "`%s`" % type(scatter).__name__)
  141. if scatter is not None and len(scatter) > 0:
  142. # Keep a reference to the scattered data to keep the ids the same
  143. self._scatter = list(scatter)
  144. scattered = self.client.scatter(scatter, broadcast=True)
  145. self.data_futures = {id(x): f for x, f in zip(scatter, scattered)}
  146. else:
  147. self._scatter = []
  148. self.data_futures = {}
  149. self.wait_for_workers_timeout = wait_for_workers_timeout
  150. self.submit_kwargs = submit_kwargs
  151. self.waiting_futures = as_completed(
  152. [],
  153. loop=client.loop,
  154. with_results=True,
  155. raise_errors=False
  156. )
  157. self._results = {}
  158. self._callbacks = {}
  159. async def _collect(self):
  160. while self._continue:
  161. async for future, result in self.waiting_futures:
  162. cf_future = self._results.pop(future)
  163. callback = self._callbacks.pop(future)
  164. if future.status == "error":
  165. typ, exc, tb = result
  166. cf_future.set_exception(exc)
  167. else:
  168. cf_future.set_result(result)
  169. callback(result)
  170. await asyncio.sleep(0.01)
  171. def __reduce__(self):
  172. return (DaskDistributedBackend, ())
  173. def get_nested_backend(self):
  174. return DaskDistributedBackend(client=self.client), -1
  175. def configure(self, n_jobs=1, parallel=None, **backend_args):
  176. self.parallel = parallel
  177. return self.effective_n_jobs(n_jobs)
  178. def start_call(self):
  179. self._continue = True
  180. self.client.loop.add_callback(self._collect)
  181. self.call_data_futures = _WeakKeyDictionary()
  182. def stop_call(self):
  183. # The explicit call to clear is required to break a cycling reference
  184. # to the futures.
  185. self._continue = False
  186. # wait for the future collection routine (self._backend._collect) to
  187. # finish in order to limit asyncio warnings due to aborting _collect
  188. # during a following backend termination call
  189. time.sleep(0.01)
  190. self.call_data_futures.clear()
  191. def effective_n_jobs(self, n_jobs):
  192. effective_n_jobs = sum(self.client.ncores().values())
  193. if effective_n_jobs != 0 or not self.wait_for_workers_timeout:
  194. return effective_n_jobs
  195. # If there is no worker, schedule a probe task to wait for the workers
  196. # to come up and be available. If the dask cluster is in adaptive mode
  197. # task might cause the cluster to provision some workers.
  198. try:
  199. self.client.submit(_joblib_probe_task).result(
  200. timeout=self.wait_for_workers_timeout)
  201. except _TimeoutError as e:
  202. error_msg = (
  203. "DaskDistributedBackend has no worker after {} seconds. "
  204. "Make sure that workers are started and can properly connect "
  205. "to the scheduler and increase the joblib/dask connection "
  206. "timeout with:\n\n"
  207. "parallel_backend('dask', wait_for_workers_timeout={})"
  208. ).format(self.wait_for_workers_timeout,
  209. max(10, 2 * self.wait_for_workers_timeout))
  210. raise TimeoutError(error_msg) from e
  211. return sum(self.client.ncores().values())
  212. async def _to_func_args(self, func):
  213. itemgetters = dict()
  214. # Futures that are dynamically generated during a single call to
  215. # Parallel.__call__.
  216. call_data_futures = getattr(self, 'call_data_futures', None)
  217. async def maybe_to_futures(args):
  218. out = []
  219. for arg in args:
  220. arg_id = id(arg)
  221. if arg_id in itemgetters:
  222. out.append(itemgetters[arg_id])
  223. continue
  224. f = self.data_futures.get(arg_id, None)
  225. if f is None and call_data_futures is not None:
  226. try:
  227. f = call_data_futures[arg]
  228. except KeyError:
  229. pass
  230. if f is None:
  231. if is_weakrefable(arg) and sizeof(arg) > 1e3:
  232. # Automatically scatter large objects to some of
  233. # the workers to avoid duplicated data transfers.
  234. # Rely on automated inter-worker data stealing if
  235. # more workers need to reuse this data
  236. # concurrently.
  237. # set hash=False - nested scatter calls (i.e
  238. # calling client.scatter inside a dask worker)
  239. # using hash=True often raise CancelledError,
  240. # see dask/distributed#3703
  241. [f] = await self.client.scatter(
  242. [arg],
  243. asynchronous=True,
  244. hash=False
  245. )
  246. call_data_futures[arg] = f
  247. if f is not None:
  248. out.append(f)
  249. else:
  250. out.append(arg)
  251. return out
  252. tasks = []
  253. for f, args, kwargs in func.items:
  254. args = list(await maybe_to_futures(args))
  255. kwargs = dict(zip(kwargs.keys(),
  256. await maybe_to_futures(kwargs.values())))
  257. tasks.append((f, args, kwargs))
  258. return (Batch(tasks), tasks)
  259. def apply_async(self, func, callback=None):
  260. cf_future = concurrent.futures.Future()
  261. cf_future.get = cf_future.result # achieve AsyncResult API
  262. async def f(func, callback):
  263. batch, tasks = await self._to_func_args(func)
  264. key = f'{repr(batch)}-{uuid4().hex}'
  265. dask_future = self.client.submit(
  266. batch, tasks=tasks, key=key, **self.submit_kwargs
  267. )
  268. self.waiting_futures.add(dask_future)
  269. self._callbacks[dask_future] = callback
  270. self._results[dask_future] = cf_future
  271. self.client.loop.add_callback(f, func, callback)
  272. return cf_future
  273. def abort_everything(self, ensure_ready=True):
  274. """ Tell the client to cancel any task submitted via this instance
  275. joblib.Parallel will never access those results
  276. """
  277. with self.waiting_futures.lock:
  278. self.waiting_futures.futures.clear()
  279. while not self.waiting_futures.queue.empty():
  280. self.waiting_futures.queue.get()
  281. @contextlib.contextmanager
  282. def retrieval_context(self):
  283. """Override ParallelBackendBase.retrieval_context to avoid deadlocks.
  284. This removes thread from the worker's thread pool (using 'secede').
  285. Seceding avoids deadlock in nested parallelism settings.
  286. """
  287. # See 'joblib.Parallel.__call__' and 'joblib.Parallel.retrieve' for how
  288. # this is used.
  289. if hasattr(thread_state, 'execution_state'):
  290. # we are in a worker. Secede to avoid deadlock.
  291. secede()
  292. yield
  293. if hasattr(thread_state, 'execution_state'):
  294. rejoin()