Repository navigation
Move DataFrame ACA aggregations to HLG - #8468
Conversation
|
@rjzamora do you have a sense of who could review this? |
That is a great questions :) Perhaps @jrbourbeau, @gjoseph92 and/or @ian-r-rose have time to take a look? |
| class CallablePickled: | ||
| """Wrapper for a pickled "User-Defined" Function | ||
|
|
||
| This Class should be used to wrap user-defined | ||
| functions used within HLG Layers. The idea here | ||
| is to avoid the need for explicit unpickling in | ||
| the user code. | ||
| """ | ||
|
|
||
| def __init__(self, function): | ||
| if isinstance(function, CallablePickled): | ||
| self.function = function.function | ||
| self.function = function | ||
|
|
||
| def __call__(self, *args, **kwargs): | ||
| if isinstance(self.function, bytes): | ||
| import pickle | ||
|
|
||
| self.function = pickle.loads(self.function) | ||
| return self.function(*args, **kwargs) |
There was a problem hiding this comment.
I am interested to know how others feel about this new class. Do others feel that there are more-elegant ways to side-step explicit serialization/deserialization of user-defined functions?
There was a problem hiding this comment.
Anything that involves serialization within tasks is a -1 from me. I also don't like the lack of caching; I think that every task will deserialize to a separate CallablePickled object, so then we'll also be unpickling the function on every task invocation.
What's wrong with wrapping the functions in to_serialize? I imagine that causes double-serialization in dumps_task, but would this make it work?
diff --git a/distributed/worker.py b/distributed/worker.py
index b3ffb347..9cea849b 100644
--- a/distributed/worker.py
+++ b/distributed/worker.py
@@ -21,6 +21,8 @@ from inspect import isawaitable
from pickle import PicklingError
from typing import TYPE_CHECKING, Any, ClassVar
+from distributed.protocol.serialize import Serialize, Serialized
+
if TYPE_CHECKING:
from typing_extensions import Literal
from .diagnostics.plugin import WorkerPlugin
@@ -4098,8 +4100,10 @@ cache_dumps = LRU(maxsize=100)
_cache_lock = threading.Lock()
-def dumps_function(func) -> bytes:
+def dumps_function(func) -> bytes | Serialize | Serialized:
"""Dump a function to bytes, cache functions"""
+ if isinstance(func, (Serialize, Serialized)):
+ return func
try:
with _cache_lock:
result = cache_dumps[func]There was a problem hiding this comment.
I think I agree, but I'm also a bit confused. I seem to remember that the main downside of using to_serialze is that you do not get function caching. Perhaps I am mistaken or this limitation has changed now? To be honest, my primary motivation for CallablePickled was to enable caching. However, I'm certainly willing to believe that I was completely confused here :)
There was a problem hiding this comment.
I could see that, because maybe the deserialization happens at the comm level, as opposed to worker.loads_function, which has its own cache.
But I think this is a different case no matter what, because we have complex tasks here (due to the nested concatenation). Looking at dumps_task, the tasks in this case are going to fail the elif not any(map(_maybe_complex, task[1:])): check on L4364. So it's going to hit the final to_serialize(task), meaning serialization will happen at the comm level. (And deserialization as well).
So I think caching is basically a moot point for this case; we don't get it either way.
There was a problem hiding this comment.
Thanks again for the great review @gjoseph92. This is the only remaining suggestion that I am still unsure how to resolve. I added CallablePickled so that I could more-or-less avoid the need to solve the larger HLG serialization challenge. I absolutely agree that deserialization within the task is absolutely not what we want. However, it seems like we will need to make some significant changes in distributed to enable us to use to_serialize here.
The Challenge
There is certainly the double-serialization issue you aknowledged. However, it also seems that we need a mechanism to ensure that the the Serialized object is marked as "callable" when it reaches the scheduler. When I try wrapping the functions in to_serialize in __dask_distributed_pack__, the nested tasks are not being recognized as such at deserialization time. Since the first element of the tuple is no-longer a callable object, I am getting errors like: Exception: 'AttributeError("\'tuple\' object has no attribute \'groupby\'")'.
Perhaps there is already an existing solution I am missing? cc @madsbk (Just in case you have thoughts as well)
There was a problem hiding this comment.
I'll start by saying that you know a lot more about the serialization code path than I do (for some reason, it falls out of my head immediately) :)
I'm confused why the scheduler would need to look at the contents of a task at all?
Right - I don't think the scheduler should "look" at the contents of a task. My worry was that the second Serialize pass may need to know about the original callable objects "callable" nature. There is a good chance that this worry is completely wrong, and the problem is somewhere else altogether.
Scheduler creates the nested task and serializes it with dumps_task, which uses to_serialize on the task tuple here. So you'd have Serialize((Serialize(func), ..., (Serialize(concat), ...)).
Perhaps it doesn't make as much of a difference as I thought, but you'd actually have Serialized objects in the task: Serialize((Serialized(func), ..., (Serialized(concat), ...))
Worker.handle_compute_task receives the message and stores the runspec here. I am assuming that comms has fully unpacked the Serialize objects, so task is already the complete tuple. This would probably be the place to check. Maybe it's not traversing properly?
Good point - I will need to check if something is off here.
There was a problem hiding this comment.
Ok, if you apply this diff to your PR:
diff --git a/dask/layers.py b/dask/layers.py
index b740bfb7..bcd7f95c 100644
--- a/dask/layers.py
+++ b/dask/layers.py
@@ -1557,19 +1557,16 @@ class DataFrameTreeReduction(DataFrameLayer):
return self, deps
def __dask_distributed_pack__(self, *args, **kwargs):
- import pickle
+ from distributed.protocol.serialize import to_serialize
- # Pickle the (possibly) user-defined functions here.
- # We also wrap kwargs into the functions themselves
- # to simplify serialization
- _concat_func = pickle.dumps(self.concat_func)
- _tree_node_func = pickle.dumps(
+ _concat_func = to_serialize(self.concat_func)
+ _tree_node_func = to_serialize(
partial(self.tree_node_func, **self.tree_node_kwargs)
if self.tree_node_kwargs
else self.tree_node_func
)
if self.finalize_func:
- _finalize_func = pickle.dumps(
+ _finalize_func = to_serialize(
partial(self.finalize_func, **self.finalize_kwargs)
if self.finalize_kwargs
else self.finalize_func
@@ -1595,13 +1592,6 @@ class DataFrameTreeReduction(DataFrameLayer):
def __dask_distributed_unpack__(cls, state, dsk, dependencies):
from distributed.worker import dumps_task
- # Deal with `Serialized` user-defined functions
- state["tree_node_func"] = CallablePickled(state.get("tree_node_func"))
- state["concat_func"] = CallablePickled(state.get("concat_func"))
- finalize_func = state.get("finalize_func", None)
- if finalize_func:
- state["finalize_func"] = CallablePickled(finalize_func)
-
# Materialize the layer
raw = cls(**state)._construct_graph()And this to distributed:
diff --git a/distributed/scheduler.py b/distributed/scheduler.py
index 1776a799..4cc09b74 100644
--- a/distributed/scheduler.py
+++ b/distributed/scheduler.py
@@ -8119,6 +8119,7 @@ def _task_to_msg(state: SchedulerState, ts: TaskState, duration: double = -1) ->
msg.update(task)
else:
msg["task"] = task
+ print("Sent by scheduler:", task)
if ts._annotations:
msg["annotations"] = ts._annotations
diff --git a/distributed/worker.py b/distributed/worker.py
index 232e943a..a39cf7b5 100644
--- a/distributed/worker.py
+++ b/distributed/worker.py
@@ -1958,6 +1958,8 @@ class Worker(ServerNode):
except KeyError:
self.tasks[key] = ts = TaskState(key)
+ if task is not no_value:
+ print("Received by worker:", task)
ts.runspec = SerializedTask(function, args, kwargs, task)
if priority is not None:And run pytest dask/tests/test_distributed.py::test_serializable_groupby_agg, you'll get the AttributeError: 'tuple' object has no attribute 'groupby', and see this stdout (added line breaks for clarity):
Sent by scheduler: <Serialize: (
<distributed.protocol.serialize.Serialized object at 0x7fd4a0b22850>,
(<distributed.protocol.serialize.Serialized object at 0x7fd4a0b226d0>, ["('aggregate-chunk-af7341a27f9acaf09b2f7c7ac0f735b1-62a7c942e290c6e47ac25e375db5d1dc', 0)", "('aggregate-chunk-af7341a27f9acaf09b2f7c7ac0f735b1-62a7c942e290c6e47ac25e375db5d1dc', 1)"])
)>
Received by worker: (
functools.partial(<function _agg_finalize at 0x7fd4a0a3c160>, aggregate_funcs=[('count-x-caf6abc2c5c9c7a4c1b06ad5806fad59', <function _apply_func_to_column at 0x7fd4a0a3c1f0>, {'column': 'count-x-caf6abc2c5c9c7a4c1b06ad5806fad59', 'func': <methodcaller: sum>})], finalize_funcs=[('x', <dask.utils.itemgetter object at 0x7fd4f2895670>, {})], level=0),
(<distributed.protocol.serialize.Serialized object at 0x7fd4f2895640>, ["('aggregate-chunk-af7341a27f9acaf09b2f7c7ac0f735b1-62a7c942e290c6e47ac25e375db5d1dc', 0)", "('aggregate-chunk-af7341a27f9acaf09b2f7c7ac0f735b1-62a7c942e290c6e47ac25e375db5d1dc', 1)"])
)
So it seems there's a bug in nested-Serialized deserialization. We're deserializing the top-level object, which becomes a tuple, and clearly traversing one level into that tuple, because the first Serialized object within it turns into the functools.partial(<function _agg_finalize.... But the second element in the tuple is another tuple—and we don't seem to traverse into that tuple. That causes the problem.
Now I need to figure out where this deserialization-traversal logic even happens.
There was a problem hiding this comment.
Ok, I spent some time in the debugger. It's hard to even say where the problem is, because there are so many problems. The handling of Serialized objects is just poorly-defined, mostly because the whole serialization scheme is a mess.
The issue is actually on the serialization side, not deserialization.
Recall that the data in question looks like Serialize( tupleA(Serialize(func), tupleB(Serialized(func), "x", "y") )).
- When
protocol.serialize:serializeencounters aSerializeobject, it recurses into itself on the wrapped data, and setsiterate_collection=Truehere. - This iterates through tupleA correctly here. We recurse into
serializetwice, once for each of the elements in tupleA: - The first recursive call is passed
Serialize(func). We again identify that as a Serialize object, and recurse to process its data (which is just a function). All good. - The second recursive call is passed
tupleB(Serialize(func), "x", "y"). Note that we do not pass through theiterate_collectionargument, so the recursive call isserialize(tupleB, ..., iterate_collections=None)- So since
iterate_collection is None, we check if the object is a tuple here - We then check if the object contains "dask-serializable" data here
- In
check_dask_serializablehere, we check if there's a dispatcher registered for the type of only the first element in the collection. The first element of the collection is aSerialize. (Only checking the first element, and assuming all are the same type, seems like a bad assumption. But in this case it doesn't actually affect us.) - There is no dask serializer registered for
Serializeobjects. So we decide thatiterate_collections=False. - Because we're not iterating collections, we never traverse into the tuple and discover that the first element in a
Serializeobject. - We end up pickling the whole tuple here.
- So since
- Therefore, at deserialization time, the pickled blob (correctly) just gets deserialized back into tupleB, which contains a
Serializeobject within it
There are a few ways I can think of to make this code path not happen:
- When iterating collections, we could pass down the
iterate_collectionargument. That would mean that if aSerializeobject contained other deeply-nestedSerializeobjects, they'd always get fully unpacked. OTOH, any lists/tuples/etc that didn't need to be unpacked would still be unpacked. This feels heavy-handed but somewhat reasonable? - Register a dask serializer for
Serialize, so thatcheck_dask_serializablereturns True and we iterate collections again. Doesn't make much sense. Extremely specific fix for just this exact scenario. - @rjzamora, just don't generate a nested task. This is by far the easiest and what we should do here.
You can easily redefine any nested task to be a simple task. Here, something likedef _define_task(self, input_keys, final_task=False): # Define nested concatenation and func task def concat_and_apply(func, concat_func, inputs, kwargs=None): # TODO move out of nested scope conc = concat_func(inputs) return func(conc, **kwargs) if kwargs else func(conc) if final_task and self.finalize_func: func = self.finalize_func kwargs = self.finalize_kwargs else: func = self.tree_node_func kwargs = self.tree_node_kwargs if kwargs: return (concat_and_apply, func, self.concat_func, input_keys, kwargs) else: return (concat_and_apply, func, self.concat_func, input_keys)
I think we should just sidestep the nested-serialization issue here, because that problem is so messy. But in general, we either need to figure out a way to handle nested-serialization cleanly, or a structural way to avoid it and prohibit it entirely, so we don't keep getting lost in this mess.
There was a problem hiding this comment.
Thanks for investigating @gjoseph92 ! I was just trying to work out a "clean" way to get iterate_collection=True behavior, but I didn't consider that it may be worth avoiding the issue altogether for now. You are totally right that the nested task will always be the concat-based function. So, your work-around should probably do the trick for us :)
But in general, we either need to figure out a way to handle nested-serialization cleanly, or a structural way to avoid it and prohibit it entirely, so we don't keep getting lost in this mess.
I think this should be treated as high-priority for sure. I think we are in desperate need of a simple/robust serialization stratety for HLGs (that or we just need to decide that we will stop sending them to the scheduler :) ).
There was a problem hiding this comment.
I think we are in desperate need of a simple/robust serialization stratety for HLGs (that or we just need to decide that we will stop sending them to the scheduler :) )
Well said! I hope we can come up with some answers in dask/distributed#5581.
| class CallablePickled: | ||
| """Wrapper for a pickled "User-Defined" Function | ||
|
|
||
| This Class should be used to wrap user-defined | ||
| functions used within HLG Layers. The idea here | ||
| is to avoid the need for explicit unpickling in | ||
| the user code. | ||
| """ | ||
|
|
||
| def __init__(self, function): | ||
| if isinstance(function, CallablePickled): | ||
| self.function = function.function | ||
| self.function = function | ||
|
|
||
| def __call__(self, *args, **kwargs): | ||
| if isinstance(self.function, bytes): | ||
| import pickle | ||
|
|
||
| self.function = pickle.loads(self.function) | ||
| return self.function(*args, **kwargs) |
There was a problem hiding this comment.
Anything that involves serialization within tasks is a -1 from me. I also don't like the lack of caching; I think that every task will deserialize to a separate CallablePickled object, so then we'll also be unpickling the function on every task invocation.
What's wrong with wrapping the functions in to_serialize? I imagine that causes double-serialization in dumps_task, but would this make it work?
diff --git a/distributed/worker.py b/distributed/worker.py
index b3ffb347..9cea849b 100644
--- a/distributed/worker.py
+++ b/distributed/worker.py
@@ -21,6 +21,8 @@ from inspect import isawaitable
from pickle import PicklingError
from typing import TYPE_CHECKING, Any, ClassVar
+from distributed.protocol.serialize import Serialize, Serialized
+
if TYPE_CHECKING:
from typing_extensions import Literal
from .diagnostics.plugin import WorkerPlugin
@@ -4098,8 +4100,10 @@ cache_dumps = LRU(maxsize=100)
_cache_lock = threading.Lock()
-def dumps_function(func) -> bytes:
+def dumps_function(func) -> bytes | Serialize | Serialized:
"""Dump a function to bytes, cache functions"""
+ if isinstance(func, (Serialize, Serialized)):
+ return func
try:
with _cache_lock:
result = cache_dumps[func]|
I really appreciate the awesome review @gjoseph92 ! I'll revise soon :) |
|
@gjoseph92 - I think this was pretty close to "ready" when we last iterated on it in December. Any remaining thoughts/concerns here? |
| # Deal with single-partition case | ||
| for s in self.output_partitions: | ||
| input_keys = [self._make_key(name_input_use, 0, split=s)] | ||
| dsk[(self.name, s)] = self._define_task(input_keys, final_task=True) |
There was a problem hiding this comment.
How does split_out factor into this?
There was a problem hiding this comment.
output_partitions is essentially the list version of split_out (list(range(split_out))). We convert split_out to this list form to make culling possible.
There was a problem hiding this comment.
Ahh I think I see. I was thinking about a not-very-treelike case of 20 inputs, split_every=40, so you just have one output task that takes 20 inputs. But that's still height == 2. The only way this case can happen is if npartitions_input <= 1.
| concat_func: Callable | ||
| tree_node_func: Callable | ||
| finalize_func: Optional[Callable] |
There was a problem hiding this comment.
| concat_func: Callable | |
| tree_node_func: Callable | |
| finalize_func: Optional[Callable] | |
| concat_func: Callable[[List[T]], CT] | |
| tree_node_func: Callable[[CT], OT] | |
| finalize_func: Optional[Callable[[CT], OT]] |
I think this is accurate? Where T probably means pd.DataFrame for now. But I could see wanting to generalize this tree reduction layer to arrays, etc. too? Maybe DataFrameTreeReduction should be generic on T, OT (the input type and output type)?
I personally find these sort of detailed annotations helpful, but maybe others don't.
There was a problem hiding this comment.
This is another case where the underlying types may be pd.DataFrame or cudf.DataFrame. Do the Callable's argument types need to be specified to make type-checking useful here? (I don't know much about python type checking)
There was a problem hiding this comment.
I just liked the idea of noting that concat_func produces something that tree_node_func and finalize_func have to be able to consume. Even if the input and output types (T, OT) aren't specified, a type-checker could still validate that part. But it may not be worth it right now.
| # Deal with single-partition case | ||
| for s in self.output_partitions: | ||
| input_keys = [self._make_key(name_input_use, 0, split=s)] | ||
| dsk[(self.name, s)] = self._define_task(input_keys, final_task=True) |
There was a problem hiding this comment.
Ahh I think I see. I was thinking about a not-very-treelike case of 20 inputs, split_every=40, so you just have one output task that takes 20 inputs. But that's still height == 2. The only way this case can happen is if npartitions_input <= 1.
|
Looks like some conflicts crept in here. Though appears minor just |
|
@rjzamora this is looking good to me. But I just realized—are there any tests that trigger the culling functionality? And the pack/upack? I realized there aren't any unit tests for the layer itself, it just gets exercised through groupby tests, etc. But perhaps there are certain cases which should be tested, and aren't being exercised in that way. |
Fair enough - The new layer certainly has a lot of test coverage in the form of general aggregation and groupby tests. However, I updated tests in |
This PR adds a new
DataFrameTreeReductionHighLevelGraph (HLG) layer and re-implements the apply-concat-apply (ACA) logic to use the new layer type (along withBlockwise). The primary motivation for this PR is to reduce the number of common cases where Dask-Dataframe constructs raw graphs, and where skipping low-level task fusion may be a problem. For example, consider the following groupby aggregation:On
main, this HLG forresultwill contain only two layers (aDataFrameIOLayerlayer used for timeseries creation, and aMaterializedLayerfor the groupby aggregation):Since the only HLG-level fusion mechanism is between
Blockwise-based layers, there is no way to achieve "complete" task fusion in the low-level graph without materializing it on the client. It is clear from a visualization of the "HLG-optimized" graph that there are missed opportunities for fusion (note the aligned tasks at the bottom):By implementing a new
DataFrameTreeReductionlayer, and by breaking the ACA algorithm into a combination ofBlockwiseandDataFrameTreeReductionlayers, we resolve the fusion problem for many aggregations in Dask-Dataframe (including groupby aggregations):See #8447 for motivation
Note that I am also compiling notes on the process I followed here to possibly help with address #7709 (and related)