Skip to content

from_dask_array uses blockwise instead of merging graphs - #8889

Merged
rjzamora merged 9 commits into
dask:mainfrom
bryanwweber:fix-8496
Apr 20, 2022
Merged

rjzamora merged 9 commits into
dask:mainfrom
bryanwweber:fix-8496

Conversation

@bryanwweber

Copy link
Copy Markdown
Contributor

This change uses dask.blockwise to generate the high-level graph for dask.dataframe.from_dask_array. If no index is given and the chunks are known, the graph to generate an index is still created directly. I don't see a way around this, but suggestions are very welcome! cc @ian-r-rose @gjoseph92 @rjzamora

Comment thread dask/dataframe/io/io.py Resolved
Comment thread dask/dataframe/io/io.py Resolved
Comment thread dask/dataframe/io/io.py Resolved
@rjzamora

rjzamora commented Apr 6, 2022

Copy link
Copy Markdown
Member

Nice work @bryanwweber - This is a pretty complicated problem.

If no index is given and the chunks are known, the graph to generate an index is still created directly. I don't see a way around this, but suggestions are very welcome!

I could be missing something, but I do think we should avoid defining a stand-alone graph/collection for the index. If the chunks are known, then it seems like we should absolutely try to calculate the local range index in the same task that converts the underlying chunk array into a DataFrame partition. For example, it wouldn't work now, but it would be nice if we could just just use a DataFrameIOLayer here. #8852 is attempting to do something very similar for from_delayed, and it seems like we should try to think of a design that will work for both of these cases :)

@rjzamora rjzamora left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks again for this Bryan - Perhaps these suggestions will help?

Comment thread dask/dataframe/io/io.py Resolved
Comment thread dask/dataframe/io/io.py Resolved
@bryanwweber

Copy link
Copy Markdown
Contributor Author

@rjzamora Thanks for the suggestion! @ian-r-rose and I talked about this, I had considered creating a new RangeIndexDep class to use for this case. Do you have any thoughts about which would be more efficient/preferable? Ian wasn't sure there were any strong advantages or disadvantages one way or the other.

@rjzamora

Copy link
Copy Markdown
Member

@ian-r-rose and I talked about this, I had considered creating a new RangeIndexDep class to use for this case. Do you have any thoughts about which would be more efficient/preferable? Ian wasn't sure there were any strong advantages or disadvantages one way or the other.

Yeah - I suppose you could define all this logic in a RangeIndexDep class that could be initialized with a list/tuple defining the known size of every output partition. In order to delay the index creation, we would need to use produces_tasks=True. I don't think this approach would be more efficient, but it could make it easier for us to define range indices in other places. With that said, it is not immediately obvious to me where else we would want to do this. If you don't already have another use case in mind, then I'd probably suggest we avoid adding a new class (at least for now).

@bryanwweber bryanwweber self-assigned this Apr 13, 2022
Bryan Weber and others added 5 commits April 18, 2022 13:47
This condition is checked in _meta_from_array, so this line of code is
never covered.
Splits several large tests that have different goals. Uses
match keyword argument to pytest.raises.
Co-authored-by: Richard (Rick) Zamora <[email protected]>
Comment thread dask/dataframe/io/tests/test_io.py Outdated
Comment on lines +383 to +403
def test_create_index_is_blockwise():
x = da.ones((10, 3), chunks=(4, 2))
# The index will be a range from 0-10 with three partitions. Each partition index's
# starting value will be 4 higher than the previous one since chunks=(4, 2).
index_mapping = {
(0,): (0, 4),
(1,): (4, 8),
(2,): (8, 10),
}
df = dd.from_dask_array(x, ["a", "b", "c"])
layer = hlg_layer(df.dask, "from-dask-array")
# The layer to create the DataFrame should create the index using a BlockwiseDep
# If that is the case, then the io_deps dictionary will not be empty.
assert layer.io_deps
# Also test that the BlockwiseDepDict mapping attribute corresponds to the
# RangeIndex that will be created for `x`. There's only one item in the io_deps
# dictionary here, so we avoid a loop with this line. This is specific to
# BlockwiseDepDict, so it'll break if from_dask_array is refactored to use a
# different means of generating the index.
blk_dep = next(iter(layer.io_deps.values()))
assert blk_dep.mapping == index_mapping

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rjzamora Thanks for the suggestions! I adopted them as-is, other than linting 😄

I also added this test, which I'm about 80% sure is valuable. I wanted to assert that the layer creating the index is a HLG/blockwise, since that's what your change enabled. I think this test does that, but it does depend on the specific implementation using BlockwiseDepDict which is... not great? At least, it'll break if the implementation is changed, which IMO means it's not a great test. Happy for your thoughts though!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I agree with your intuition that checking for BlockwiseDepDict usage is not ideal, because we may decide to use a different kind of BlockwiseDep or tweak the design in the future. I do like how thorough this test is, but my preference would be to simply assert that isisntance(layer, Blockwise) here, and to rely on the assert_eq in other tests to ensure that the index is being set correctly.

One other thing you can test is whether dask.blockwise.optimize_blockwise fuses everything down to one Blockwise layer. For example:

from dask.blockwise import Blockwise, optimize_blockwise

graph = optimize_blockwise(df.dask, df.__dask_keys__())
assert len(graph.layers) == 1
assert isinstance(hlg_layer(graph, "from-dask-array"), Blockwise)

(note: I didn't check that this works yet)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rely on the assert_eq in other tests to ensure that the index is being set correctly.

I'm not worried here about the index being set correctly, I'm trying to test that the index is being created by a BlockwiseDep. I also have other tests that check whether or not layer is an HLG at least, the ones that are like assert not hlg_layer_topographical(df.dask, -1).is_materialized(). Unfortunately, the .is_materialized() is true even if the index creation is done non-Blockwise, that is, those tests passed before I adopted your changes. So I was looking for something deeper in the HLG to really assert that the index was a BlockwiseDep.

The easiest way to do that is to assert all(isinstance(dep, BlockwiseDep) for dep in layer.io_deps.values()). I didn't want to import BlockwiseDep into the test module directly though, since it felt icky (don't have a better word 😄) and too specific again. I also considered materializing the graph in this test and checking there (I'm not sure if the BlockwiseDep would be materialized into the low-level graph), but this worked, so I figured I'd push it up for feedback 😄

I think it's not super important to really assert that the index is generated by a BlockwiseDep, but it also felt weird to apply a bunch of changes to the code and not check that they were doing what they were supposed to be doing.

One other thing you can test is whether dask.blockwise.optimize_blockwise fuses everything down to one Blockwise layer.

Happy to add a test for this! Just a note that the BlockwiseDepDict doesn't show up in the layers though, so this would be an assertion that Blockwise is doing what it's supposed to, which is presumably covered elsewhere.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with both you and @rjzamora that delving into the specific shape of BlockwiseDepDict is not ideal, and is best left as an implementation detail.

assert_eq to verify the index still seems like a good idea here: if the range index construction is wrong then this would catch it.

Unfortunately, the .is_materialized() is true even if the index creation is done non-Blockwise

I'm not sure I understand what you mean here, can you elaborate? We should be able to verify some things about the HLG before materialization.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's not super important to really assert that the index is generated by a BlockwiseDep, but it also felt weird to apply a bunch of changes to the code and not check that they were doing what they were supposed to be doing.

Right - I would argue that it is not important at all that the index is generated by a BlockwiseDep, and so there is no reason to test this. We only care that from_dask_array produces a single Blockwise layer. The fact that we use BlockwiseDep for the index is just to make this possible.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would argue that it is not important at all that the index is generated by a BlockwiseDep, and so there is no reason to test this.

Thanks @rjzamora, I think it makes sense to drop the test then.

Unfortunately, the .is_materialized() is true even if the index creation is done non-Blockwise

I'm not sure I understand what you mean here, can you elaborate? We should be able to verify some things about the HLG before materialization.

@ian-r-rose Sorry, that was a brain fart. I meant hlg_layer_topological(df.dask, -1).is_materialized() is False, so that assert not ... is True and the test passes. This happened even when I was constructing the low-level graph directly (dsk = {} ...), because the from-dask-array task hadn't been materialized even though its dependencies were created as a materialized graph. I don't recall what happens if I try to check all the layers though, but I think the point is moot now since I agree with Rick that it makes sense to drop this test as being too specific to the implementation.

@ian-r-rose ian-r-rose left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is looking really great @bryanwweber

Comment thread dask/dataframe/io/io.py Resolved
Comment thread dask/dataframe/io/io.py Resolved
Comment thread dask/dataframe/io/tests/test_io.py Outdated
Comment on lines +383 to +403
def test_create_index_is_blockwise():
x = da.ones((10, 3), chunks=(4, 2))
# The index will be a range from 0-10 with three partitions. Each partition index's
# starting value will be 4 higher than the previous one since chunks=(4, 2).
index_mapping = {
(0,): (0, 4),
(1,): (4, 8),
(2,): (8, 10),
}
df = dd.from_dask_array(x, ["a", "b", "c"])
layer = hlg_layer(df.dask, "from-dask-array")
# The layer to create the DataFrame should create the index using a BlockwiseDep
# If that is the case, then the io_deps dictionary will not be empty.
assert layer.io_deps
# Also test that the BlockwiseDepDict mapping attribute corresponds to the
# RangeIndex that will be created for `x`. There's only one item in the io_deps
# dictionary here, so we avoid a loop with this line. This is specific to
# BlockwiseDepDict, so it'll break if from_dask_array is refactored to use a
# different means of generating the index.
blk_dep = next(iter(layer.io_deps.values()))
assert blk_dep.mapping == index_mapping

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with both you and @rjzamora that delving into the specific shape of BlockwiseDepDict is not ideal, and is best left as an implementation detail.

assert_eq to verify the index still seems like a good idea here: if the range index construction is wrong then this would catch it.

Unfortunately, the .is_materialized() is true even if the index creation is done non-Blockwise

I'm not sure I understand what you mean here, can you elaborate? We should be able to verify some things about the HLG before materialization.

Bryan Weber added 2 commits April 19, 2022 10:06
Add a docstring explaining the types of the arguments.
@bryanwweber

Copy link
Copy Markdown
Contributor Author

@ian-r-rose @rjzamora I just pushed an update that drops the too-specific test and moves _partition_from_array() to a module-level function. I didn't type-annotate the function signature because nothing else here is using type annotations, but I did add a fairly detailed docstring, I hope I got everything correct. Thanks for all your feedback!

@rjzamora rjzamora left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks again for working on this @bryanwweber

I tried adding an optimize_blockwise test to your branch, but quickly learned that this is technically a "reduction" (since "from-dask-array-*" technically depends on two "collections"), and blockwise fusion does not work for such a case :/

It is not immediately clear to me "how" we could go about achieving blockwise fusion in this case, but perhaps that doesn't gain us much anyway. Either way, this PR is a nice improvement.

Comment thread dask/dataframe/io/io.py
Comment on lines +517 to +520
if is_series_like(meta):
kwargs = {"dtype": x.dtype, "name": meta.name, "initializer": type(meta)}
else:
kwargs = {"columns": meta.columns, "initializer": type(meta)}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a note that the index and intializer can both be defined in arrays_and_indices, rather than being included as kwargs. However, I don't think that gains us any readability or performance, so I'm good with what you already have.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @rjzamora! I wasn't sure what the indices for type(meta) would be, presumably the same as the input? In any case, I'm glad to know that's possible for the future.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe if they are scalars then the indices would be None. But I also think it's fine as-is in kwargs

Comment thread dask/dataframe/io/io.py Resolved
Comment thread dask/dataframe/io/io.py Resolved

@ian-r-rose ian-r-rose left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a few nitpicky comments, which I think are optional, but I'm happy where this stands now!

@ian-r-rose

Copy link
Copy Markdown
Collaborator

I tried adding an optimize_blockwise test to your branch, but quickly learned that this is technically a "reduction" (since "from-dask-array-*" technically depends on two "collections"), and blockwise fusion does not work for such a case :/

That's unfortunate! In what way does it depend on two collections? It would be nice, for instance, to be able to fuse from_zarr + from_dask_array + assign + groupby or whatever.

@rjzamora

rjzamora commented Apr 19, 2022 •

Copy link
Copy Markdown
Member

That's unfortunate! In what way does it depend on two collections? It would be nice, for instance, to be able to fuse from_zarr + from_dask_array + assign + groupby or whatever.

Exactly my thought. I suppose you do get full fusion if there is not index and the chunksize is not "known." However, any case where we need to use a BlockwiseDep (or a real collection dependency), then the new DataFrame collection depends on the original Array collection and the temporary index collection :/

@bryanwweber

bryanwweber commented Apr 19, 2022 •

Copy link
Copy Markdown
Contributor Author

Thanks @ian-r-rose! I added the two changes you suggested 👍 I'm seeing (seemingly) unrelated and random failures in parts of the test suite here on CI. One time was on Ubuntu/py3.10, the next was on Windows/py3.10...

@ian-r-rose

Copy link
Copy Markdown
Collaborator

Exactly my thought. I suppose you do get full fusion if there is not index and the chunksize is not "known." However, any case where we need to use a BlockwiseDep (or a real collection dependency), then the new DataFrame collection depends on the original Array collection and the temporary index collection :/

That's really unfortunate, how hard do you think it would be to remove that restriction? I suppose we are talking about this block?

dask/dask/blockwise.py

Lines 1293 to 1305 in 9000abd

for d in full_graph.dependencies.get(dep, ()):
# Don't allow reductions to proceed
output_indices = set(layers[dep].output_indices)
input_indices = {
i for _, ind in layers[dep].indices if ind for i in ind
}
if len(dependents[d]) <= 1 and output_indices.issuperset(
input_indices
):
deps.add(d)
else:
stack.append(d)

@rjzamora

Copy link
Copy Markdown
Member

That's really unfortunate, how hard do you think it would be to remove that restriction? I suppose we are talking about this block?

Yep - That's exactly where we loose the optimization.

I'll probably need to think a bit about this one. There is probably a good reason why we have avoided fusing reductions so fare, but it definitely seems like something we should be able to do (even if it is for a very restricted set of cases...).

@ian-r-rose

Copy link
Copy Markdown
Collaborator

From the git blame: #4207

I'll bet we can (at the very least) make an exception for BlockwiseDeps

@ian-r-rose

Copy link
Copy Markdown
Collaborator

(I should note, I see no reason to block this PR on the above discussion)

@bryanwweber

Copy link
Copy Markdown
Contributor Author

FYI I'm done with changes and all tests are green

@rjzamora
rjzamora merged commit 99e2600 into dask:main Apr 20, 2022
@rjzamora

Copy link
Copy Markdown
Member

Thanks for the nice improvement @bryanwweber !

We can (hopefully) address blockwise fusion in a follow-up.

@rjzamora

rjzamora commented Apr 20, 2022 •

Copy link
Copy Markdown
Member

From the git blame: #4207
I'll bet we can (at the very least) make an exception for BlockwiseDeps

@ian-r-rose - Just to follow up on this. It does seem that the "reduction" issue is easy to resolve. However, there is also a trickier problem that I didn't see before: The need for concatenate=True in from_dask_array. Since the concatentate keyword changes the way indices are handled, the current optimization logic assumes two layers with different concatenate settings should never be fused. concatenate docstring for reference:

concatenate: bool
Whether or not to pass contracted dimensions as a list of inputs or a
single input to the block function

I'll have to think if there is a way around this for the general case. We can certainly avoid setting concatenate=True when the shape of the input Dask array is one dimensional, but that would only cover the creation of Series collections.

@bryanwweber
bryanwweber deleted the fix-8496 branch April 20, 2022 15:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

from_dask_array materializes the graph unnecessarily

4 participants