Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions distributed/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,7 @@ def __init__(self, address=None, loop=None, timeout=5,
self.connection_args = self.security.get_connection_args('client')
self._connecting_to_scheduler = False
self._asynchronous = asynchronous
self._should_close_loop = not loop
self._loop_runner = LoopRunner(loop=loop, asynchronous=asynchronous)
self.loop = self._loop_runner.loop

Expand Down Expand Up @@ -618,7 +619,7 @@ def __repr__(self):
return '<%s: not connected>' % (self.__class__.__name__,)

def _repr_html_(self):
if self._loop_runner.is_started():
if self._loop_runner.is_started() and self.scheduler:
info = sync(self.loop, self.scheduler.identity)
else:
info = False
Expand Down Expand Up @@ -1021,7 +1022,8 @@ def close(self, timeout=10):
sync(self.loop, self._close, fast=True)
assert self.status == 'closed'

self._loop_runner.stop()
if self._should_close_loop:
self._loop_runner.stop()

with ignoring(AttributeError):
dask.set_options(get=self._previous_get)
Expand Down
61 changes: 57 additions & 4 deletions distributed/joblib.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
from __future__ import print_function, division, absolute_import

import contextlib

from distutils.version import LooseVersion
from uuid import uuid4

from tornado import gen

from .client import Client, _wait
from .utils import ignoring, funcname, itemgetter
from . import get_client, secede, rejoin

# A user could have installed joblib, sklearn, both, or neither. Further, only
# joblib >= 0.10.0 supports backends, so we also need to check for that. This
Expand Down Expand Up @@ -68,12 +71,29 @@ class DaskDistributedBackend(ParallelBackendBase, AutoBatchingMixin):
MIN_IDEAL_BATCH_DURATION = 0.2
MAX_IDEAL_BATCH_DURATION = 1.0

def __init__(self, scheduler_host='127.0.0.1:8786', scatter=None, loop=None):
def __init__(self, scheduler_host=None, scatter=None,
client=None, loop=None):
if client is None:
if scheduler_host:
client = Client(scheduler_host, loop=loop, set_as_default=False)
else:
try:
client = get_client()
except ValueError:
msg = ("To use Joblib with Dask first create a Dask Client"
"\n\n"
" from dask.distributed import Client\n"
" client = Client()\n"
"or\n"
" client = Client('scheduler-address:8786')")
raise ValueError(msg)

self.client = client

if scatter is not None and not isinstance(scatter, (list, tuple)):
raise TypeError("scatter must be a list/tuple, got "
"`%s`" % type(scatter).__name__)

self.client = Client(scheduler_host, loop=loop, set_as_default=False)
if scatter is not None:
# Keep a reference to the scattered data to keep the ids the same
self._scatter = list(scatter)
Expand All @@ -84,6 +104,12 @@ def __init__(self, scheduler_host='127.0.0.1:8786', scatter=None, loop=None):
self.data_to_future = {}
self.futures = set()

def __reduce__(self):
return (DaskDistributedBackend, ())

def get_nested_backend(self):
return DaskDistributedBackend()

def configure(self, n_jobs=1, parallel=None, **backend_args):
return self.effective_n_jobs(n_jobs)

Expand Down Expand Up @@ -120,6 +146,7 @@ def maybe_to_futures(args):
def apply_async(self, func, callback=None):
key = '%s-batch-%s' % (joblib_funcname(func), uuid4().hex)
func, args = self._to_func_args(func)

future = self.client.submit(func, *args, key=key)
self.futures.add(future)

Expand All @@ -136,11 +163,35 @@ def callback_wrapper():
return future

def abort_everything(self, ensure_ready=True):
# Tell the client to cancel any task submitted via this instance
# as joblib.Parallel will never access those results.
""" Tell the client to cancel any task submitted via this instance

joblib.Parallel will never access those results
"""
self.client.cancel(self.futures)
self.futures.clear()

@contextlib.contextmanager
def retrieval_context(self):
"""Override ParallelBackendBase.retrieval_context to avoid deadlocks.

This removes thread from the worker's thread pool (using 'secede').
Seceding avoids deadlock in nested parallelism settings.
"""
# See 'joblib.Parallel.__call__' and 'joblib.Parallel.retrieve' for how
# this is used.
try:
secede()
except ValueError:
# We are not a worker, i.e. not in nested parallelism.
pass

yield

try:
rejoin()
except AttributeError:
pass

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we rejoin here? Typically this is necessary if there is additional computational work to do in the task. That may not be the case here. It's harmless either way, but might add a tiny bit of unwanted delay.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wasn't sure about that either. To make sure I understand, when the worker thread secedes, the scheduler will tell the worker to make a new thread to take its place? In that case, yes we should be OK just not rejoining.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, the thread leaves the thread pool, leaving it with n - 1 threads. We make a new thread to take it's place. Relevant code here: https://github.com/dask/distributed/blob/master/distributed/threadpoolexecutor.py#L94-L105

def secede(adjust=True):
    """ Have this thread secede from the ThreadPoolExecutor
    See Also
    --------
    rejoin: rejoin the thread pool
    """
    thread_state.proceed = False
    with threads_lock:
        thread_state.executor._threads.remove(threading.current_thread())
        if adjust:
            thread_state.executor._adjust_thread_count()



for base in _bases:
base.register(DaskDistributedBackend)
Expand All @@ -151,8 +202,10 @@ def abort_everything(self, ensure_ready=True):

# Register the backend with any available versions of joblib
if joblib:
joblib.register_parallel_backend('dask', DaskDistributedBackend)
joblib.register_parallel_backend('distributed', DaskDistributedBackend)
joblib.register_parallel_backend('dask.distributed', DaskDistributedBackend)
if sk_joblib:
sk_joblib.register_parallel_backend('dask', DaskDistributedBackend)
sk_joblib.register_parallel_backend('distributed', DaskDistributedBackend)
sk_joblib.register_parallel_backend('dask.distributed', DaskDistributedBackend)
8 changes: 8 additions & 0 deletions distributed/tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5166,5 +5166,13 @@ def test_client_name(s, a, b):
yield c._close()


def test_client_doesnt_close_given_loop(loop):
with cluster() as (s, [a, b]):
with Client(s['address'], loop=loop) as c:
assert c.submit(inc, 1).result() == 2
with Client(s['address'], loop=loop) as c:
assert c.submit(inc, 2).result() == 3


if sys.version_info >= (3, 5):
from distributed.tests.py3_test_client import * # flake8: noqa
120 changes: 80 additions & 40 deletions distributed/tests/test_joblib.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from __future__ import print_function, division, absolute_import
import os
from distutils.version import LooseVersion

import pytest
from random import random
from time import sleep

from distributed import Client
from distributed.utils_test import cluster, inc
from distributed.utils_test import loop # flake8: noqa

Expand All @@ -18,28 +21,24 @@ def slow_raise_value_error(condition, duration=0.05):
raise ValueError("condition evaluated to True")


@pytest.mark.skip(reason="intermittent blocking failures")
@pytest.mark.parametrize('joblib', joblibs)
def test_simple(loop, joblib):
if joblib is None:
pytest.skip()
Parallel = joblib.Parallel
delayed = joblib.delayed
with cluster() as (s, [a, b]):
with joblib.parallel_backend('dask.distributed', loop=loop,
scheduler_host=s['address']) as (ba, _):
with Client(s['address'], loop=loop) as client:
with joblib.parallel_backend('dask') as (ba, _):
seq = Parallel()(delayed(inc)(i) for i in range(10))
assert seq == [inc(i) for i in range(10)]

seq = Parallel()(delayed(inc)(i) for i in range(10))
assert seq == [inc(i) for i in range(10)]
with pytest.raises(ValueError):
Parallel()(delayed(slow_raise_value_error)(i == 3)
for i in range(10))

with pytest.raises(ValueError):
Parallel()(delayed(slow_raise_value_error)(i == 3)
for i in range(10))

seq = Parallel()(delayed(inc)(i) for i in range(10))
assert seq == [inc(i) for i in range(10)]

ba.client.close()
seq = Parallel()(delayed(inc)(i) for i in range(10))
assert seq == [inc(i) for i in range(10)]


def random2():
Expand All @@ -53,21 +52,21 @@ def test_dont_assume_function_purity(loop, joblib):
Parallel = joblib.Parallel
delayed = joblib.delayed
with cluster() as (s, [a, b]):
with joblib.parallel_backend('dask.distributed', loop=loop,
scheduler_host=s['address']) as (ba, _):

x, y = Parallel()(delayed(random2)() for i in range(2))
assert x != y

ba.client.close()
with Client(s['address'], loop=loop) as client:
with joblib.parallel_backend('dask') as (ba, _):
x, y = Parallel()(delayed(random2)() for i in range(2))
assert x != y


@pytest.mark.parametrize('joblib', joblibs)
def test_joblib_funcname(joblib):
if joblib is None:
pytest.skip()
BatchedCalls = joblib.parallel.BatchedCalls
func = BatchedCalls([(random2,), (random2,)])
if LooseVersion(joblib.__version__) <= "0.11.0":
func = BatchedCalls([(random2,), (random2,)])
else:
func = BatchedCalls([(random2,), (random2,)], None)
assert joblib_funcname(func) == 'random2'
assert joblib_funcname(random2) == 'random2'

Expand Down Expand Up @@ -113,25 +112,21 @@ def test_joblib_scatter(loop, joblib):
z = CountSerialized(3)

with cluster() as (s, [a, b]):
with joblib.parallel_backend('dask.distributed', loop=loop,
scheduler_host=s['address'],
scatter=[x, y]) as (ba, _):
f = delayed(add5)
tasks = [f(x, y, z, d=4, e=5),
f(x, z, y, d=5, e=4),
f(y, x, z, d=x, e=5),
f(z, z, x, d=z, e=y)]
sols = [func(*args, **kwargs) for func, args, kwargs in tasks]
results = Parallel()(tasks)

ba.client.close()

# Scatter must take a list/tuple
with pytest.raises(TypeError):
with joblib.parallel_backend('dask.distributed', loop=loop,
scheduler_host=s['address'],
scatter=1):
pass
with Client(s['address'], loop=loop) as client:
with joblib.parallel_backend('dask', scatter=[x, y]) as (ba, _):
f = delayed(add5)
tasks = [f(x, y, z, d=4, e=5),
f(x, z, y, d=5, e=4),
f(y, x, z, d=x, e=5),
f(z, z, x, d=z, e=y)]
sols = [func(*args, **kwargs) for func, args, kwargs in tasks]
results = Parallel()(tasks)

# Scatter must take a list/tuple
with pytest.raises(TypeError):
with joblib.parallel_backend('dask', loop=loop,
scatter=1):
pass

for l, r in zip(sols, results):
assert l == r
Expand All @@ -140,3 +135,48 @@ def test_joblib_scatter(loop, joblib):
assert x.count == 1
assert y.count == 1
assert z.count == 4


@pytest.mark.parametrize('joblib', joblibs)
def test_nested_backend_context_manager(loop, joblib):
if joblib is None or LooseVersion(joblib.__version__) <= "0.11.0":
pytest.skip("Joblib >= 0.11.1 required.")
Parallel = joblib.Parallel
delayed = joblib.delayed

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slight preference to leave these as fully namespaced, especially given the double use of delayed


def get_nested_pids():
pids = set(Parallel(n_jobs=2)(delayed(os.getpid)() for _ in range(2)))
pids |= set(Parallel(n_jobs=2)(delayed(os.getpid)() for _ in range(2)))
return pids

with cluster() as (s, [a, b]):
with Client(s['address'], loop=loop) as client:
with joblib.parallel_backend('dask') as (ba, _):
pid_groups = Parallel(n_jobs=2)(
delayed(get_nested_pids, check_pickle=False)()
for _ in range(10)
)
for pid_group in pid_groups:
assert len(set(pid_group)) <= 2

# No deadlocks
with Client(s['address'], loop=loop) as client:
with joblib.parallel_backend('dask') as (ba, _):
pid_groups = Parallel(n_jobs=2)(
delayed(get_nested_pids, check_pickle=False)()
for _ in range(10)
)
for pid_group in pid_groups:
assert len(set(pid_group)) <= 2


@pytest.mark.parametrize('joblib', joblibs)
def test_errors(loop, joblib):
if joblib is None:
pytest.skip()

with pytest.raises(ValueError) as info:
with joblib.parallel_backend('dask'):
pass

assert "create a dask client" in str(info.value).lower()