Skip to content

Should dask.array.name be a settable property? #7218

Open

Description

@jsignell

I am wondering whether dask.Array.name should be a settable property. Given the relationship between the task graph and name, it feels like name is a special property that should be protected.

Consider the following case:

import numpy as np
import dask.array as da

darr = da.from_array(np.arange(1, 10))
darr.name = "foo"
darr.compute()
Output
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-0163ab538b86> in <module>
      5 print(darr.name)
      6 darr.name = "foo"
----> 7 darr.compute()

~/dask/dask/base.py in compute(self, **kwargs)
    280         dask.base.compute
    281         """
--> 282         (result,) = compute(self, traverse=False, **kwargs)
    283         return result
    284 

~/dask/dask/base.py in compute(*args, **kwargs)
    562         postcomputes.append(x.__dask_postcompute__())
    563 
--> 564     results = schedule(dsk, keys, **kwargs)
    565     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    566 

~/dask/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),

~/dask/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)
    502                     finish(dsk, state, not succeeded)
    503 
--> 504     return nested_get(result, state["cache"])
    505 
    506 

~/dask/dask/local.py in nested_get(ind, coll)
    298     """
    299     if isinstance(ind, list):
--> 300         return tuple([nested_get(i, coll) for i in ind])
    301     else:
    302         return coll[ind]

~/dask/dask/local.py in <listcomp>(.0)
    298     """
    299     if isinstance(ind, list):
--> 300         return tuple([nested_get(i, coll) for i in ind])
    301     else:
    302         return coll[ind]

~/dask/dask/local.py in nested_get(ind, coll)
    298     """
    299     if isinstance(ind, list):
--> 300         return tuple([nested_get(i, coll) for i in ind])
    301     else:
    302         return coll[ind]

~/dask/dask/local.py in <listcomp>(.0)
    298     """
    299     if isinstance(ind, list):
--> 300         return tuple([nested_get(i, coll) for i in ind])
    301     else:
    302         return coll[ind]

~/dask/dask/local.py in nested_get(ind, coll)
    300         return tuple([nested_get(i, coll) for i in ind])
    301     else:
--> 302         return coll[ind]
    303 
    304 

KeyError: ('foo', 0)

This is an especially confusing behavior since other libraries (like xarray and pandas) use name in a much more user-facing way (xref #7209)

Proposal
If I am right in my understanding that name is intentionally tied to the task graph, then I think the setter for name should be made to raise an error, and downstream libraries should use self._name instead.

Activity

  1. mrocklin commented on Feb 15, 2021

    @mrocklin
    Member
  2. jsignell commented on Feb 15, 2021

    @jsignell
    MemberAuthor

    To be clear name is already a property. I am mostly worried that downstream libraries will have to change from setting it using .name to ._name, but it's not clear to me how common it is for downstream libraries set name anyways.

  3. mrocklin commented on Feb 15, 2021

    @mrocklin
    Member
  4. jsignell commented on Feb 15, 2021

    @jsignell
    MemberAuthor

    Right. Ok I will open a PR to raise when name is set directly.

  5. allefeld commented on Feb 20, 2021

    @allefeld

    I found this issue when trying to debug my code. There are a few functions that allow to set the name in array creation, e.g. from_array and map_blocks, and this makes it easier to read the task stream and progress parts of the dashboard. The normal task names, e.g. p-sum-sum-sum-aggregate, are hard to map onto one's code.

    I found that the name is stored in the name attribute, and tried to set it explicitly on intermediate arrays, a.name = 'myname', which however makes compute and persist fail.

    Would it be possible to allow setting names on arbitrary Dask arrays, i.e. intermediate results, without breaking compute and persist? If not by directly setting the attribute, then e.g. by a set_name method, or allowing from_array to work on Dask arrays?

  6. dcherian commented on Feb 21, 2021

    @dcherian
    Collaborator

    Maybe a rename function?

  7. jsignell commented on Feb 22, 2021

    @jsignell
    MemberAuthor

    Would it be possible to allow setting names on arbitrary Dask arrays, i.e. intermediate results, without breaking compute and persist?

    The functions that you list are creating an array from scratch so it makes sense to set the name there. In intermediate arrays I don't know that there is a strong motivation to do the kind of task graph editing that this would require.

    I am wondering why you are interested in setting the name. Dask arrays should be thought of as similar to numpy arrays and numpy arrays don't have a name attribute at all.

  8. allefeld commented on Feb 22, 2021

    @allefeld

    I am wondering why you are interested in setting the name

    Having user-defined names makes it easier to read the task stream and progress parts of the dashboard. The normal task names, e.g. sum-sum-sum-aggregate-hash, are hard to map onto one's code. Without such a mapping, the dashboard is nice to look at, but doesn't provide a lot of insight.

    What I have done before is to print the names from the code, e.g. for a Dask array a:

    print('a:', a.name)

    but that's tedious and error-prone.

  9. jsignell commented on Feb 24, 2021

    @jsignell
    MemberAuthor

    Thanks for the additional context @allefeld. It makes sense to me that since the name is user-facing in the context of the dashboard, you'd want to make it more readable. I think this PR is still a good idea since it makes the current behavior clearer and protects users from getting into confusing states. Going forward there are two paths that we could take:

    1. Allow name to be settable or provide a rename function and do the proper graph manipulation to update existing graphs with the new name. Ping @crusaderky since you've been working with graph manipulation.
    2. Add name kwarg to more dask collection creation methods. This wouldn't require any graph manipulation and would let users control the name before the graph is constructed.

    Downside with both these options: name would still have to be unique and the burden would fall on the user to know that.

    Ping @dask/maintenance for opinions

  10. martindurant commented on Feb 24, 2021

    @martindurant
    Member

    (same arguments could be made for any dask collection; only xarrays have a concept of name, and even there it's unclear)

  11. allefeld commented on Feb 24, 2021

    @allefeld

    Downside with both these options: name would still have to be unique and the burden would fall on the user to know that.

    The current names seem to include some kind of hash. Couldn't such a hash be appended to user-specified names?

  12. jsignell commented on Feb 24, 2021

    @jsignell
    MemberAuthor

    The current names seem to include some kind of hash. Couldn't such a hash be appended to user-specified names?

    This proposal sounds like creating a new attribute on dask collections (maybe called key) that is a unique identifier and is what is used in the task-graph and then having a separate attribute (name) that is user-settable and is what is used in visualizations. Some downsides: what if multiple collections in a graph have the same name, how will they be distinguishable?

  13. allefeld commented on Feb 25, 2021

    @allefeld

    Some downsides: what if multiple collections in a graph have the same name, how will they be distinguishable?

    Maybe I'm missing something – but since this feature would be to assist the user in getting insight into the computation, it would be up to the user to choose distinct names.

  14. crusaderky commented on Feb 25, 2021

    @crusaderky
    Collaborator

    it makes sense to have both a .rename() read-only method and a .name settable property. They would both create a new Blockwise layer in the dask graph.

    Some downsides: what if multiple collections in a graph have the same name, how will they be distinguishable?

    Then you'll get key collisions and everything will fall apart. This is always the case when you let the user manually set dask keys. There are precedents for this, namely with Delayed objects.

    To improve usability and avoid accidental collisions for all those users that just want a prettier output in the dask GUI and profiling reports, may I suggest this API:

    @overload
    def rename(self, *, prefix: str): ...
    
    @overload
    def rename(self, name: str): ...
    
    def rename(self, name: str = None, *, prefix: str = None):
        if prefix:
            if name:
                raise TypeError("name and prefix are mutually exclusive")
            name = prefix + "-" + tokenize(self)
        elif not name:
            raise TypeError("must provide either name or prefix")
    
        out = self.copy()
        out.name = name
        return out
  15. jsignell commented on Feb 25, 2021

    @jsignell
    MemberAuthor

    They would both create a new Blockwise layer in the dask graph.

    You mean they wouldn't edit the task graph, they'd just add a layer to edit the graph?

  16. crusaderky commented on Feb 25, 2021

    @crusaderky
    Collaborator

    @jsignell you can either replace the topmost layer or add a new one on top. I prefer the former for obvious performance reasons

  17. bmerry commented on Mar 16, 2021

    @bmerry
    Contributor

    Ah. I see now that this is new for the recent work with setitem. I would
    be curious to learn which downstream libraries are setting name and why.

    I have some code that rewrites the name of an array in place (including renaming all the keys of the graph). This is done if the data underlying the bottom-most levels of the graph is modified, to ensure that any sort of caching of intermediate blocks is invalidated. So I am now using the escape hatch of assigning to _name.

    I realise that it would be cleaner to return a new Array instead of modifying it in place, but in my case it would have been difficult to find all the places that held references to the original Array to ensure that they're updated.

  18. jrbourbeau commented on Mar 16, 2021

    @jrbourbeau
    Member

    Good to know, thanks @bmerry. Hopefully the move to _name didn't disrupt things too much for you

  19. bmerry commented on Mar 16, 2021

    @bmerry
    Contributor

    Hopefully the move to _name didn't disrupt things too much for you

    Nah, just a couple of lines of change. We religiously pin dependencies so the disruption was controlled. I brought it up mostly so that you're aware that the escape hatch is being used.

  20. jakirkham commented on Apr 27, 2021

    @jakirkham
    Member

    I realise that it would be cleaner to return a new Array instead of modifying it in place

    I think that is the intended usage actually. It's interesting to learn that there are use cases changing the name on existing Array as opposed to building a new one.

  21. added
    needs attention
    on Nov 11, 2024
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

    arrayneeds attention

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions