Skip to content

array getitem with another array and broadcasting #2412

Closed

Description

@TomAugspurger

An example

>>> x = np.arange(12).reshape(4, 3)
>>> y = np.array([1, 1, 2, 3])
>>> dx = da.from_array(x, chunks=2)
>>> dy = da.from_array(y, chunks=2)
>>> x[y == 1]  # NumPy
array([[0, 1, 2],
       [3, 4, 5]])
In [43]: dx[dy == 1]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-43-9a0439f73673> in <module>()
----> 1 dx[dy == 1]

/Users/taugspurger/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/array/core.py in __getitem__(self, index)
   1196         # Slicing
   1197         if isinstance(index, Array):
-> 1198             return slice_with_dask_array(self, index)
   1199
   1200         if not isinstance(index, tuple):

/Users/taugspurger/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/array/core.py in slice_with_dask_array(x, index)
   3868
   3869 def slice_with_dask_array(x, index):
-> 3870     y = elemwise(getitem, x, index, dtype=x.dtype)
   3871
   3872     name = 'getitem-' + tokenize(x, index)

/Users/taugspurger/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/array/core.py in elemwise(op, *args, **kwargs)
   2624     shapes = [getattr(arg, 'shape', ()) for arg in args]
   2625     shapes = [s if isinstance(s, Iterable) else () for s in shapes]
-> 2626     out_ndim = len(broadcast_shapes(*shapes))   # Raises ValueError if dimensions mismatch
   2627     expr_inds = tuple(range(out_ndim))[::-1]
   2628

/Users/taugspurger/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/array/core.py in broadcast_shapes(*shapes)
   2597         if any(i != -1 and i != 1 and i != dim and not np.isnan(i) for i in sizes):
   2598             raise ValueError("operands could not be broadcast together with "
-> 2599                              "shapes {0}".format(' '.join(map(str, shapes))))
   2600         out.append(dim)
   2601     return tuple(reversed(out))

ValueError: operands could not be broadcast together with shapes (4, 3) (4,)

A solution is for the user to manually reshape to y to a 2-d array, with length 1 on the second dimension. Then the broadcasting lines up. I think we want to follow NumPy here (if possible?)

Activity

  1. mrocklin commented on Jun 5, 2017

    @mrocklin
    Member

    Doing the broadcasting automatically makes sense to me.

  2. TomAugspurger commented on Jun 5, 2017

    @TomAugspurger
    MemberAuthor
  3. TomAugspurger commented on Jun 6, 2017

    @TomAugspurger
    MemberAuthor

    @mrocklin would you (or anyone else familiar with the slicing / atop code) take a look at master...TomAugspurger:array-slice-array and let me know if I'm starting down the wrong track? (apologies for the messy WIP code).

    My current goal is to get dx[dy == 1] working, where dx and dy are dask arrays with the correct shapes

    1. dx.shape[0] == dy.shape[0]
    2. dx.ndim > dy.ndim

    Currently, it constructs a graph, built incorrectly; running pytest dask/array/tests/test_slicing.py -k test_slice_array_mask_simple raises on the compute with

    dask/array/tests/test_slicing.py:587:
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    dask/array/utils.py:60: in assert_eq
        a = a.compute(get=get_sync)
    dask/base.py:97: in compute
        (result,) = compute(self, traverse=False, **kwargs)
    dask/base.py:202: in compute
        dsk = collections_to_dsk(variables, optimize_graph, **kwargs)
    dask/base.py:461: in collections_to_dsk
        for opt, (dsk, keys) in groups.items()])
    dask/base.py:461: in <listcomp>
        for opt, (dsk, keys) in groups.items()])
    dask/context.py:84: in f
        return func(*args, **kwargs)
    dask/array/optimization.py:30: in optimize
        dsk2, dependencies = cull(dsk, keys)
    dask/optimize.py:47: in cull
        for k in work]
    dask/optimize.py:47: in <listcomp>
        for k in work]
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    
    dsk = {('getitem-a3ae0bd91a3873b743f1663f57fc66be', 0, 0): (<built-in function getitem>, ('array-2d68ac816440984399abba3b570... function getitem>, ('array-2d68ac816440984399abba3b570ca725', 1, 1), ('eq-7f02bb319ba45387432c1112e13587e1', 1)), ...}
    key = ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 1, 1), task = None, as_list = True
    
        def get_dependencies(dsk, key=None, task=None, as_list=False):
            """ Get the immediate tasks on which this task depends
            """
            if key is not None:
    >           arg = dsk[key]
    E           KeyError: ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 1, 1)

    I'll keep going down this route a bit further to see what I can get working.

  4. mrocklin commented on Jun 6, 2017

    @mrocklin
    Member

    When I look at the result of the elemwise call everything seems fine. I checked this by using result.visualize('dask.pdf') and result.compute() within a pdb call.

    However when I look at the full output graph and keys I see that there is a mismatch

    (Pdb) c
    {'array-original-2d68ac816440984399abba3b570ca725': array([[ 0,  1,  2],
           [ 3,  4,  5],
           [ 6,  7,  8],
           [ 9, 10, 11]]),
     'array-original-ad8f775f40e1a6878c20aeda11eb6432': array([1, 1, 2, 3]),
     ('array-2d68ac816440984399abba3b570ca725', 0, 0): (<function getarray at 0x7f84682cb510>,
                                                        'array-original-2d68ac816440984399abba3b570ca725',
                                                        (slice(0, 2, None),
                                                         slice(0, 2, None))),
     ('array-2d68ac816440984399abba3b570ca725', 0, 1): (<function getarray at 0x7f84682cb510>,
                                                        'array-original-2d68ac816440984399abba3b570ca725',
                                                        (slice(0, 2, None),
                                                         slice(2, 3, None))),
     ('array-2d68ac816440984399abba3b570ca725', 1, 0): (<function getarray at 0x7f84682cb510>,
                                                        'array-original-2d68ac816440984399abba3b570ca725',
                                                        (slice(2, 4, None),
                                                         slice(0, 2, None))),
     ('array-2d68ac816440984399abba3b570ca725', 1, 1): (<function getarray at 0x7f84682cb510>,
                                                        'array-original-2d68ac816440984399abba3b570ca725',
                                                        (slice(2, 4, None),
                                                         slice(2, 3, None))),
     ('array-ad8f775f40e1a6878c20aeda11eb6432', 0): (<function getarray at 0x7f84682cb510>,
                                                     'array-original-ad8f775f40e1a6878c20aeda11eb6432',
                                                     (slice(0, 2, None),)),
     ('array-ad8f775f40e1a6878c20aeda11eb6432', 1): (<function getarray at 0x7f84682cb510>,
                                                     'array-original-ad8f775f40e1a6878c20aeda11eb6432',
                                                     (slice(2, 4, None),)),
     ('eq-7f02bb319ba45387432c1112e13587e1', 0): (<function apply at 0x7f8469dcc400>,
                                                  <function partial_by_order at 0x7f8464398e18>,
                                                  [('array-ad8f775f40e1a6878c20aeda11eb6432',
                                                    0)],
                                                  {'function': <built-in function eq>,
                                                   'other': [(1, 1)]}),
     ('eq-7f02bb319ba45387432c1112e13587e1', 1): (<function apply at 0x7f8469dcc400>,
                                                  <function partial_by_order at 0x7f8464398e18>,
                                                  [('array-ad8f775f40e1a6878c20aeda11eb6432',
                                                    1)],
                                                  {'function': <built-in function eq>,
                                                   'other': [(1, 1)]}),
     ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 0): ('getitem-a3ae0bd91a3873b743f1663f57fc66be',
                                                       0,
                                                       0),
     ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 1): ('getitem-a3ae0bd91a3873b743f1663f57fc66be',
                                                       0,
                                                       1),
     ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 2): ('getitem-a3ae0bd91a3873b743f1663f57fc66be',
                                                       1,
                                                       0),
     ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 3): ('getitem-a3ae0bd91a3873b743f1663f57fc66be',
                                                       1,
                                                       1),
     ('getitem-a3ae0bd91a3873b743f1663f57fc66be', 0, 0): (<built-in function getitem>,
                                                          ('array-2d68ac816440984399abba3b570ca725',
                                                           0,
                                                           0),
                                                          ('eq-7f02bb319ba45387432c1112e13587e1',
                                                           0)),
     ('getitem-a3ae0bd91a3873b743f1663f57fc66be', 0, 1): (<built-in function getitem>,
                                                          ('array-2d68ac816440984399abba3b570ca725',
                                                           0,
                                                           1),
                                                          ('eq-7f02bb319ba45387432c1112e13587e1',
                                                           0)),
     ('getitem-a3ae0bd91a3873b743f1663f57fc66be', 1, 0): (<built-in function getitem>,
                                                          ('array-2d68ac816440984399abba3b570ca725',
                                                           1,
                                                           0),
                                                          ('eq-7f02bb319ba45387432c1112e13587e1',
                                                           1)),
     ('getitem-a3ae0bd91a3873b743f1663f57fc66be', 1, 1): (<built-in function getitem>,
                                                          ('array-2d68ac816440984399abba3b570ca725',
                                                           1,
                                                           1),
                                                          ('eq-7f02bb319ba45387432c1112e13587e1',
                                                           1))}
    (Pdb) pp (dx[dy == 1])._keys()
    
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB set_trace (IO-capturing turned off) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    > /home/mrocklin/workspace/dask/dask/array/core.py(2673)elemwise()
    -> return result
    (Pdb) c
    [[('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 0, 0),
      ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 0, 1)],
     [('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 1, 0),
      ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 1, 1)],
     [('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 2, 0),
      ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 2, 1)],
     [('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 3, 0),
      ('getitem-3e4c700d35ba80a7fbb3387f1ea0c076', 3, 1)]]
    (Pdb) 

    The getitem-3e4 keys have two indexes in our keys but only one index in the graph. Looking at this code we see that slice_with_dask_array linearizes the keys. This made sense in the case we had before but no longer makes sense here.

    def slice_with_dask_array(x, index):
        y = elemwise(getitem, x, index, dtype=x.dtype)
    
        name = 'getitem-' + tokenize(x, index)
    
        dsk = {(name, i): k
               for i, k in enumerate(core.flatten(y._keys()))} # <<--- I suspect that this is the issue
        if _is_boolean_mask(x, index):
            chunks = ((np.nan,) * y.npartitions,) + x.chunks[1:]
        else:
            chunks = ((np.nan,) * y.npartitions,)
    
        return Array(sharedict.merge(y.dask, (name, dsk)), name, chunks, x.dtype)
  5. TomAugspurger commented on Jun 6, 2017

    @TomAugspurger
    MemberAuthor

    Great, thanks for the pointer. I'll go there next.

  6. TomAugspurger commented on Jun 7, 2017

    @TomAugspurger
    MemberAuthor

    @mrocklin one more request for guidance if you don't mind :)

    master...TomAugspurger:array-slice-array is working correctly with dx[mask] where mask is a 1-d boolean mask. We should be able to support dx[mask] for any dimension mask (<= dx.ndim).

    def test_slice_array_mask_higher():
        x = np.arange(30).reshape(2, 3, 5)
        dx = da.from_array(x, chunks=5)
        m = x.sum(2) % 10 == 0
        dm = dx.sum(2) % 10 == 0  # `dm` is a 2-d boolean array, matching len on first dim
        assert_eq(dx[dm], x[m])
    

    Constructs the DAG (correctly I think) but fails on executation with

        def _execute_task(arg, cache, dsk=None):
            if isinstance(arg, list):
                return [_execute_task(a, cache) for a in arg]
            elif istask(arg):
                func, args = arg[0], arg[1:]
                args2 = [_execute_task(a, cache) for a in args]
    >           return func(*args2)
    E           TypeError: list indices must be integers or slices, not list
    
    dask/local.py:271: TypeError
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    [31] > /Users/taugspurger/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/local.py(271)_execute_task()
    -> return func(*args2)
    (Pdb++) pp args2
    [[array([[[ 0,  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]]])],
     [array([[ True, False,  True],
           [False,  True, False]], dtype=bool)]]

    So the is that args2[0] and args2[1] are length 1 lists, rather than ndarrays. In the 1-d case, these lists are unpacked down to just the arrays (I think, may be wrong about this), possibly in concatenate3.

    My question: does it sound like the issue is with the constructed DAG, or is there something I need to do on the compute side to make this work? Actually, typing this up has given my some ideas of where to look (based on the visualization). Going to check out rechunking stage next.

  7. mrocklin commented on Jun 7, 2017

    @mrocklin
    Member

    OK, so atop handles contractions (when some of the input indices are not present in the output) by giving the function a list of chunks as an input. That is what is happening in our case.

    (Pdb) pp atop_args
    [dask.array<array, shape=(2, 3, 5), dtype=int64, chunksize=(2, 3, 5)>,
     (2, 1, 0),
     dask.array<eq, shape=(2, 3), dtype=bool, chunksize=(2, 3)>,
     (2, 1)]
    (Pdb) pp expr_inds
    (1, 0)

    Perhaps you want to have expr_inds be the full index set? You might do a bit of atop work in this way and then collapse dimensions afterwards?

  8. TomAugspurger commented on Jun 7, 2017

    @TomAugspurger
    MemberAuthor

    I see, thanks.

  9. mrocklin commented on Jun 7, 2017

    @mrocklin
    Member

    Another way to think of this is that atop simultaneously handles broadcasting and reductions. In your case you probably just want broadcasting, in which case you'll want the output index set to be full. You might want to do some sort of axis shuffling afterwards (I'm not clear on array[array] semantics).

  10. jakirkham commented on Dec 4, 2017

    @jakirkham
    Member

    So the example raised in the OP appears to be solved at least in 0.16.0. Though admittedly the fix may have come earlier, but I don't recall which PR. This is the result from running the OP example below.

    In [1]: import numpy
       ...: import numpy as np
       ...: 
       ...: import dask
       ...: import dask.array
       ...: import dask.array as da
       ...: 
    
    In [2]: x = np.arange(12).reshape(4, 3)
    
    In [3]: y = np.array([1, 1, 2, 3])
    
    In [4]: dx = da.from_array(x, chunks=2)
    
    In [5]: dy = da.from_array(y, chunks=2)
    
    In [6]: x[y == 1]
    Out[6]: 
    array([[0, 1, 2],
           [3, 4, 5]])
    
    In [7]: dx[dy == 1]
    Out[7]: dask.array<getitem_variadic, shape=(nan, 3), dtype=int64, chunksize=(nan, 2)>
    
    In [8]: dx[dy == 1].compute()
    Out[8]: 
    array([[0, 1, 2],
           [3, 4, 5]])

    Were there other things we were trying to solve here or was that it?

  11. TomAugspurger commented on Jun 29, 2018

    @TomAugspurger
    MemberAuthor

    I think that was it.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions