Skip to content

ValueError: cannot broadcast shape in Array.__setitem__ with boolean mask #11753

Closed

Description

@TomAugspurger

Describe the issue:

After #11728, Array.__setitem__ with a boolean mass fails with a ValueError

Minimal Complete Verifiable Example:

import dask.array as da


a = da.random.uniform(size=10)
mask = a > 0.5
a[mask] = a

that raises:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[3], line 6
      4 a = da.random.uniform(size=10)
      5 mask = a > 0.5
----> 6 a[mask] = a

File ~/gh/dask/dask/dask/array/core.py:1973, in Array.__setitem__(self, key, value)
   1967 # If value has ndim > 0, they must be broadcastable to self.shape[idx].
   1968 # This raises when the bool mask causes the size to become unknown,
   1969 # e.g. this is valid in numpy but raises here:
   1970 # x = da.array([1,2,3])
   1971 # x[da.array([True, True, False])] = [4, 5]
   1972 if value.ndim:
-> 1973     value = broadcast_to(value, self[key].shape)
   1975 y = where(key, value, self)
   1976 # FIXME does any backend allow mixed ops vs. numpy?
   1977 # If yes, is it wise to let them change the meta?

File ~/gh/dask/dask/dask/array/core.py:5241, in broadcast_to(x, shape, chunks, meta)
   5237 ndim_new = len(shape) - x.ndim
   5238 if ndim_new < 0 or any(
   5239     new != old for new, old in zip(shape[ndim_new:], x.shape) if old != 1
   5240 ):
-> 5241     raise ValueError(f"cannot broadcast shape {x.shape} to shape {shape}")
   5243 if chunks is None:
   5244     chunks = tuple((s,) for s in shape[:ndim_new]) + tuple(
   5245         bd if old > 1 else (new,)
   5246         for bd, old, new in zip(x.chunks, x.shape, shape[ndim_new:])
   5247     )

ValueError: cannot broadcast shape (10,) to shape (nan,)

Anything else we need to know?:

That snippet worked prior to #11728. dask/dask-ml#1012 is a downstream failure in dask-ml from this.

Environment:

  • Dask version:
  • Python version:
  • Operating System:
  • Install method (conda, pip, source):

Activity

  1. added
    needs triage
    on Feb 17, 2025
  2. phofl commented on Feb 17, 2025

    @phofl
    Collaborator

    @crusaderky as well

  3. added
    bug
    and removed
    needs triage
    on Feb 17, 2025
  4. self-assigned this
    on Feb 18, 2025
  5. crusaderky commented on Feb 18, 2025

    @crusaderky
    Collaborator

    To me this looks like dask-ml is abusing accidental, incorrect, undocumented, and untested behaviour of dask <2025.2.0.

    Your reproducer fails on numpy, and rightfully so, as you are trying to call __setitem__ on an array with size ~5 with a value of size 10.

    On dask 2025.1.0, a[mask] = b accidentally behaves like a[mask] = b[mask] does on numpy, due to lack of validation. a[mask] = b[mask] has always failed on Dask (and I recognize that's a problem).

    I would suggest making a[mask] = b[mask] work in Dask instead of restoring the previous behaviour. In other words, if both lhs and rhs have the same nan chunks, assume they have been sliced by the same mask and delay shape checks until compute time. This would be generically useful through a variety of use cases.

    In the meantime, dask-ml should use da.where instead (which is what da.Array.__setitem__ calls internally) unless there is a use case about applying the same functions to numpy arrays, which would take a performance hit?

  6. TomAugspurger commented on Feb 18, 2025

    @TomAugspurger
    MemberAuthor

    @crusaderky sorry, I trimmed my minimal example too far. It was supposed to be a[mask] = a[mask]. I see now that works when the size of the last dimension is 1.

    import dask.array as da
    
    
    a = da.random.uniform(size=1)
    mask = a > 0.5
    a[mask] = a[mask]
    

    I'll look later whether that's just an artifact of the test, or whether it's a behavior dask-ml (and so probably others) were relying on.

  7. crusaderky commented on Feb 24, 2025

    @crusaderky
    Collaborator
    import dask.array as da
    
    
    a = da.random.uniform(size=1)
    mask = a > 0.5
    a[mask] = a[mask]
    

    That exclusively worked, for some weird reason, if you had a mask sized 1 AND valued True.
    On 2025.1.0:

    >>> import dask.array as da
    >>> a = da.random.uniform(size=1)
    >>> mask = da.ones(1, dtype=bool)
    >>> a[mask] = a[mask]
    >>> a.compute()
    array([0.67559102])  # OK
    
    >>> a = da.random.uniform(size=1)
    >>> mask = da.zeros(1, dtype=bool)
    >>> a[mask] = a[mask]
    >>> a.compute()
    array([], dtype=float64)  # KO
    
  8. crusaderky commented on Mar 18, 2025

    @crusaderky
    Collaborator

    @TomAugspurger any update on this?

  9. TomAugspurger commented on Mar 20, 2025

    @TomAugspurger
    MemberAuthor

    Haven't had a chance to look into it yet.

  10. added
    needs attention
    on Apr 28, 2025
  11. TomAugspurger commented on May 10, 2025

    @TomAugspurger
    MemberAuthor

    @crusaderky able to look at this again today. I agree that my original example was faultly.

    We have one more failure in dask-ml, which I think boils down to this:

    import dask.array as da
    import numpy as np
    from dask import delayed
    
    
    @delayed
    def gen():
        return np.ones(10)
    
    
    @delayed
    def gen_bool():
        return np.ones(10, dtype=bool)
    
    
    X = da.concatenate(
        [
            da.from_delayed(gen, shape=(np.nan,), dtype=np.float64),
            da.from_delayed(gen, shape=(np.nan,), dtype=np.float64),
        ]
    )
    y = da.concatenate(
        [
            da.from_delayed(gen_bool, shape=(np.nan,), dtype=bool),
            da.from_delayed(gen_bool, shape=(np.nan,), dtype=bool),
        ]
    )
    
    X[y] = 1

    which raises with

    File ~/gh/dask/dask-ml/.venv/lib/python3.13/site-packages/dask/array/core.py:1938, in Array.__setitem__(self, key, value)
       1935 from dask.array.routines import where
       1937 if key.shape != self.shape:
    -> 1938     raise IndexError(
       1939         f"boolean index shape {key.shape} must match indexed array's "
       1940         f"{self.shape}."
       1941     )
       1943 # If value has ndim > 0, they must be broadcastable to self.shape[idx].
       1944 # This raises when the bool mask causes the size to become unknown,
       1945 # e.g. this is valid in numpy but raises here:
       1946 # x = da.array([1,2,3])
       1947 # x[da.array([True, True, False])] = [4, 5]
       1948 if value.ndim:
    
    IndexError: boolean index shape (nan,) must match indexed array's (nan,).

    That's erroring because (nan,) != (nan,). IMO, that should use something like (key.shape != self.shape) | key.isnan() == self.isnan(), assume that if a dimension is length nan on both sides assume it's the same shape. WDYT?

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

Metadata

Metadata

Assignees

Labels

arraybugneeds attention

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions