Skip to content

Converting Dask Array of unknown shape to known shape (at the cost of computing) #3293

Closed

Description

@jakirkham

Sometimes at the end of a series of Dask Array computations one has an array of unknown shape. However once the array is computed, it should be possible to know how big each chunk is and thus how big the array is as a whole. It would be nice at this stage to determine the array's shape and possibly even convert the Dask Array into one with known shape. This ends up being pretty important when allocating space for storage.

Activity

  1. mrocklin commented on Mar 16, 2018

    @mrocklin
    Member
  2. jakirkham commented on Mar 16, 2018

    @jakirkham
    MemberAuthor

    That sounds reasonable to me. Do you have any thoughts/suggestions on an API for this?

  3. mrocklin commented on Mar 16, 2018

    @mrocklin
    Member
  4. shoyer commented on Mar 17, 2018

    @shoyer
    Member

    I would suggest implementing a setter for Array.chunks, which could then automatically recompute the shape.

    TensorFlow supports something similar for making unknown dimension sizes known via the Tensor.set_shape() method. They don't support assignment to Tensor.shape because that might suggest NumPy's shape alternating semantics (but that wouldn't be an issue for us if we only support setting chunks).

  5. jakirkham commented on Mar 17, 2018

    @jakirkham
    MemberAuthor

    So there is a method setting chunks, which currently raises. Looking at the history, this tracks back to commit ( 66929ed ) in PR ( #416 ). Not sure if anyone was actually abusing chunks by setting. Perhaps this is a good argument to use rechunk here as well despite it being a bit strange. 🤔 Otherwise I do like the explicit setting of chunks because this feels like different behavior than rechunk and is a bit more inline with what is actually happening.

  6. shoyer commented on Mar 17, 2018

    @shoyer
    Member

    We could add some validation to ensure that chunks being assigned match the original structure, only replacing unknown with known sizes.

  7. mrocklin commented on Mar 17, 2018

    @mrocklin
    Member

    My expectation of setting chunks is that it would trigger a reshape operation, not that it would figure out the current value of unknown chunk sizes.

  8. mrocklin commented on Mar 17, 2018

    @mrocklin
    Member

    I'll throw out the option of adding a .compute_chunk_sizes() method or something else suitably boring.

    x = x.compute_chunk_sizes()
  9. jakirkham commented on Mar 28, 2018

    @jakirkham
    MemberAuthor

    FWIW this currently works. So maybe that can inform how we might want to interact with it as well.

    import dask
    import dask.array as da
    import numpy as np
    
    # Sample data to harden chunks for
    a = da.random.random((100, 110), chunks=10)
    a = a[a[:, 0] > 0.5, :]
    
    # Find unknown chunks
    c_0 = tuple(a[:, 0].map_blocks(lambda e: np.atleast_1d(e.shape[0])).compute())
    c = (c_0,) + a.chunks[1:]
    
    # Rebuild Dask Array with known chunks
    a2 = da.Array(
        a.__dask_graph__(),
        a.name,
        c,
        a.dtype
    )
  10. jakirkham commented on Apr 2, 2018

    @jakirkham
    MemberAuthor

    Have occasionally thought it might be nice to tackle this in a non-blocking way. That said, it's not totally obvious to me how this would be done. If anyone has ideas, would be interested to hear.

  11. jakirkham commented on Apr 6, 2018

    @jakirkham
    MemberAuthor

    Would add that in some cases it appears one needs to drop empty chunks from the array, which requires that the new array with those chunks dropped pick a new name and index the chunks in order. Not sure if there is a good utility function for this sort of thing, but it seems like a good idea.

  12. jakirkham commented on Apr 19, 2018

    @jakirkham
    MemberAuthor

    Playing with this idea a little bit more have come to the following.

    import numpy
    
    def _get_shape_helper(a):
        s = numpy.asarray(a.shape, dtype=int)
        return s[len(s) * (None,) + (slice(None),)]
    
    def get_all_chunk_shapes(a):
        return a.map_blocks(
            _get_shape_helper,
            dtype=int,
            chunks=tuple(len(c) * (1,) for c in a.chunks) + ((a.ndim,),),
            new_axis=a.ndim
        )
    
    def get_chunks(a):
        cs = get_all_chunk_shapes(a)
    
        c = []
        for i in range(a.ndim):
            s = a.ndim * [0] + [i]
            s[i] = slice(None)
            s = tuple(s)
    
            c.append(tuple(cs[s]))
    
        return tuple(c)

    This let's one do the following.

    In [1]: a = da.random.random((10, 11), chunks=5)
    
    In [2]: b = a[a > 0.3]
    
    In [3]: get_chunks(b)
    Out[3]: 
    ((dask.array<getitem, shape=(), dtype=int64, chunksize=()>,
      dask.array<getitem, shape=(), dtype=int64, chunksize=()>,
      dask.array<getitem, shape=(), dtype=int64, chunksize=()>,
      dask.array<getitem, shape=(), dtype=int64, chunksize=()>,
      dask.array<getitem, shape=(), dtype=int64, chunksize=()>,
      dask.array<getitem, shape=(), dtype=int64, chunksize=()>),)
    
    In [4]: da.compute(*get_chunks(b))
    Out[4]: ((18, 17, 3, 19, 18, 5),)

    There's probably room for improvement as this is a rough sketch. That said, this could be used to solve the task.

  13. mrocklin commented on Oct 24, 2018

    @mrocklin
    Member

    Any update on this @jakirkham ?

  14. jakirkham commented on Oct 29, 2018

    @jakirkham
    MemberAuthor

    Think the code above is as far as I got. Have gotten some use out of that though. Something like that in Dask should be adequate for my needs.

    However my understanding from the discussion above is we have not reached a consensus about the API (naming). Personally don't have strong feelings beyond using a reasonably short function name that gets the idea across (though many things probably work ok here :). Is there something agreeable on that front?

  15. djhoese commented on Feb 7, 2019

    @djhoese
    Contributor

    I wanted to make sure I was reading this correctly. Assuming I know the shape of my data (say I have a CSV that has a strangely formatted header with the number of rows in it) and I read it with dask, there is no way to "tell" dask what the shape is without computing/loading all the data, right?

  16. mrocklin commented on Feb 7, 2019

    @mrocklin
    Member

    If you know how many rows are in each chunk then you can manually define the chunks attribute. This is more information than the number of total rows though.

  17. djhoese commented on Feb 7, 2019

    @djhoese
    Contributor

    So I know the number of rows and the number of columns. I am using dask.dataframe.read_csv. It sounds like you are saying I should be able to do df.chunks = (rows, cols) right? Or even taking the dask array with to_dask_array on a Series and doing df.chunks = or rechunk? I had tried these with no luck since either I can't assign chunks directly this way or the shape is NaN so it complains.

  18. mrocklin commented on Feb 7, 2019

    @mrocklin
    Member

    There is no way to assign length to a dataframe

    You can define chunks on a dask array, but you'll need to define it for every single chunk of the array. This is the full tuple-of-tuples form. (See http://docs.dask.org/en/latest/array-chunks.html)

  19. djhoese commented on Feb 7, 2019

    @djhoese
    Contributor

    I got it to work. I had to pass lengths to to_dask_array which I didn't realize existed. Thanks.

  20. jakirkham commented on Mar 7, 2019

    @jakirkham
    MemberAuthor

    Should we put up a few options for the method name and vote? What’s the right way to proceed? It looks like the technical part is already solved.

  21. mrocklin commented on Mar 7, 2019

    @mrocklin
    Member

    Seems sensible to me

  22. ogrisel commented on Mar 20, 2019

    @ogrisel
    Contributor

    By the way, why wouldn't a call to .persist() automatically compute the chunksize metadata?

  23. mrocklin commented on Mar 20, 2019

    @mrocklin
    Member

    That's an interesting idea.

    One challenge is that with the distributed scheduler persist finishes immediately and runs asynchronously in the background, so we don't actually have any new information at this point.

  24. ogrisel commented on Mar 21, 2019

    @ogrisel
    Contributor

    That's a good point. Maybe we persist could take an argument to block (e.g. .persist(wait=True), possibly with a timeout) in which case the computation of the chunksize metadata could be automatically enabled.

  25. mrocklin commented on Mar 21, 2019

    @mrocklin
    Member

    With the proposal above this would be a two-liner

    x = x.persist()
    x = x.compute_chunk_sizes()

    We could add a flag into the persist method

    x = x.persist(compute_chunk_sizes=True)

    But I hesitate to do this a bit because the persist API is used for other collections and for the dask.persist function as well. The inconsistency might be a little surprising to users (though probably not that bad). I think that the two-liner is ok, and in many cases probably about the same speed.

  26. TomAugspurger commented on Sep 10, 2019

    @TomAugspurger
    Member

    This was fixed by #5312

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