Skip to content

Reintroduce __setitem__ which more closely matches NumPy #7261

Closed

Description

@ryan-williams

Trying to run tests on current master (3d0e7bd) on an Amazon Linux m4.10xlarge (40 cores), I see dask/array/tests/test_array_core.py::test_setitem_extended_API allocating OS threads up to 32k at which point I get one of a variety of possible errors from within threading or multiprocessing (and also potentially in subsequent tests that try to run, ultimately segfault'ing the Python process):

# Run test + send to background
pytest -v dask/array/tests/test_array_core.py::test_setitem_extended_API &>test-out.txt &

# Print the number of OS threads in use every 1s
while [ 1 ] ; do ps -fLu $USER | wc -l; sleep 1; done

Output:

17
1823
5134
7714
10055
12960
14766
16744
18749
20395
21560
22893
24183
25602
25989
26634
27709
28655
29472
30375
30934
31442
32009
32176
32176
32176
32176
17810
[1]+  Exit 1                  pytest -v dask/array/tests/test_array_core.py::test_setitem_extended_API &>test-out.txt
16
16
16
16
test-out.txt
============================= test session starts ==============================
platform linux -- Python 3.7.10, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 -- /home/rwilliams/.pyenv/versions/3.7.10/bin/python3.7
cachedir: .pytest_cache
rootdir: /home/rwilliams/c/dask, configfile: setup.cfg
collecting ... collected 1 item

dask/array/tests/test_array_core.py::test_setitem_extended_API FAILED    [100%]

=================================== FAILURES ===================================
__________________________ test_setitem_extended_API ___________________________

    def test_setitem_extended_API():
        x = np.ma.arange(60).reshape((6, 10))
        dx = da.from_array(x.copy(), chunks=(2, 2))

        x[:, 2] = range(6)
        x[3, :] = range(10)
        x[::2, ::-1] = -1
        x[1::2] = -2
        x[:, [3, 5, 6]] = -3
        x[2:4, x[0] > 3] = -5
        x[2, x[0] < -2] = -7
        x[x % 2 == 0] = -8
        x[[4, 3, 1]] = -9
        x[5, ...] = -10
        x[..., 4] = -11
        x[2:4, 5:1:-2] = -x[:2, 4:1:-2]
        x[:2, :3] = [[1, 2, 3]]
        x[1, 1:7:2] = np.ma.masked
        x[0, 1:3] = -x[0, 4:2:-1]
        x[...] = x
        x[...] = x[...]
        x[0] = x[-1]
        x[0, :] = x[-2, :]
        x[:, 1] = x[:, -3]
        x[[True, False, False, False, True, False], 2] = -4
        x[3, [True, True, False, True, True, False, True, False, True, True]] = -5
        x[
            4,
            da.from_array(
                [False, False, True, True, False, False, True, False, False, True]
            ),
        ] = -55
        x[np.array([False, False, True, True, False, False]), 5:7] = -66

        dx[:, 2] = range(6)
        dx[3, :] = range(10)
        dx[::2, ::-1] = -1
        dx[1::2] = -2
        dx[:, [3, 5, 6]] = -3
        dx[2:4, dx[0] > 3] = -5
        dx[2, dx[0] < -2] = -7
        dx[dx % 2 == 0] = -8
        dx[[4, 3, 1]] = -9
        dx[5, ...] = -10
        dx[..., 4] = -11
        dx[2:4, 5:1:-2] = -dx[:2, 4:1:-2]
        dx[:2, :3] = [[1, 2, 3]]
        dx[1, 1:7:2] = np.ma.masked
        dx[0, 1:3] = -dx[0, 4:2:-1]
        dx[...] = dx
        dx[...] = dx[...]
        dx[0, :] = dx[-2, :]
        dx[:, 1] = dx[:, -3]
        dx[[True, False, False, False, True, False], 2] = -4
        dx[3, [True, True, False, True, True, False, True, False, True, True]] = -5
        dx[
            4,
            da.from_array(
                [False, False, True, True, False, False, True, False, False, True]
            ),
        ] = -55
        dx[np.array([False, False, True, True, False, False]), 5:7] = -66

        assert_eq(x, dx.compute())
>       assert_eq(x.mask, da.ma.getmaskarray(dx))

dask/array/tests/test_array_core.py:3677:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
dask/array/utils.py:265: in assert_eq
    b, check_shape=check_shape, check_graph=check_graph
dask/array/utils.py:239: in _get_dt_meta_computed
    x = x.compute(scheduler="sync")
dask/base.py:281: in compute
    (result,) = compute(self, traverse=False, **kwargs)
dask/base.py:563: in compute
    results = schedule(dsk, keys, **kwargs)
dask/local.py:528: in get_sync
    return get_async(apply_sync, 1, dsk, keys, **kwargs)
dask/local.py:495: in get_async
    fire_task()
dask/local.py:467: in fire_task
    callback=queue.put,
dask/local.py:517: in apply_sync
    res = func(*args, **kwds)
dask/local.py:227: in execute_task
    result = pack_exception(e, dumps)
dask/local.py:222: in execute_task
    result = _execute_task(task, data)
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/optimization.py:963: in __call__
    return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
dask/core.py:151: in get
    result = _execute_task(task, cache)
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/utils.py:35: in apply
    return func(*args, **kwargs)
dask/array/core.py:446: in _pass_extra_kwargs
    return func(*args[len(keys) :], **kwargs)
dask/array/slicing.py:1729: in setitem
    v = np.asanyarray(value[tuple(value_indices)])
../../.pyenv/versions/3.7.10/lib/python3.7/site-packages/numpy/core/_asarray.py:171: in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
dask/array/core.py:1454: in __array__
    x = self.compute()
dask/base.py:281: in compute
    (result,) = compute(self, traverse=False, **kwargs)
dask/base.py:563: in compute
    results = schedule(dsk, keys, **kwargs)
dask/threaded.py:84: in get
    **kwargs
dask/local.py:487: in get_async
    raise_exception(exc, tb)
dask/local.py:317: in reraise
    raise exc
dask/local.py:222: in execute_task
    result = _execute_task(task, data)
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/optimization.py:963: in __call__
    return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
dask/core.py:151: in get
    result = _execute_task(task, cache)
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/utils.py:35: in apply
    return func(*args, **kwargs)
dask/array/core.py:446: in _pass_extra_kwargs
    return func(*args[len(keys) :], **kwargs)
dask/array/slicing.py:1729: in setitem
    v = np.asanyarray(value[tuple(value_indices)])
../../.pyenv/versions/3.7.10/lib/python3.7/site-packages/numpy/core/_asarray.py:171: in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
dask/array/core.py:1454: in __array__
    x = self.compute()
dask/base.py:281: in compute
    (result,) = compute(self, traverse=False, **kwargs)
dask/base.py:563: in compute
    results = schedule(dsk, keys, **kwargs)
dask/threaded.py:84: in get
    **kwargs
dask/local.py:487: in get_async
    raise_exception(exc, tb)
dask/local.py:317: in reraise
    raise exc
dask/local.py:222: in execute_task
    result = _execute_task(task, data)
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/optimization.py:963: in __call__
    return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
dask/core.py:151: in get
    result = _execute_task(task, cache)
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/utils.py:35: in apply
    return func(*args, **kwargs)
dask/array/core.py:446: in _pass_extra_kwargs
    return func(*args[len(keys) :], **kwargs)
dask/array/slicing.py:1729: in setitem
    v = np.asanyarray(value[tuple(value_indices)])
../../.pyenv/versions/3.7.10/lib/python3.7/site-packages/numpy/core/_asarray.py:171: in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
dask/array/core.py:1454: in __array__
    x = self.compute()
dask/base.py:281: in compute
    (result,) = compute(self, traverse=False, **kwargs)
dask/base.py:563: in compute
    results = schedule(dsk, keys, **kwargs)
dask/threaded.py:84: in get
    **kwargs
dask/local.py:487: in get_async
    raise_exception(exc, tb)
dask/local.py:317: in reraise
    raise exc
dask/local.py:222: in execute_task
    result = _execute_task(task, data)
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/optimization.py:963: in __call__
    return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
dask/core.py:151: in get
    result = _execute_task(task, cache)
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:121: in <genexpr>
    return func(*(_execute_task(a, cache) for a in args))
dask/core.py:115: in _execute_task
    return [_execute_task(a, cache) for a in arg]
dask/core.py:115: in <listcomp>
    return [_execute_task(a, cache) for a in arg]
dask/core.py:121: in _execute_task
    return func(*(_execute_task(a, cache) for a in args))
dask/utils.py:35: in apply
    return func(*args, **kwargs)
dask/array/core.py:446: in _pass_extra_kwargs
    return func(*args[len(keys) :], **kwargs)
dask/array/slicing.py:1729: in setitem
    v = np.asanyarray(value[tuple(value_indices)])
../../.pyenv/versions/3.7.10/lib/python3.7/site-packages/numpy/core/_asarray.py:171: in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
dask/array/core.py:1454: in __array__
    x = self.compute()
dask/base.py:281: in compute
    (result,) = compute(self, traverse=False, **kwargs)
dask/base.py:563: in compute
    results = schedule(dsk, keys, **kwargs)
dask/threaded.py:72: in get
    pool = ThreadPool(num_workers)
../../.pyenv/versions/3.7.10/lib/python3.7/multiprocessing/pool.py:802: in __init__
    Pool.__init__(self, processes, initializer, initargs)
../../.pyenv/versions/3.7.10/lib/python3.7/multiprocessing/pool.py:176: in __init__
    self._repopulate_pool()
../../.pyenv/versions/3.7.10/lib/python3.7/multiprocessing/pool.py:241: in _repopulate_pool
    w.start()
../../.pyenv/versions/3.7.10/lib/python3.7/multiprocessing/dummy/__init__.py:51: in start
    threading.Thread.start(self)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <DummyProcess(Thread-32160, initial daemon)>

    def start(self):
        """Start the thread's activity.

        It must be called at most once per thread object. It arranges for the
        object's run() method to be invoked in a separate thread of control.

        This method will raise a RuntimeError if called more than once on the
        same thread object.

        """
        if not self._initialized:
            raise RuntimeError("thread.__init__() not called")

        if self._started.is_set():
            raise RuntimeError("threads can only be started once")
        with _active_limbo_lock:
            _limbo[self] = self
        try:
>           _start_new_thread(self._bootstrap, ())
E           RuntimeError: can't start new thread

../../.pyenv/versions/3.7.10/lib/python3.7/threading.py:852: RuntimeError
============================= slowest 10 durations =============================
45.06s call     dask/array/tests/test_array_core.py::test_setitem_extended_API
0.01s teardown dask/array/tests/test_array_core.py::test_setitem_extended_API

(1 durations < 0.005s hidden.  Use -vv to show these durations.)
============================== 1 failed in 55.67s ==============================

This test seems to work fine on my 8-core macbook (and in GHA, presumably). I'm wondering if there are relevant system libraries that should be checked?

I repro'd the error on 3.7.10, 3.8.6, and 3.8.8 (the error msgs were sometimes different on each one).

The test was added in #7033, so perhaps it should just be @ignored while we debug? I am going to do that locally at least.

FWIW, here are my ulimits:

ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 644539
max locked memory       (kbytes, -l) unlimited
max memory size         (kbytes, -m) unlimited
open files                      (-n) 8192
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 644539
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

None of them seem to exactly match the ≈2^15 where I see the error happen, but the exploding thread counts + 32k ceiling seem pretty consistent.

cc @davidhassell for visibility

Activity

  1. ryan-williams commented on Feb 22, 2021

    @ryan-williams
    ContributorAuthor

    I should note: on the EC2 instance that exhibits the issue, I see the same error inside Docker (which is using the underlying OS in various ways).

    Meanwhile, on my macbook, the test works inside or outside Docker.

    I've also had several CI builds that include #7033 pass over at https://github.com/celsiustx/dask/actions.

    So the culprit must be some system library or OS quirk? Theories are welcome.

  2. jsignell commented on Feb 23, 2021

    @jsignell
    Member

    Thanks for bringing this up! I can reproduce locally on my machine, so I can try to figure it out.

  3. jrbourbeau commented on Feb 24, 2021

    @jrbourbeau
    Member

    I'm able to reproduce locally too (thanks for catching this @ryan-williams). I'm a little surprised this isn't showing up in CI.

    Looking at the traceback Ryan posted, it appears there's some cycle happening in setitem where we end up recursively calling compute on an array and create a bunch of local threadpools:

    ...
    dask/array/slicing.py:1729: in setitem
        v = np.asanyarray(value[tuple(value_indices)])
    ../../.pyenv/versions/3.7.10/lib/python3.7/site-packages/numpy/core/_asarray.py:171: in asanyarray
        return array(a, dtype, copy=False, order=order, subok=True)
    dask/array/core.py:1454: in __array__
        x = self.compute()
    ...
    dask/array/slicing.py:1729: in setitem
        v = np.asanyarray(value[tuple(value_indices)])
    ../../.pyenv/versions/3.7.10/lib/python3.7/site-packages/numpy/core/_asarray.py:171: in asanyarray
        return array(a, dtype, copy=False, order=order, subok=True)
    dask/array/core.py:1454: in __array__
        x = self.compute()
    ...
    

    cc @davidhassell @Illviljan if you have any thoughts on this

  4. davidhassell commented on Feb 24, 2021

    @davidhassell
    Contributor

    Hi,

    I'm guessing from the comments here that this could be related to the fact that indices that are 1-d dask arrays are tested to see if they are strictly monotonically increasing/decreasing:

    If the tests that do this check (https://github.com/dask/dask/blob/master/dask/array/tests/test_array_core.py#L3652-L3654) are removed, does it work OK? I haven't been able to reproduce it myself.

    In any case, I shall look at moving the monotonicity check to the compute time of the __setitem__ operation, rather than the assignment time, which would be better all round.

  5. jsignell commented on Feb 24, 2021

    @jsignell
    Member

    If the tests that do this check (https://github.com/dask/dask/blob/master/dask/array/tests/test_array_core.py#L3652-L3654) are removed, does it work OK?

    I can confirm that that works locally.

  6. davidhassell commented on Feb 24, 2021

    @davidhassell
    Contributor

    Thanks, @jsignell. I've had a bit of a closer look, and I'm not so sure what's going on, as the recursing line has no direct relation to the dask array assignment indices, rather it is working on a __getitem__ slice of the assignment RHS value, which is just -5 or -7 or -8 in the three offending tests.

    This flow from, e.g. dx[2:4, dx[0] > 3] = -5 can be seen as follows:

    import dask.array as da
    import numpy as np
    
    value = -5  # RHS of assignment
    value = da.asanyarray(value)  # turned into a dask array in __setitem__ and passed to slicing.setitem()
    v = np.asanyarray(value[tuple([])]) # run in slicing.setitem(), v is actually assigned to the block
    print(repr(v))
    # array(-5)

    Does changing the line https://github.com/dask/dask/blob/master/dask/array/slicing.py#L1754 from v = np.asanyarray(value[tuple(value_indices)]) to v = value[tuple(value_indices)].compute() help (in ways which I don't fully understand)? I.e. is it related to the __array__ call, or not? The alternative version of this line would have the also have the required functionality.

    Thanks.

  7. jsignell commented on Feb 26, 2021

    @jsignell
    Member

    Does changing the line https://github.com/dask/dask/blob/master/dask/array/slicing.py#L1754 from v = np.asanyarray(value[tuple(value_indices)]) to v = value[tuple(value_indices)].compute() help

    No that doesn't seem to help.

  8. davidhassell commented on Feb 26, 2021

    @davidhassell
    Contributor

    Hmm. It was a long shot ... I'm currently stuck, here, but will think about it some more. Any ideas welcome!

  9. crusaderky commented on Mar 4, 2021

    @crusaderky
    Collaborator

    Minimal reproducer:

    import dask.array as da
    import psutil
    
    dx = da.zeros((6, 10), chunks=(2, 2))
    dx[::2, ::-1] = -1
    dx[2, dx[0] < -2] = -7
    dx[...] = dx
    dx[...] = dx[...]
    
    
    p = psutil.Process()
    print(p.num_threads())
    dx.compute()
    print(p.num_threads())

    Output on my 16 cores / 32 threads Ubuntu box:

    1
    10221
    
  10. jakirkham commented on Mar 4, 2021

    @jakirkham
    Member

    Should we add that as a test? Maybe marked as xfail?

  11. jrbourbeau commented on Mar 4, 2021

    @jrbourbeau
    Member

    Long term such a test would be nice to have. However short term, given the release tomorrow, if we can't resolve the test_setitem_extended_API issue before the release the plan is to revert #7033 altogether.

  12. jakirkham commented on Mar 4, 2021

    @jakirkham
    Member

    Yeah reverting makes sense. In that case should we go ahead and just include this test? That way we would be able to catch and fix this issue when undoing the revert

  13. sadielbartholomew commented on Mar 4, 2021

    @sadielbartholomew

    Hi, I'm commenting because I've been investigating the issue outlined here with @davidhassell because we are intrigued as to this new test he added in #7033 is showing this behaviour.

    Having seen that you plan to revert #7033 for the forthcoming release, I thought I could summarise beforehand what we have found out, in case it helps to pinpoint any problems relating to either this or to #7291 (to which we have found links as covered below) and also because we think we potentially have a solution as suggested below, though I for one am quite new to Dask so it might not be anything.

    I hope this is helpful anyhow. I have put the most important findings in bold (TLDR, etc.).

    Task graph complexity for dx and effect of a single persist

    The dx task graph

    We looked at the task graph of dx by the end of the test method in question, in case it showed anything useful. This is what we got from running the precise code (except adding the imports and removing the assert.eq statements with the code given in the hidden block below) in test_setitem_extended_API in iPython and running visualize (had to convert to PNG to embed here, hope it is sufficiently comprehensible):

    dx-task-graph

    Expand for code to reproduce graph
    import numpy as np
    import dask.array as da
    
    x = np.ma.arange(60).reshape((6, 10))
    dx = da.from_array(x.copy(), chunks=(2, 2))
    
    x[:, 2] = range(6)
    x[3, :] = range(10)
    x[::2, ::-1] = -1
    x[1::2] = -2
    x[:, [3, 5, 6]] = -3
    x[2:4, x[0] > 3] = -5
    x[2, x[0] < -2] = -7
    x[x % 2 == 0] = -8
    x[[4, 3, 1]] = -9
    x[5, ...] = -10
    x[..., 4] = -11
    x[2:4, 5:1:-2] = -x[:2, 4:1:-2]
    x[:2, :3] = [[1, 2, 3]]
    x[1, 1:7:2] = np.ma.masked
    x[0, 1:3] = -x[0, 4:2:-1]
    x[...] = x
    x[...] = x[...]
    x[0] = x[-1]
    x[0, :] = x[-2, :]
    x[:, 1] = x[:, -3]
    x[[True, False, False, False, True, False], 2] = -4
    x[3, [True, True, False, True, True, False, True, False, True, True]] = -5
    x[
        4,
        da.from_array(
            [False, False, True, True, False, False, True, False, False, True]
        ),
    ] = -55
    x[np.array([False, False, True, True, False, False]), 5:7] = -66
    
    dx[:, 2] = range(6)
    dx[3, :] = range(10)
    dx[::2, ::-1] = -1
    dx[1::2] = -2
    dx[:, [3, 5, 6]] = -3
    dx[2:4, dx[0] > 3] = -5
    dx[2, dx[0] < -2] = -7
    dx[dx % 2 == 0] = -8
    dx[[4, 3, 1]] = -9
    dx[5, ...] = -10
    dx[..., 4] = -11
    dx[2:4, 5:1:-2] = -dx[:2, 4:1:-2]
    dx[:2, :3] = [[1, 2, 3]]
    dx[1, 1:7:2] = np.ma.masked
    dx[0, 1:3] = -dx[0, 4:2:-1]
    
    dx[...] = dx
    dx[...] = dx[...]
    dx[0, :] = dx[-2, :]
    dx[:, 1] = dx[:, -3]
    dx[[True, False, False, False, True, False], 2] = -4
    dx[3, [True, True, False, True, True, False, True, False, True, True]] = -5
    dx[
        4,
        da.from_array(
            [False, False, True, True, False, False, True, False, False, True]
        ),
    ] = -55
    dx[np.array([False, False, True, True, False, False]), 5:7] = -66
    
    x, dx.compute()
    x.mask, da.ma.getmaskarray(dx)
    
    dx.visualize('dx-task-graph.svg')

    We noticed it had a lot of connections and this made us wonder if it was the kind of graph dask might struggle with? Or should dask be able to cope well with this? And above all is there anything about that graph that others might know could shine light on this or #7291?

    Adding a persist to dx

    We then thought to try adding some intermediate computes and persists, given the computations to be done by the end of the test method are quite extensive.

    We found that adding a single persist call on dx before the most intensive setitem operations (that ism dx = f(dx) where there is no slicing to give a new array to set as the value), namely here:

    diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py
    index 31143faa..3e6bac49 100644
    --- a/dask/array/tests/test_array_core.py
    +++ b/dask/array/tests/test_array_core.py
    @@ -3659,6 +3659,9 @@ def test_setitem_extended_API():
         dx[:2, :3] = [[1, 2, 3]]
         dx[1, 1:7:2] = np.ma.masked
         dx[0, 1:3] = -dx[0, 4:2:-1]
    +
    +    dx = dx.persist()
    +
         dx[...] = dx
         dx[...] = dx[...]
         dx[0, :] = dx[-2, :]

    seems to prevent the bug outlined here from emerging and also it (understandably) makes the test method run much quicker by OOM of around 10, which makes it run in comparable time to the other test methods, for example compare this with the persist call added:

    $ py.test --verbose -s dask/array/tests/test_array_core.py
    ...
    ...
    ============================= slowest 10 durations =============================
    1.86s call     dask/array/tests/test_array_core.py::test_from_array_meta
    0.82s call     dask/array/tests/test_array_core.py::test_setitem_extended_API
    0.76s call     dask/array/tests/test_array_core.py::test_tiledb_multiattr
    0.73s call     dask/array/tests/test_array_core.py::test_cumulative
    0.32s call     dask/array/tests/test_array_core.py::test_store_locks
    0.20s call     dask/array/tests/test_array_core.py::test_arithmetic
    0.17s call     dask/array/tests/test_array_core.py::test_tiledb_roundtrip
    0.13s call     dask/array/tests/test_array_core.py::test_store_multiprocessing_lock
    0.10s call     dask/array/tests/test_array_core.py::test_long_slice
    0.09s call     dask/array/tests/test_array_core.py::test_from_array_names
    =========================== short test summary info ============================
    XFAIL dask/array/tests/test_array_core.py::test_store_multiprocessing_lock
      can't lock with multiprocessing
    XFAIL dask/array/tests/test_array_core.py::test_index_array_with_array_3d_2d
      Chunking does not align well
    XFAIL dask/array/tests/test_array_core.py::test_map_blocks_dataframe
      need to remove singleton index dimension
    ================= 381 passed, 3 xfailed, 2 warnings in 10.62s ==================

    to some representative timings we saw originally (in a case on 8 cores where the bug was not showing, to allow a proper comparison):

    ============================= slowest 10 durations =============================
    8.10s call     dask/array/tests/test_array_core.py::test_setitem_extended_API
    1.89s call     dask/array/tests/test_array_core.py::test_from_array_meta
    1.61s call     dask/array/tests/test_array_core.py::test_tiledb_multiattr
    0.68s call     dask/array/tests/test_array_core.py::test_cumulative
    0.33s call     dask/array/tests/test_array_core.py::test_store_locks
    0.20s call     dask/array/tests/test_array_core.py::test_arithmetic
    0.15s call     dask/array/tests/test_array_core.py::test_tiledb_roundtrip
    0.12s call     dask/array/tests/test_array_core.py::test_store_multiprocessing_lock
    0.10s call     dask/array/tests/test_array_core.py::test_long_slice
    0.08s call     dask/array/tests/test_array_core.py::test_from_array_names
    =========================== short test summary info ============================
    XFAIL dask/array/tests/test_array_core.py::test_store_multiprocessing_lock
      can't lock with multiprocessing
    XFAIL dask/array/tests/test_array_core.py::test_index_array_with_array_3d_2d
      Chunking does not align well
    XFAIL dask/array/tests/test_array_core.py::test_map_blocks_dataframe
      need to remove singleton index dimension
    ================= 381 passed, 3 xfailed, 2 warnings in 18.51s ==================

    For reference, after adding that persist call the graph simplifies to:

    dx-task-graph-with-persist-call

    Perhaps this implies that the setitem work and test is not the cause of the bug, but is intensive enough without some intermediate task graph taming to be throwing up issues elsewhere? If so, and it is confirmed by others with different environments and scheduling to be the case, could a solution be to add that persist call (and perhaps a few more too) into the test instead of reverting #7033?

    "Too many open files" with >1 thread via PBD

    We also thought it could be significant that we were seeing the error OSError: [Errno 24] Too many open files from a new calculation at the end of the test_setitem_extended_API.

    For example, if I run the debugger at the very end of the method (when on 8 cores so even when the bug isn't showing up otherwise):

    diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py
    index 31143faa..b91450b9 100644
    --- a/dask/array/tests/test_array_core.py
    +++ b/dask/array/tests/test_array_core.py
    @@ -3676,6 +3676,9 @@ def test_setitem_extended_API():
         assert_eq(x, dx.compute())
         assert_eq(x.mask, da.ma.getmaskarray(dx))
     
    +    import pdb
    +    pdb.set_trace()
    +
     
     def test_setitem_on_read_only_blocks():
         # Outputs of broadcast_trick-style functions contain read-only

    then once running the test and into the debugger I run into the OSError:

    ...
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB set_trace >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    --Return--
    > /home/sadie/dask/dask/array/tests/test_array_core.py(3680)test_setitem_extended_API()->None
    -> pdb.set_trace()
    (Pdb) da.ma.getmaskarray(dx).compute()
    *** OSError: [Errno 24] Too many open files
    

    In my experience running da.ma.getmaskarray(dx).compute() can quickly raise any latent errors relating to the problem of this Issue. Note that if I call da.ma.getmaskarray(dx).compute(scheduler='single-threaded') instead, no such error is thrown.

    Similarly if I remove the lines to initiate the debugger and instead out da.ma.getmaskarray(dx).compute() at the end of the test, it raises the same traceback from #7261 (comment) and then many subsequent test methods in test_array_core, mainly realting to Zarr and/or TileDB, fail because they can't open any files.

    So we think this evidence indicates the issue may arise only in the threaded case and that it probably relates closely to #7291.

  14. pentschev commented on Mar 4, 2021

    @pentschev
    Member

    seems to prevent the bug outlined here from emerging and also it (understandably) makes the test method run much quicker by OOM of around 10, which makes it run in comparable time to the other test methods, for example compare this with the persist call added:

    I can confirm this improves the issue and allows the test to pass on my side. However, checking the process just after the dx.persist() that was added in the patch shows that there are still 8k threads, which is far from perfect, but at least it doesn't hit OS limits anymore.

  15. jakirkham commented on Mar 5, 2021

    @jakirkham
    Member

    Reverting in PR ( #7326 ) to help get the release out today. We can revisit these changes and how to improve behavior after the release. I know this is non-ideal as folks adding those changes put a lot of work into them, but we are just trying to find a practical way forward on releasing in the near term. Hope that makes sense

  16. 2 remaining items

  17. sadielbartholomew commented on Mar 5, 2021

    @sadielbartholomew

    Hi, just wanted to say on behalf of @davidhassell and myself that we completely understand the need to revert #7033 to get a release out without worrying about the threading issue outlined here. Good luck with the release and thanks for keeping #7033 in mind to be re-incorporated later.

    We now have a concrete theory about the root cause of the issue described here and ideas for potential means to resolve it, so once we have fleshed those out we will get back to you with suggestions and indications of code changes that might form the resolution. There is no immediate rush now that it can be pushed back to a later release I suppose.

    Thanks all.

  18. jakirkham commented on Mar 5, 2021

    @jakirkham
    Member

    Yeah we should have a couple of weeks after this release to work with you on reintroducing and addressing issues here. So hopefully that helps 🙂

  19. davidhassell commented on Mar 10, 2021

    @davidhassell
    Contributor

    Hi - we think that we've solved the unbounded threads issue, and also made the operation fully lazy for 1-d dask array indices, and removed the requirement of monotonic integer indices!

    PR, with an explanation of what was wrong and how we changed it, to follow soon.

    Thanks for your patience!
    David

  20. jakirkham commented on Mar 18, 2021

    @jakirkham
    Member

    It would be good if people here could try out PR ( #7393 ) and report back how it is working 🙂

  21. jakirkham commented on Mar 27, 2021

    @jakirkham
    Member

    Could people here please try the PR linked above and report back?

  22. abergou commented on Mar 29, 2021

    @abergou
    Contributor

    I took this out for a quick spin and it's very cool; seems quite useful!

    A few thoughts (these are musings, so feel free to ignore them if they're not useful thoughts):

    • It might be worth considering adding a readonly flag (or numpy flags-like attribute) to a dask array to make certain dask arrays readonly (this feature might be useful if for example if an object created a cached dask array interface into some data stored on disk; client code to this interface could rewrite the dask array, which would lead to difficult to diagnose bugs).
    • The docstring for Array.copy is now out of data (with this pr dask arrays are no longer immutable). If the item above is something of interest then it may also be worth considering having a copy reset the readonly flag so that a user can create a read-write dask array from a read-only one.
  23. davidhassell commented on Mar 29, 2021

    @davidhassell
    Contributor

    Hi @abergou - thanks!

    The docstring for Array.copy is now out of date (with this pr dask arrays are no longer immutable). If the item above is something of interest then it may also be worth considering having a copy reset the readonly flag so that a user can create a read-write dask array from a read-only one.

    Good point. Array.copy is still a no-op, so is it sufficient just to drop the ", which are immutable" bit?

        def copy(self):
            """
            Copy array.  This is a no-op for dask.arrays.
            """
    

    It might be worth considering adding a readonly flag (or numpy flags-like attribute) to a dask array to make certain dask arrays readonly (this feature might be useful if for example if an object created a cached dask array interface into some data stored on disk; client code to this interface could rewrite the dask array, which would lead to difficult to diagnose bugs).

    So that if readonly=True, __setitem__ raises an exception? Sounds fine to me, but perhaps this could be tackled in a separate issue - it sounds like this has ramifications far beyond __setitem__ ...

  24. jakirkham commented on Mar 29, 2021

    @jakirkham
    Member

    To be clear arrays still are immutable, what __setitem__ is really doing is more like np.where. So it constructs a new array that keeps the same chunks where things are unchanged and replaces them with new chunks when modified

  25. abergou commented on Mar 29, 2021

    @abergou
    Contributor

    @davidhassell thank you - that sounds great.

    @jakirkham I saw that this is how it's done from an implementation standpoint, but from a user's standpoint I think a dask array container is effectively no longer immutable. For example, suppose I have a dask array x, then a piece of code that runs y = x.compute() may now no longer compute the same y as one that runs f(x); y = x.compute() for some function f and the same initial array x.

  26. jakirkham commented on Mar 29, 2021

    @jakirkham
    Member

    We already support things like += and sometimes support out= arguments

  27. abergou commented on Mar 29, 2021

    @abergou
    Contributor

    Thanks for the clarification @jakirkham! Indeed you're right, I would suggest that in that case dask arrays haven't been immutable for a while :-), but your point is taken that this has nothing to do with this particular pr.

  28. jakirkham commented on Mar 29, 2021

    @jakirkham
    Member

    The thing is that the graph is immutable. Meaning that existing nodes and connections cannot change. Not that this cannot be a subgraph contained in a larger graph that is still being built. Also not necessarily that other things are immutable (like classes that hold the graph at different stages)

  29. jakirkham commented on Apr 7, 2021

    @jakirkham
    Member

    This was reworked and reintroduced in main. Could some people here please try this out and report back on how it goes? 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions