Skip to content

from_dask_array materializes the graph unnecessarily #8496

Closed

Description

@gjoseph92

dask.dataframe.from_dask_array has many instances of ensure_dict and low-level dict-merging, which is both inefficient and will prevent any optimizations from being applied to those layers (without #8447).

Convert from_dask_array to use and merge HighLevelGraphs properly. xref #8306

meta = _meta_from_array(x, columns, index, meta=meta)
if x.ndim == 2 and len(x.chunks[1]) > 1:
x = x.rechunk({1: x.shape[1]})
name = "from-dask-array" + tokenize(x, columns)
to_merge = []
if index is not None:
if not isinstance(index, Index):
raise ValueError("'index' must be an instance of dask.dataframe.Index")
if index.npartitions != x.numblocks[0]:
msg = (
"The index and array have different numbers of blocks. "
"({} != {})".format(index.npartitions, x.numblocks[0])
)
raise ValueError(msg)
divisions = index.divisions
to_merge.append(ensure_dict(index.dask))
index = index.__dask_keys__()
elif np.isnan(sum(x.shape)):
divisions = [None] * (len(x.chunks[0]) + 1)
index = [None] * len(x.chunks[0])
else:
divisions = [0]
for c in x.chunks[0]:
divisions.append(divisions[-1] + c)
index = [
(np.arange, a, b, 1, "i8") for a, b in zip(divisions[:-1], divisions[1:])
]
divisions[-1] -= 1
dsk = {}
for i, (chunk, ind) in enumerate(zip(x.__dask_keys__(), index)):
if x.ndim == 2:
chunk = chunk[0]
if is_series_like(meta):
dsk[name, i] = (type(meta), chunk, ind, x.dtype, meta.name)
else:
dsk[name, i] = (type(meta), chunk, ind, meta.columns)
to_merge.extend([ensure_dict(x.dask), dsk])
return new_dd_object(merge(*to_merge), name, meta, divisions)

Activity

  1. scharlottej13 commented on Jan 12, 2022

    @scharlottej13
    Contributor

    @gjoseph92 would you be able to provide a little more detail on this in case a new contributor would like to pick it up?

  2. gjoseph92 commented on Jan 12, 2022

    @gjoseph92
    CollaboratorAuthor

    I would probably not recommend this for a new contributor. After reading through the current code, I think I would approach this by rewriting it with a different approach: rather than generating graphs, you can fully express this operation using the high-level Array and DataFrame APIs, then da.map_blocks/da.blockwise/dd.map_partitions (not sure which yet) to combine the array with the new index and convert it to a DataFrame.

    But this will require a decent understanding of blockwise, which may not be documented well enough yet for someone to be able to pick up.

  3. self-assigned this
    on Mar 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions