Skip to content

map_blocks converts dask arrays kwargs to strings #3263

Closed

Description

@mraspaud

Hi,

The following example causes me trouble:

import dask.array as da
import numpy as np

indices = da.arange(4, chunks=4)
data = da.arange(25, chunks=5).reshape(5, 5)

def get_samples(indices, data):
    print(data, indices)
    return data[:, indices]

da.map_blocks(get_samples, indices, data=data, new_axis=0, dtype=data.dtype).compute()

Basically, it looks like the data variable is converted to a string, hence the [:, indices] failing with a TypeError. Using a numpy array as data works as expected.

(btw, this is obviously just a toy example).

I understand that data needs to be computed before we can run map_blocks, but I don't want to do it just there.

So this looks like a bug to me, but maybe I'm missing something ?

Traceback:

-> python test_dask.py                                                                                                                tmp/ 
('finalize-4b8aee4f1226703a4df0635fe70b6c86', array([0, 1, 2, 3]))
Traceback (most recent call last):
  File "test_dask.py", line 11, in <module>
    da.map_blocks(get_samples, indices, data=data, new_axis=0, dtype=data.dtype).compute()
  File "/home/a001673/.local/lib/python2.7/site-packages/dask/base.py", line 143, in compute
    (result,) = compute(self, traverse=False, **kwargs)
  File "/home/a001673/.local/lib/python2.7/site-packages/dask/base.py", line 392, in compute
    results = get(dsk, keys, **kwargs)
  File "/home/a001673/.local/lib/python2.7/site-packages/dask/threaded.py", line 75, in get
    pack_exception=pack_exception, **kwargs)
  File "/home/a001673/.local/lib/python2.7/site-packages/dask/local.py", line 521, in get_async
    raise_exception(exc, tb)
  File "/home/a001673/.local/lib/python2.7/site-packages/dask/local.py", line 290, in execute_task
    result = _execute_task(task, data)
  File "/home/a001673/.local/lib/python2.7/site-packages/dask/local.py", line 271, in _execute_task
    return func(*args2)
  File "test_dask.py", line 9, in get_samples
    return data[:, indices]
TypeError: string indices must be integers, not tuple

Activity

  1. mrocklin commented on Mar 9, 2018

    @mrocklin
    Member

    I believe that map_blocks currently only unpacks dask arguments from args, not from kwargs. This could be changed if someone wants to submit a fix, but short term I would recommend including your dask array arguments as normal positional arguments.

  2. djhoese commented on Mar 9, 2018

    @djhoese
    Contributor

    @mrocklin I believe he intended to compute the entire data array and pass it to the function so it could be indexed. The oddness here is that the token of the dask array seems to get passed to the function and not the dask array.

  3. mraspaud commented on Mar 9, 2018

    @mraspaud
    Author

    @mrocklin yes, I understand that, and the intended purposed wasn't to unpack the data array, rather to index it. The strange thing is that map_blocks transforms the data dask array into a string (looks like the token as @davidh-ssec says) that is then unusable as is in the get_samples function.

  4. mraspaud commented on Mar 10, 2018

    @mraspaud
    Author

    Also passing data as a positional argument exhibits the same problem:
    da.map_blocks(get_samples, indices, data, new_axis=0, dtype=data.dtype).compute()
    -> TypeError: string indices must be integers, not tuple

  5. mrocklin commented on Mar 10, 2018

    @mrocklin
    Member

    Using positional arguments I get the following error:

    In [1]: import dask.array as da
       ...: import numpy as np
       ...: 
       ...: indices = da.arange(4, chunks=4)
       ...: data = da.arange(25, chunks=5).reshape(5, 5)
       ...: 
       ...: def get_samples(indices, data):
       ...:     print(data, indices)
       ...:     return data[:, indices]
       ...: 
       ...: da.map_blocks(get_samples, indices, data, new_axis=0, dtype=data.dtype).compute()
       ...: 
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    /home/mrocklin/workspace/dask/dask/array/core.py in map_blocks(func, *args, **kwargs)
        759             try:
    --> 760                 chunks2 = list(broadcast_chunks(*[a.chunks for a in arrs]))
        761             except Exception:
    
    /home/mrocklin/workspace/dask/dask/array/core.py in broadcast_chunks(*chunkss)
        815         if len(set(step2)) != 1:
    --> 816             raise ValueError("Chunks do not align: %s" % str(step2))
        817         result.append(step2[0])
    
    ValueError: Chunks do not align: [(4,), (5,)]
    
    During handling of the above exception, another exception occurred:
    
    ValueError                                Traceback (most recent call last)
    <ipython-input-1-ec53fee48272> in <module>()
          9     return data[:, indices]
         10 
    ---> 11 da.map_blocks(get_samples, indices, data, new_axis=0, dtype=data.dtype).compute()
    
    /home/mrocklin/workspace/dask/dask/array/core.py in map_blocks(func, *args, **kwargs)
        760                 chunks2 = list(broadcast_chunks(*[a.chunks for a in arrs]))
        761             except Exception:
    --> 762                 raise ValueError("Arrays in `map_blocks` don't align, can't "
        763                                  "infer output chunks. Please provide "
        764                                  "`chunks` kwarg.")
    
    ValueError: Arrays in `map_blocks` don't align, can't infer output chunks. Please provide `chunks` kwarg.
  6. mraspaud commented on Mar 12, 2018

    @mraspaud
    Author

    Yes, I get that error too with data as positional argument, sorry for that.
    Anyway, the use case is when you want to create an array with the values of another (data) using the indices which has the shape of the array to create.
    In that case we can't really use data as a positional argument. Is there a way to delay the evaluation of data until get_samples is executed, since passing data as a dask array in the kwargs just returns its token ?

  7. mraspaud commented on Mar 12, 2018

    @mraspaud
    Author

    I looked a bit further, and it looks like this function is responsible for replacing the data array with its token:

    dask/dask/delayed.py

    Lines 32 to 37 in 69ea16e

    def to_task_dask(expr):
    """Normalize a python object and merge all sub-graphs.
    - Replace ``Delayed`` with their keys
    - Convert literals to things the schedulers can handle
    - Extract dask graphs from all enclosed values

    So I see the delayed objects are replaced with their tokens, should it do the same for dask arrays ? Is there a way to retrieve the dask array from its token somehow ?

  8. mraspaud commented on Mar 13, 2018

    @mraspaud
    Author

    Ok, new discovery this morning: if I remove new_axis=0 from the map_blocks call, data passed to get_samples is a numpy array, which is perfect in my case.
    However, the shape of the resulting dask array is wrong. Running compute makes it right, but it means the shape of the dask array is unusable (which is problematic for us as we use xarray in conjuction with dask).

    So, which behaviour is the right one when passing data to get_samples via map_blocks ?

  9. jakirkham commented on Apr 5, 2018

    @jakirkham
    Member

    For some problems, map_blocks is great. However as one starts to adventure outside of the canonical usage of map_blocks, things can get a bit strange. Fortunately map_blocks is pretty good about suggesting an alternative as part of the error message for some of these common extensions.

    Namely it suggests atop. Would suggest taking a look at it for this use case as well. It can be a little daunting understanding atop, but the examples help and playing with a few toy problems should clarify it further. So take a look and see if it helps at all. Would be good to hear back either way. :)

  10. djhoese commented on Jun 20, 2018

    @djhoese
    Contributor

    Small update on this: I was able to use atop to solve @mraspaud's problem. He had written some logic to get around dask arrays not supporting indexing by dask arrays and I used that to provide the necessary dimension information to atop. For reference (although I don't know how readable this is out of context):

            def _my_index(index_arr, vii, data_arr, vii_slices=None, ia_slices=None, fill_value=np.nan):
                vii_slices = tuple(x if x is not None else vii.ravel()
                                   for x in vii_slices)
                mask_slices = tuple(x if x is not None else (index_arr == -1)
                                    for x in ia_slices)
                ia_slices = tuple(x if x is not None else index_arr for x in ia_slices)
                res = data_arr[vii_slices][ia_slices]
                res[mask_slices] = fill_value
                return res
    
            new_data = data.data.reshape(flat_src_shape)
            vii = vii.ravel()
            dst_adims = [dst_dim_to_ind[dim] for dim in dst_dims]
            ia_adims = [dst_dim_to_ind[dim] for dim in dst_geo_dims]
            res = da.atop(_my_index, dst_adims,
                          ia, ia_adims,
                          vii, flat_adim,
                          new_data, src_adims,
                          vii_slices=vii_slices, ia_slices=ia_slices,
                          fill_value=fill_value,
                          dtype=new_data.dtype, concatenate=True)
    

    Where ia is an integer index array (dask), vii is a boolean array of "valid inputs", and the original input data is an xarray DataArray. Above this code is a big for loop to map source dimensions to output dimensions along with figuring out which dimensions are flattened to handle the boolean array indexing being used. The ugliest part of this is that I have to provide these _slices lists so that I ignore dimensions I don't care about and slicing the ones I do care about. Not sure there is an easier way to do this.

    I guess it is up to you guys if this issue stays open since the original question is more generic than our use case.

  11. GenevieveBuckley commented on Oct 12, 2021

    @GenevieveBuckley
    Contributor

    I can run the code snippet without error with dask 2021.09.0, so I'm going to close this issue since it looks like it's been addressed in more recent versions of Dask.

    Anyone still experiencing this should try upgrading their version of dask, and if that doesn't help then please open an issue.

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