Skip to content

dask compute on reduction failes with ValueError #1759

Closed

Description

@TomAugspurger

I'm doing a reduction like mean on a dask-backed DataArray, and passing it to dask.compute

In [3]: from dask import compute
   ...: import numpy as np
   ...: import xarray as xr
   ...:

In [4]: data = xr.DataArray(np.random.random(size=(10, 2)),
   ...:                     dims=['samples', 'features']).chunk((5, 2))
   ...:

In [5]: compute(data.mean(axis=0))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-47605102585c> in <module>()
----> 1 compute(data.mean(axis=0))

~/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/base.py in compute(*args, **kwargs)
    334     results_iter = iter(results)
    335     return tuple(a if f is None else f(next(results_iter), *a)
--> 336                  for f, a in postcomputes)
    337
    338

~/Envs/dask-dev/lib/python3.6/site-packages/dask/dask/base.py in <genexpr>(.0)
    334     results_iter = iter(results)
    335     return tuple(a if f is None else f(next(results_iter), *a)
--> 336                  for f, a in postcomputes)
    337
    338

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/dataarray.py in _dask_finalize(results, func, args, name)
    607     @staticmethod
    608     def _dask_finalize(results, func, args, name):
--> 609         ds = func(results, *args)
    610         variable = ds._variables.pop(_THIS_ARRAY)
    611         coords = ds._variables

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/dataset.py in _dask_postcompute(results, info, *args)
    551                 func, args2 = v
    552                 r = results2.pop()
--> 553                 result = func(r, *args2)
    554             else:
    555                 result = v

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/variable.py in _dask_finalize(results, array_func, array_args, dims, attrs, encoding)
    389             results = {k: v for k, v in results.items() if k[0] == name}  # cull
    390         data = array_func(results, *array_args)
--> 391         return Variable(dims, data, attrs=attrs, encoding=encoding)
    392
    393     @property

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/variable.py in __init__(self, dims, data, attrs, encoding, fastpath)
    267         """
    268         self._data = as_compatible_data(data, fastpath=fastpath)
--> 269         self._dims = self._parse_dimensions(dims)
    270         self._attrs = None
    271         self._encoding = None

~/Envs/dask-dev/lib/python3.6/site-packages/xarray/xarray/core/variable.py in _parse_dimensions(self, dims)
    431             raise ValueError('dimensions %s must have the same length as the '
    432                              'number of data dimensions, ndim=%s'
--> 433                              % (dims, self.ndim))
    434         return dims
    435

ValueError: dimensions ('features',) must have the same length as the number of data dimensions, ndim=0

The expected output is the .compute version, which works correctly:

In [7]: data.mean(axis=0).compute()
Out[7]:
<xarray.DataArray (features: 2)>
array([0.535643, 0.459406])
Dimensions without coordinates: features
Details
In [6]: xr.show_versions()

INSTALLED VERSIONS
------------------
commit: c2b205f29467a4431baa80b5c07fe31bda67fbef
python: 3.6.1.final.0
python-bits: 64
OS: Darwin
OS-release: 16.7.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

xarray: 0.10.0-5-gc2b205f
pandas: 0.22.0.dev0+118.g4c6387520
numpy: 1.14.0.dev0+2995e6a
scipy: 1.1.0.dev0+b6fd544
netCDF4: 1.3.1
h5netcdf: None
Nio: None
bottleneck: None
cyordereddict: None
dask: 0.16.0+15.gcbc62fbef
matplotlib: 2.1.0
cartopy: None
seaborn: 0.8.1
setuptools: 36.7.2
pip: 10.0.0.dev0
conda: None
pytest: 3.2.3
IPython: 6.2.1
sphinx: 1.6.5

Apologies if I'm doing something silly here, I don't know xarray :)

Activity

  1. shoyer commented on Dec 4, 2017

    @shoyer
    Member

    I don't think you're doing anything wrong. This looks like a bug related to @mrocklin's recent addition of dask duck methods for xarray.

    Here are the values being passed to xarray.Dataset._dask_postcompute:

    results = ('mean_agg-aggregate-21a3ca7e382bdeee43ea06bee1ce3feb', 0)
    info = [(True, <this-array>, (<function Variable._dask_finalize at 0x118156158>, (<function finalize at 0x118350730>, (), ('y',), None, None)))]
    args = (set(), {'y': 2}, None, None, None)
    

    It seems like something is going wrong on the dask side: results should be the computed numpy array, not an uncomputed dask key.

  2. mrocklin commented on Dec 4, 2017

    @mrocklin
    Contributor

    I'll take a look

  3. mrocklin commented on Dec 4, 2017

    @mrocklin
    Contributor

    While testing this I oddly learn that the following line makes this pass

    from xarray.tests import mock
  4. mrocklin commented on Dec 4, 2017

    @mrocklin
    Contributor

    Here is the problem. It was just a silly typo.

    diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py
    index 0516b47..263860d 100644
    --- a/xarray/core/dataarray.py
    +++ b/xarray/core/dataarray.py
    @@ -594,7 +594,7 @@ class DataArray(AbstractArray, BaseDataObject):
     
         @property
         def __dask_scheduler__(self):
    -        return self._to_temp_dataset().__dask_optimize__
    +        return self._to_temp_dataset().__dask_scheduler__
     
         def __dask_postcompute__(self):
             func, args = self._to_temp_dataset().__dask_postcompute__()

    @shoyer any suggestions on comprehensive ways to test things?

  5. mrocklin commented on Dec 4, 2017

    @mrocklin
    Contributor

    Any objection to having the .compute methods point to dask.compute if the dask.__version__ is appropriate?

  6. shoyer commented on Dec 4, 2017

    @shoyer
    Member

    Any objection to having the .compute methods point to dask.compute if the dask.version is appropriate?

    Yes, this seems like a small win.

  7. mrocklin commented on Dec 5, 2017

    @mrocklin
    Contributor
  8. shoyer commented on Dec 5, 2017

    @shoyer
    Member

    any suggestions on comprehensive ways to test things?

    I still don't understand what actually went wrong here. It looks like we have test coverage for calling compute on an xarray.DataArray (see test_dataarray_with_dask_coords), but even though the exact example from that test fails at the repl the test passes when called with pytest:

    In [5]: import xarray as xr
    
    In [6]: import numpy as np
    
    In [7]: import dask
    
    In [8]: import dask.array as da
    
    In [9]:     import toolz
       ...:     x = xr.Variable('x', da.arange(8, chunks=(4,)))
       ...:     y = xr.Variable('y', da.arange(8, chunks=(4,)) * 2)
       ...:     data = da.random.random((8, 8), chunks=(4, 4)) + 1
       ...:     array = xr.DataArray(data, dims=['x', 'y'])
       ...:     array.coords['xx'] = x
       ...:     array.coords['yy'] = y
       ...:
       ...:     assert dict(array.__dask_graph__()) == toolz.merge(data.__dask_graph__(),
       ...:                                                        x.__dask_graph__(),
       ...:                                                        y.__dask_graph__())
       ...:
       ...:     (array2,) = dask.compute(array)
       ...:
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-9-4aaee405bed6> in <module>()
         11                                                    y.__dask_graph__())
         12
    ---> 13 (array2,) = dask.compute(array)
    
    ~/conda/envs/xarray-py36/lib/python3.6/site-packages/dask/base.py in compute(*args, **kwargs)
        334     results_iter = iter(results)
        335     return tuple(a if f is None else f(next(results_iter), *a)
    --> 336                  for f, a in postcomputes)
        337
        338
    
    ~/conda/envs/xarray-py36/lib/python3.6/site-packages/dask/base.py in <genexpr>(.0)
        334     results_iter = iter(results)
        335     return tuple(a if f is None else f(next(results_iter), *a)
    --> 336                  for f, a in postcomputes)
        337
        338
    
    ~/dev/xarray/xarray/core/dataarray.py in _dask_finalize(results, func, args, name)
        607     @staticmethod
        608     def _dask_finalize(results, func, args, name):
    --> 609         ds = func(results, *args)
        610         variable = ds._variables.pop(_THIS_ARRAY)
        611         coords = ds._variables
    
    ~/dev/xarray/xarray/core/dataset.py in _dask_postcompute(results, info, *args)
        551                 func, args2 = v
        552                 r = results2.pop()
    --> 553                 result = func(r, *args2)
        554             else:
        555                 result = v
    
    ~/dev/xarray/xarray/core/variable.py in _dask_finalize(results, array_func, array_args, dims, attrs, encoding)
        389             results = {k: v for k, v in results.items() if k[0] == name}  # cull
        390         data = array_func(results, *array_args)
    --> 391         return Variable(dims, data, attrs=attrs, encoding=encoding)
        392
        393     @property
    
    ~/dev/xarray/xarray/core/variable.py in __init__(self, dims, data, attrs, encoding, fastpath)
        267         """
        268         self._data = as_compatible_data(data, fastpath=fastpath)
    --> 269         self._dims = self._parse_dimensions(dims)
        270         self._attrs = None
        271         self._encoding = None
    
    ~/dev/xarray/xarray/core/variable.py in _parse_dimensions(self, dims)
        431             raise ValueError('dimensions %s must have the same length as the '
        432                              'number of data dimensions, ndim=%s'
    --> 433                              % (dims, self.ndim))
        434         return dims
        435
    
    ValueError: dimensions ('x',) must have the same length as the number of data dimensions, ndim=0
    
  9. mrocklin commented on Dec 5, 2017

    @mrocklin
    Contributor

    See #1760 for a potential fix

  10. mrocklin commented on Dec 5, 2017

    @mrocklin
    Contributor

    I still don't understand what actually went wrong here. It looks like we have test coverage for calling compute on an xarray.DataArray (see test_dataarray_with_dask_coords), but even though the exact example from that test fails at the repl the test passes when called with pytest:

    I experienced some odd behavior when testing this within the XArray test suite

    This file would pass when within xarray/tests/ but would fail when within the root directory

    import numpy as np
    import xarray as xr
    import dask
    
    def test_dask_reduction():
        data = xr.DataArray(np.random.random(size=(10, 2)),
                            dims=['samples', 'features']).chunk((5, 2))
        result = dask.compute(data.mean(axis=0))

    I suspect some odd behavior around mock, but that's probably due to a general bias/lack of understanding of that module.

  11. shoyer commented on Dec 5, 2017

    @shoyer
    Member

    I can remove all the mock related code from test_dask.py entirely and test_dataarray_with_dask_coords still passes.

  12. mrocklin commented on Dec 5, 2017

    @mrocklin
    Contributor

    I can remove all the mock related code from test_dask.py entirely and test_dataarray_with_dask_coords still passes.

    It was just a guess. Something wacky is certainly happening though. I recommend copying my code from my last comment and running pytest on it either in the root directory or in xarray/tests. I found that the outcome differed depending on location.

  13. shoyer commented on Dec 6, 2017

    @shoyer
    Member

    OK, I figured it out. We set dask.set_options(get=dask.get) in xarray/tests/__init__.py, which is convenient for debugging (warning: changing global state!). Naturally, that means dask ignores the value of __dask_scheduler__ attribute.

    I don't really have better ideas for how to test this, but it is reassuring that __dask_scheduler__ is the only attribute where we could reasonably expect to encounter this issue and its implementation is basically trivial. I suppose we could make one basic sanity test where we test each xarray data structure using the default scheduler. Possibly it would also make sense to change the scheduler explicitly (e.g., via a helper function for equality checks) rather than overloading it for all tests.

  14. mrocklin commented on Dec 6, 2017

    @mrocklin
    Contributor

    In the dask library itself we solve this by creating our own assert_eq functions that both invoke the single-threaded scheduler, and also do a variety of other sanity checks like ensuring that the expected and computed dtypes and shapes are the same, that the keynames in graphs are sensible, etc..

  15. max-sixty commented on Dec 6, 2017

    @max-sixty
    Collaborator

    our own assert_eq functions that both invoke the single-threaded scheduler, and also do a variety of other sanity checks like ensuring that the expected and computed dtypes and shapes are the same, that the keynames in graphs are sensible, etc..

    What do you think about using that in our tests, i.e. from dask.utils import asset_eq as assert_dask_equals?

    Or we could even check for a dask object in our own assert_equals and pass off to dask's?

  16. mrocklin commented on Dec 6, 2017

    @mrocklin
    Contributor

    That seems sensible to me. It would also be a good way to ensure that XArray operations adhere to all of the dask.array checks.

    from dask.array.utils import assert_eq
    
  17. jakirkham commented on Dec 6, 2017

    @jakirkham

    Given the recent turn in discussion here, might be worthwhile to share some thoughts on issue ( dask/dask#2694 ).

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