Skip to content

Incorrect maths with tensordot for sparse arrays constructed with map_blocks #6907

Closed

Description

@stephenworsley

What happened:

When applying the tensordot function to a chunked dask array which has been made into a sparse array, the result will be incorrect.

import numpy as np
import dask.array as da
import sparse
x = np.array(
    [
        [1, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, 1, 0],
        [0, 1, 0, 1],
    ]
)

x_chunked = da.from_array(x, chunks=(2, 2))
x_sparse_chunked = x_chunked.map_blocks(sparse.COO)

result = da.tensordot(x_sparse_chunked, x_sparse_chunked, axes=1).compute().todense()
print(result)

What you expected to happen:

This should yield

[[1 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 1]]

but instead yields

[[1 0 1 0]
 [0 1 0 1]
 [1 0 1 0]
 [0 1 0 1]]

It's worth noting that this bug does not happen with regular sparse arrays or if the chunked sparse array is constructed as follows:

x = np.array(
    [
        [1, 0, 0, 0],
        [0, 1, 0, 0],
        [0, 0, 1, 0],
        [0, 1, 0, 1],
    ]
)
x_sparse = sparse.COO(x)
x_sparse_chunked = da.from_array(x_sparse, chunks=(2, 2))

I'm not sure if this is a problem with dask or with sparse, though the fact that the behaviour changes when constructing the array with map_blocks vs converting a sparse array to dask makes me think that dask may be involved.
Environment:

Dask 2.30.0
Sparse 0.11.2

Activity

  1. zklaus commented on Nov 30, 2020

    @zklaus

    This might not even be related to sparse. In the following snippet, the same problem appears. At least I think it is the same problem. Applying persist to the input makes it work.

    x = da.random.random((4,4), chunks=(2,2))
    x[x < 0.65] = 0
    y = x.persist()
    z = x.compute()
    r1 = da.dot(x, x).compute()
    r2 = da.dot(y, y).compute()
    rr = np.dot(z, z)
    print(np.allclose(rr, r1))
    print(np.allclose(rr, r2))
  2. jsignell commented on Dec 1, 2020

    @jsignell
    Member

    I can't reproduce either of these on latest master:

    image

    Please reopen if you update to latest master and are able to reproduce.

  3. zklaus commented on Dec 1, 2020

    @zklaus

    This does seem to be fixed in master (more on that below). However, the following simple program

    #!/usr/bin/env python
    # coding: utf-8
    
    import numpy as np
    import dask
    import dask.array as da
    dask.config.set(scheduler='single-threaded')
    
    x = da.random.random((4,4), chunks=(2,2))
    x[x < 0.65] = 0
    
    y = x.persist()
    z = x.compute()
    r1 = da.dot(x, x).compute()
    r2 = da.dot(y, y).compute()
    rr = np.dot(z, z)
    print(np.allclose(rr, r1))
    print(np.allclose(rr, r2))

    Produced wrong results for many releases of dask (I tested 2.30.0, 2.20.0, 2.10.0, 2.0.0, and 1.0.0) this seems to have been fixed with fbccc4e .

    Seeing as this is a rather serious bug, silently producing wrong results for da.dot and da.tensordot under certain conditions, I wonder if a bug-fix release might be in order?

  4. jsignell commented on Dec 1, 2020

    @jsignell
    Member

    I suspect that since the bug has been around for so long, this isn't something that people run into very often. But I'll raise it with @dask/maintenance to see if this should be a candidate for a bug fix release. If not, then maybe a time estimate for the next release would be helpful.

  5. martindurant commented on Dec 1, 2020

    @martindurant
    Member

    We ought to be nearing a full normal release, I believe. It would be good to have that timeline, I agree.

  6. GenevieveBuckley commented on Aug 5, 2021

    @GenevieveBuckley
    Contributor

    I can narrow down on the weirdness a bit further.

    git checkout fbccc4ef3e1974da2b4a9cb61aa83c1e6d61efba^
    

    or...

    gh pr checkout 7980
    

    This works

    #!/usr/bin/env python
    # coding: utf-8
    
    import numpy as np
    import dask
    import dask.array as da
    dask.config.set(scheduler='single-threaded')
    
    numpy_data = np.random.random((4,4))
    numpy_data[numpy_data < 0.65] = 0  # if this statement happens in numpy, there is no difference whether we persist the dask input array or not before passing it to tensordot
    x = da.random.random((4,4), chunks=(2,2))
    y = x.persist()
    z = x.compute()
    r1 = da.dot(x, x).compute()
    r2 = da.dot(y, y).compute()
    rr = np.dot(z, z)
    assert np.allclose(rr, r1)
    assert np.allclose(rr, r2)

    This doesn't work

    #!/usr/bin/env python
    # coding: utf-8
    
    import numpy as np
    import dask
    import dask.array as da
    dask.config.set(scheduler='single-threaded')
    
    x = da.random.random((4,4), chunks=(2,2))
    x[x < 0.65] = 0   # if this statement happens in dask, then we get different results from tensordot depending on whether we persist the dask input array or not
    
    y = x.persist()
    z = x.compute()
    r1 = da.dot(x, x).compute()
    r2 = da.dot(y, y).compute()
    rr = np.dot(z, z)
    assert np.allclose(rr, r1)
    assert np.allclose(rr, r2)

    Why do we care?

    We want to fix the memory problems with tensordot reported here #6916. It seemed like the simplest path for a quick fix would be to revert the change which introduced the memory bottleneck... but that's the same change that inadvertantly fixed this issue. So, I want to solve both problems at once.

  7. GenevieveBuckley commented on Aug 18, 2021

    @GenevieveBuckley
    Contributor

    Stuff I did:

    • Traced through the low level graph visualization (eg: for an example like this). Sometimes graphviz displays the nodes shuffled around a bit
    • Used the dask get entry point (link to docs) to examine all intermediate task results
    • Double checked the data going into the tensordot computation is identical if you compute the input arrays

    I think this might have something to do with how arrays/chunks get hashed. I'll need to go look at how exactly that part is done. (perhaps not?)

  8. GenevieveBuckley commented on Aug 18, 2021

    @GenevieveBuckley
    Contributor

    I've narrowed it down the circumstances in which this occurs a bit further (although I still don't know the reason it happens).

    I can reproduce this if:

    • The two input arrays have the same numeric values in all locations (note: they don't have to be the same dask array, they just need to contain the same numeric values), AND...
    • There is a conditional "where" done on the same value/location(s), AND...
    • ...something very specific about the way the chunks are aligned/arranged - I haven't worked this bit out yet
    import dask
    import dask.array as da
    import numpy as np
    
    dask.config.set(scheduler='single-threaded')
    
    x = da.from_array(np.arange(16).reshape((4, 4)), chunks=(2,2))
    x[x == 0] = 0
    
    x2 = da.from_array(np.arange(16).reshape((4, 4)), chunks=(2,2))
    x2[x2 == 0] = 0  # change this line to "x2[x2 == 1] = 1" and the bug is not triggered
    
    y = x.persist()
    y2 = x2.persist()
    
    z = x.compute()
    z2 = x2.compute()
    
    r1 = da.dot(x, x2)
    r2 = da.dot(y, y2)
    rr = np.dot(z, z2)
    
    assert np.allclose(rr, r1.compute())  # fails
    assert np.allclose(rr, r2.compute())
  9. GenevieveBuckley commented on Aug 18, 2021

    @GenevieveBuckley
    Contributor

    More investigation into the chunks reveals:

    • If the whole array has only a single chunk, the bug does not occur
    • it seems to happen only for square shaped input chunks
  10. GenevieveBuckley commented on Aug 18, 2021

    @GenevieveBuckley
    Contributor

    I thought maybe it might have something to do with the insert trick used in _tensordot to expand the dimensions, followed by the sum reduction, but perhaps not. I haven't been able to make a simpler reproducible example.

    Investigating the intermediate named arrays for both situations in :

    • The values in the arrays are the same
    • The chunk sizes/shapes don't match, according to da.assert_eq. But I don't fully understand why that's happening, because both the shape & chunksize in the array HTML reprs match, and when you iterate through the array blocks one by one they also look like they match.
  11. GenevieveBuckley commented on Sep 9, 2021

    @GenevieveBuckley
    Contributor

    I redid my experiment with the Dask get entry point, after my conversation with Peter. The results were the same as last time, but I thought it's worthwhile sharing here regardless.

    • If you .compute() the input arrays, they appear correct.
    • All of the intermediate task results look identical.
    • ...but if we .compute() the final result there's a difference 😞
    import numpy as np
    import dask.array as da
    from dask import get
    
    a = da.from_array([[1, 2], [3, 4]], chunks=(1,1))
    b = da.from_array([[1, 2], [3, 4]], chunks=(1,1))
    b[b == 1] = 1
    
    correct = da.dot(a, a)
    incorrect = da.dot(b, b)
    
    print("Correct:\n", correct.compute())
    print("Incorrect:\n", incorrect.compute())
    assert not np.allclose(correct, incorrect)
    # Correct:
    #  [[ 7 10]
    #  [15 22]]
    # Incorrect:
    #  [[ 5  5]
    #  [17 25]]
    
    def match_key(key, keylist):
        # key to match
        key = list(key)    
        key[0] = key[0].rsplit('-', 1)[0]  # remove token
        # search for matches
        for k in keylist:
            temp = list(k)    
            temp[0] = temp[0].rsplit('-', 1)[0]  # remove token
            if temp == key:
                return tuple(k)
    
    for key in correct.dask.keys():
        key2 = match_key(key, incorrect.dask.keys())
        r1 = get(correct.dask, key)
        r2 = get(incorrect.dask, key2)
        assert r1 == r2
        print(key)
        print(key2)
        print(r1)
        print(r2)
        print('---')

    There are a couple of extra keys for tasks in the array that has the where statement, but they all come at the very beginning so I think we should at least see some errors being propagated through the steps after them, but we don't until the very final compute.

  12. jsignell commented on Sep 10, 2021

    @jsignell
    Member

    Having just looked at #8131 this is looking very similar. @GenevieveBuckley do you think they could be related?

  13. GenevieveBuckley commented on Sep 14, 2021

    @GenevieveBuckley
    Contributor

    Having just looked at #8131 this is looking very similar. @GenevieveBuckley do you think they could be related?

    Hm, maybe! Thanks for highlighting that here, Julia

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