Skip to content

dask.array.triu does not works with cupy array #7452

Closed

Description

@aktech

What happened:
There is a bug which is preventing da.triu to work on cupy arrays. I feel the bug is in dask.array which is sending wrong array to cupy as in sending np.ndarray instead of cp.ndarray. I haven't looked very closely, but this should be easy to fix, I believe.

cc @pentschev for FYI

What you expected to happen:
Result of triu function on the cupy array

Minimal Complete Verifiable Example:

import cupy
import dask.array as da
import dask

print(cupy.__version__)
print(dask.__version__)

x = da.arange(4).reshape(2, 2)
x = x.map_blocks(cupy.asarray)
t = da.triu(x)
t.compute()

Traceback:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-b21820d122aa> in <module>
      8 x = x.map_blocks(cupy.asarray)
      9 t = da.triu(x)
---> 10 t.compute()

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/base.py in compute(self, **kwargs)
    281         dask.base.compute
    282         """
--> 283         (result,) = compute(self, traverse=False, **kwargs)
    284         return result
    285 

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/base.py in compute(*args, **kwargs)
    563         postcomputes.append(x.__dask_postcompute__())
    564 
--> 565     results = schedule(dsk, keys, **kwargs)
    566     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    567 

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/threaded.py in get(dsk, result, cache, num_workers, pool, **kwargs)
     74                 pools[thread][num_workers] = pool
     75 
---> 76     results = get_async(
     77         pool.apply_async,
     78         len(pool._pool),

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/local.py in get_async(apply_async, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, **kwargs)
    485                         _execute_task(task, data)  # Re-execute locally
    486                     else:
--> 487                         raise_exception(exc, tb)
    488                 res, worker_id = loads(res_info)
    489                 state["cache"][key] = res

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/local.py in reraise(exc, tb)
    315     if exc.__traceback__ is not tb:
    316         raise exc.with_traceback(tb)
--> 317     raise exc
    318 
    319 

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)
    220     try:
    221         task, data = loads(task_info)
--> 222         result = _execute_task(task, data)
    223         id = get_id()
    224         result = dumps((result, id))

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/core.py in _execute_task(arg, cache, dsk)
    119         # temporaries by their reference count and can execute certain
    120         # operations in-place.
--> 121         return func(*(_execute_task(a, cache) for a in args))
    122     elif not ishashable(arg):
    123         return arg

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/optimization.py in __call__(self, *args)
    961         if not len(args) == len(self.inkeys):
    962             raise ValueError("Expected %d args, got %d" % (len(self.inkeys), len(args)))
--> 963         return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args)))
    964 
    965     def __reduce__(self):

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/core.py in get(dsk, out, cache)
    149     for key in toposort(dsk):
    150         task = dsk[key]
--> 151         result = _execute_task(task, cache)
    152         cache[key] = result
    153     result = _execute_task(out, cache)

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/dask/core.py in _execute_task(arg, cache, dsk)
    119         # temporaries by their reference count and can execute certain
    120         # operations in-place.
--> 121         return func(*(_execute_task(a, cache) for a in args))
    122     elif not ishashable(arg):
    123         return arg

<__array_function__ internals> in where(*args, **kwargs)

cupy/core/core.pyx in cupy.core.core.ndarray.__array_function__()

~/.conda/envs/sgkit-gpu-new/lib/python3.8/site-packages/cupy/_sorting/search.py in where(condition, x, y)
    209     if fusion._is_fusing():
    210         return fusion._call_ufunc(_where_ufunc, condition, x, y)
--> 211     return _where_ufunc(condition.astype('?'), x, y)
    212 
    213 

cupy/core/_kernel.pyx in cupy.core._kernel.ufunc.__call__()

cupy/core/_kernel.pyx in cupy.core._kernel._preprocess_args()

TypeError: Unsupported type <class 'numpy.ndarray'>

Anything else we need to know?:

Environment:

  • Dask version: 2021.03.0
  • Python version: 3.8.8
  • Operating System: Ubuntu 18.04
  • Install method (conda, pip, source): conda

Activity

  1. aktech commented on Mar 23, 2021

    @aktech
    ContributorAuthor

    I think the root cause of this is:

    _min_int = np.lib.twodim_base._min_int

    The dtype is derived from numpy, irrespective of array being a cupy array.

  2. pentschev commented on Mar 23, 2021

    @pentschev
    Member

    This is a duplicate of #7324 , unfortunately some recent changes have broken tri* functions with CuPy, but because we don't have GPUs in Dask CI builds don't fail when CuPy tests break.

    Unfortunately, I don't have the bandwidth now to work on fixing that, but this isn't related to the dtype, dtypes just indicate the data type (float, int, etc.) and they're the same across CuPy and NumPy. The problem lies with array creation, whenever a new array is created Dask has to ensure this new array has the same array type (NumPy, CuPy, etc.) as that used as input. #6997 has introduced new functions in https://github.com/dask/dask/pull/6997/files#diff-be1ec6725c3829aa2f919897e0d4cfc1e00b8db1e70e90c82531c5a12fd727afR1610-R1647 that coerce to a NumPy array (by simply relying to asarray), where we would need to use something such as asarray_safe instead for CuPy arrays to work. Additionally to that, in the same PR tri now only takes integers as inputs which calls arange internally, but it has no way of knowing that the input array type was originally a CuPy array to ensure the new arrays created should also be CuPy ones. This is thus a chain of functions that each needs to ensure all new arrays created all respect the input array type.

  3. aktech commented on Mar 23, 2021

    @aktech
    ContributorAuthor

    Ah, I see thanks for the quick response. By the way the motivation for this issue, came from using cupy here: https://github.com/pystatgen/sgkit/pull/498 are you aware of any workarounds?

  4. mrocklin commented on Mar 23, 2021

    @mrocklin
    Member
  5. aktech commented on Mar 23, 2021

    @aktech
    ContributorAuthor

    @mrocklin I might be able to sometime next week, I was wondering if there is a quick workaround from the user API point of view meanwhile, as even if I managed to fix it sometime soon I'll have to wait for the next release to use it anyways.

  6. pentschev commented on Mar 23, 2021

    @pentschev
    Member

    @aktech could you please try #7457 ? Hopefully that fixes the issue.

  7. aktech commented on Mar 24, 2021

    @aktech
    ContributorAuthor

    Hey @pentschev thanks for working on this, I just tried that PR. It doesn't seems to work on the reproducer I shared above.

    Just to confirm the git commit version:

    In [1]: dask.__version__
    Out[1]: '2021.01.1+125.gc4821996.dirty'
  8. pentschev commented on Mar 24, 2021

    @pentschev
    Member

    Can you ensure you have NumPy >= 1.20? That's required as well:

    In [2]: import numpy as np
       ...: import cupy
       ...: import dask.array as da
       ...: import dask
       ...:
       ...: print(np.__version__)
       ...: print(cupy.__version__)
       ...: print(dask.__version__)
       ...:
       ...: x = da.arange(4).reshape(2, 2)
       ...: x = x.map_blocks(cupy.asarray)
       ...: t = da.triu(x)
       ...: t.compute()
    1.20.1
    8.5.0
    2021.03.0+50.gc4821996
    Out[2]:
    array([[0, 1],
           [0, 3]])
  9. aktech commented on Mar 24, 2021

    @aktech
    ContributorAuthor

    Ah, I see. Yes that works for me with upgraded numpy version.

  10. jakirkham commented on Mar 25, 2021

    @jakirkham
    Member

    This should go out in our release on Friday

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