You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here's a case where I would expect slices to be pushed down through Blockwise
importdaskdask.config.set({'array.query-planning': True})
importxarrayasxr# This `108` chunksize is important; it is large enough to trigger automatic rechunking by flox# FIXME: be more aggressive about rechunking with exprds=xr.tutorial.open_dataset("air_temperature", chunks={"time": 108})
arr=ds.air# this rechunks so that the groupby-reduction can be applied blockwise# this output has chunksize of 1 along `time`clim=arr.resample(time="ME").mean()
# let's select just three months, so 3 chunkssubset=clim.sel(time=slice("2013-01", "2013-03"))
# I would expect the slice to be pushed down to both FromArray layers, but it is notsubset.data.expr.simplify()
PS: I'm happy to take a stab at resolving this tomorrow.
Sorry I'm still struggling. How did you produce the air.zarr file. You all may be assuming that I have more familiarity with xarray than I actually do.
Now you're saying that you want the getitem to traverse down through the groupby nanmean. It looks like the Getitem/Slice is slicing in the last dimension, but the groupby nanmean is also affecting that dimension, which is why dask array is being nervous about moving it through.
In dask array parlance the groupby nanmean is a blockwise (sorry, this is going to get a little ugly for a moment, but I figure it's good education).
Now, we're happy in general to push a slice through a blockwise, but we're nervous if that blockwise adjusts the chunking of the underlying array, which this certainly does. [n:m] has to be translated somehow into [f(n): f(m)] and we don't know how to do that here in general. Probably Xarray does though, through the use of the time index. This might be a case where we need some sort of Xarray expression rather than a Dask array expression. I think that Dask array (or any underlying ndarray abstraction) doesn't have the necessary metadata to do this transformation safely. I suspect that this optimization has to be done within the Xarray abstraction.
Open to thoughts. My main question right now is how much of the value of expression optimization requires Xarray knowledge, and how much of it can be done purely within the ndarray abstaction.
Or, if we didn't want to Expr-ify Xarray, we could make some other traversal system that went through and applied optimizations. This would probably be less invasive and not that hard, but it would have to live here I think.
My thinking is that the blockwise takes in a chunk of size m, outputs a chunk of size n, so a slice that aligns with chunk boundaries e.g. slice(n, 3n) is fine to push down as slice(m, 3m) (or appropriately modified). Basically, block-slicing of blockwise is fine in theory. But now I can see that this is a little hard with general blockwise since there is an arbitrary function to transform chunks (the m->n mapping).
One thing I've been toying around with is whether flox needs to insert its own expr layer, instead of relying on general blockwise. This seems like a reason to do so.
Having your own Expr layer thats more specific than Blockwise would make this much easier to resolve.
My thinking is that the blockwise takes in a chunk of size m, outputs a chunk of size n, so a slice that aligns with chunk boundaries e.g. slice(n, 3n) is fine to push down as slice(m, 3m)
Yeah, historically we used to allow adjust_chunks to be a function. I could imagine something like what you're describing being more possible (but still probably not doable in general) in that world. In our case we just store a dict of new chunks now (it's hard to send a callable to the scheduler).
FWIW I suspect that Claude, given the context in the dask repo, could probably implement that new expression for you if given enough description of what you're trying to accomplish.
In our case we just store a dict of new chunks now
In that case if the applied slice indices are present in cumsum(new_chunks), you can back out which "source" chunks are needed on all source arrays.
Happy to do this in flox, but I bet someone is going to expect this. It's also a pretty high-impact optimization I would think (blockwise being so pervasive)
In that case if the applied slice indices are present in cumsum(new_chunks), you can back out which "source" chunks are needed on all source arrays.
Maybe I need to better understand what flox is doing. This is a cumreduction? If so, why did the shape change? I'm quite happy to add more optimizations into dask array expressions (that's what it's there for) I just don't understand this situation well enough to understand what the pattern is. My understanding currently is that Flox is doing some blockwise operation with highly custom chunk changing. In that situation there's not much we can do. If Flox is actually doing some other more specific dask array operation (like calling cumreduction) and if there's some optimization we can do there I'm more than happy to work on it. I just need to learn more.
I can work on a pure dask.array example tonight. Here is a visual from the docs [each square is a single array element; each color is a different group; gaps between groups of elements indicate a chunk boundary]:
If I apply a slicer aligned with blocks on the output (say slice(0, 4) => slice out the first two blocks); then to compute that i only need slice(0, 16) on the input (first two blocks of the input after rechunking). The blockwise applies a groupby-reduction per block which is why the chunk sizes change. Because of the intelligently chosen chunking, it happens to be a reduction without cross-block dependencies, so block-aligned slicing can be pushed down.
Does the expr branch still cull or are we relying on pushdown to remove the need to cull?
Does the expr branch still cull or are we relying on pushdown to remove the need to cull?
We're relying on slice pushdown to remove the need to cull. Beyond this, maybe the scheduler handles it. It's not something that task graphs are thinking about though.
If I apply a slicer aligned with blocks on the output (say slice(0, 4) => slice out the first two blocks); then to compute that i only need slice(0, 16) on the input (first two blocks of the input after rechunking). The blockwise applies a groupby-reduction per block which is why the chunk sizes change. Because of the intelligently chosen chunking, it happens to be a reduction without cross-block dependencies, so block-aligned slicing can be pushed down.
We only know that we only need the first two blocks in this case because we get to look at the colors though, right? This [:4] -> [:16] result doesn't hold generally for all groupby-reduction operations, right? I suspect that in this case the colors are coming from the index, is that right? So we need to have the index on-hand in order to make this optimization safely. If so, my guess is that the Flox expression will have access to that Index as it performs the optimization. That's the piece of information that the Dask array expressions are missing.
importdask.arrayimportnumpyasnparray=dask.array.ones((10,), chunks=((2, 3, 4, 1),))
deffunc(a):
returna.sum(keepdims=True)
res=dask.array.blockwise(
func,
"i",
array,
"i",
# this seems unnecessaryadjust_chunks={0: (1,)*len(array.chunks[0])},
)
dask.array.assert_eq(res.compute(), np.array([2., 3, 4, 1])) # fails without compute# the result is wrong but # the slice should be pushed down to the inputs. we only need `array[slice(5)]` to compute this resultdask.array.assert_eq(res[:2].compute(), np.array([2., 3]))
importdask.arrayimportnumpyasnparray=dask.array.ones((10,), chunks=((2, 3, 4, 1),))
by=np.array([0, 1, 2, 2, 3, 4, 4, 4, 4, 5])
deffunc(a, b):
out=np.zeros(b.max() +1)
print('\n', a, b, out)
np.add.at(out, b, a)
returnout[b.min():b.max() +1]
res=dask.array.blockwise(
func,
"i",
array,
"i",
by,
"i",
adjust_chunks={0: (2, 2, 1, 1)}, # this seems unnecessarymeta=array._meta,
)
dask.array.assert_eq(res.compute(), np.array([1., 1, 2, 1, 4, 1])) # fails without compute# the result is wrong but # the slice should be pushed down to the inputs. we only need `array[slice(5)]` to compute this resultdask.array.assert_eq(res[:2].compute(), np.array([1., 1]))
Here's the first 30s of the conversation. Mostly sharing here to convey that this is something that other people can do too:
Working on array expressions I'm curious about an optimization that pushes slices through
blockwises, at least partially, even if adjust_chunks is set.
If a slice after a blockwise only needs to engage a few of the output blocks, then we know that we
only need the those relevant input blocks as well (blockwise is constrained to operate by block after
all). The idea here is that we could inject a new slice onto the inputs of a blockwise even if
adjust_chunks is set to only select the relevant blocks. Thoughts on this?
As usual, I think that we should start with some tests (we'll have to think through things like the
simple blockwise case, a multi-input blockwise case, a case where the dimensions move around, etc.)
and then think about how to solve.
⏺ This is an interesting optimization idea. Let me activate the relevant skills first.
⏺ /expr-optimization
⏺ This is a good optimization idea. The key insight is that even when adjust_chunks prevents full slice pushdown, we can still do "block-level" selection - if we only need output blocks 2-4, we only need input blocks 2-4 (for aligned dimensions).
Let me first explore the current slice pushdown implementation to understand what we're building on:
⏺ Search(pattern: "dask/array/_array_expr/slicing/*.py")
⎿ Found 7 files (ctrl+o to expand)
⏺ Search(pattern: "adjust_chunks", path: "dask/array/_array_expr/slicing")
⎿ Found 0 files
You'll also want the /array-expr skill
⏺ Search(pattern: "adjust_chunks", path: "dask/array/_array_expr")
⎿ Found 10 files (ctrl+o to expand)
⏺ Let me look at the current slice-through-blockwise implementation and the Blockwise class:
⏺ Now I understand the current state. Looking at _accept_slice in _blockwise.py:404-517, it currently rejects slices when adjust_chunks is set on a sliced dimension (lines 434-439).
The optimization you're proposing is: even when we can't push the exact slice through (because chunk sizes change), we can still do a "coarse" block-level selection. If output slice only needs blocks 2-4, we only need input blocks 2-4.
Let me create a test file to explore the cases:
Test file
⏺ Write(dask/array/_array_expr/tests/test_coarse_slice_through_blockwise.py)
──────────────────────────────────────────────────────────────────────────────────────────────────────────
Createfiledask/array/_array_expr/tests/test_coarse_slice_through_blockwise.py
╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
1"""Tests for coarse slice pushdown through Blockwise with adjust_chunks. 2 3 When a Blockwise has adjust_chunks set, we can't push the exact slice through 4 because input/output chunk boundaries don't align. However, we CAN still do 5 a "coarse" optimization: if the output slice only needs certain blocks, we 6 only need the corresponding input blocks. 7 8 This is a block-level optimization, not an element-level optimization. 9 """1011from __future__ importannotations1213importnumpyasnp14importpytest1516importdask.arrayasda17fromdask.array.utilsimportassert_eq1819pytestmark=pytest.mark.skipif(
20notda._array_expr_enabled(), reason="array_expr not enabled"21 )
222324# =============================================================================25# Case 1: Simple - single input with adjust_chunks26# =============================================================================272829deftest_coarse_slice_simple_adjust_chunks():
30"""Coarse slice through blockwise that doubles chunk size. 31 32 x has 10 blocks of 10 elements each (100 total). 33 blockwise doubles each block to 20 elements (200 total). 34 Slicing [:20] needs only output block 0, which needs only input block 0. 35 """36arr=np.arange(100)
37x=da.from_array(arr, chunks=10)
3839# Each block doubles in size40defdouble_elements(block):
41returnnp.repeat(block, 2)
4243y=da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
44asserty.shape== (200,)
4546# Slice first 20 elements - this is exactly output block 047result=y[:20]
4849# Should be correct50expected=np.repeat(arr, 2)[:20]
51assert_eq(result, expected)
5253# Optimization check: should need fewer tasks than full computation54full_tasks=len(y.optimize().__dask_graph__())
55sliced_tasks=len(result.optimize().__dask_graph__())
5657# With coarse slice optimization, should need ~1/10 the tasks58# (1 input block + 1 map_blocks + 1 slice vs 10+10)59assertsliced_tasks<full_tasks, f"{sliced_tasks} >= {full_tasks}"606162deftest_coarse_slice_middle_blocks():
63"""Coarse slice selecting blocks in the middle."""64arr=np.arange(100)
65x=da.from_array(arr, chunks=10)
6667defdouble_elements(block):
68returnnp.repeat(block, 2)
6970y=da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
7172# Slice [40:80] needs output blocks 2-3, which need input blocks 2-373result=y[40:80]
7475expected=np.repeat(arr, 2)[40:80]
76assert_eq(result, expected)
7778# Task count check79full_tasks=len(y.optimize().__dask_graph__())
80sliced_tasks=len(result.optimize().__dask_graph__())
81assertsliced_tasks<full_tasks828384deftest_coarse_slice_partial_block():
85"""Coarse slice that spans partial blocks still works. 86 87 Even if slice doesn't align to block boundaries, we only need 88 the blocks that contain the slice range. 89 """90arr=np.arange(100)
91x=da.from_array(arr, chunks=10)
9293defdouble_elements(block):
94returnnp.repeat(block, 2)
9596y=da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
9798# Slice [15:45] spans partial blocks 0 and 1, plus full block 299# Needs output blocks 0, 1, 2 -> input blocks 0, 1, 2100result=y[15:45]
101102expected=np.repeat(arr, 2)[15:45]
103assert_eq(result, expected)
104105106# =============================================================================107# Case 2: Multi-dimensional108# =============================================================================109110111deftest_coarse_slice_2d():
112"""Coarse slice through 2D blockwise with adjust_chunks."""113arr=np.arange(100).reshape(10, 10)
114x=da.from_array(arr, chunks=(5, 5))
115116# Double along axis 0117defdouble_rows(block):
118returnnp.repeat(block, 2, axis=0)
119120y=da.map_blocks(double_rows, x, chunks=(10, 5), dtype=arr.dtype)
121asserty.shape== (20, 10)
122123# Slice [:10, :5] needs output block (0,0), input block (0,0)124result=y[:10, :5]
125126expected=np.repeat(arr, 2, axis=0)[:10, :5]
127assert_eq(result, expected)
128129# Task count check130full_tasks=len(y.optimize().__dask_graph__())
131sliced_tasks=len(result.optimize().__dask_graph__())
132assertsliced_tasks<full_tasks133134135deftest_coarse_slice_2d_one_axis_adjusted():
136"""Slice on non-adjusted axis can still push through fully."""137arr=np.arange(100).reshape(10, 10)
138x=da.from_array(arr, chunks=(5, 5))
139140# Only axis 0 has adjusted chunks141defdouble_rows(block):
142returnnp.repeat(block, 2, axis=0)
143144y=da.map_blocks(double_rows, x, chunks=(10, 5), dtype=arr.dtype)
145146# Slice [:, :3] - axis 1 is NOT adjusted, so can push through147# But axis 0 would need coarse handling if we also sliced it148result=y[:, :3]
149150expected=np.repeat(arr, 2, axis=0)[:, :3]
151assert_eq(result, expected)
152153154# =============================================================================155# Case 3: Multi-input Blockwise156# =============================================================================157158159deftest_coarse_slice_multi_input():
160"""Coarse slice through blockwise with multiple inputs."""161arr1=np.arange(100)
162arr2=np.arange(100, 200)
163164x=da.from_array(arr1, chunks=10)
165y=da.from_array(arr2, chunks=10)
166167# Blockwise that combines two inputs and changes chunk size168defcombine_double(a, b):
169returnnp.repeat(a+b, 2)
170171# Use blockwise directly172z=da.blockwise(
173combine_double, 'i',
174x, 'i',
175y, 'i',
176dtype=arr1.dtype,
177adjust_chunks={'i': lambdac: c*2}
178 )
179assertz.shape== (200,)
180181# Slice [:20] needs output block 0, which needs input blocks (0, 0)182result=z[:20]
183184expected=np.repeat(arr1+arr2, 2)[:20]
185assert_eq(result, expected)
186187188# =============================================================================189# Case 4: Dimension reordering190# =============================================================================191192193deftest_coarse_slice_with_transposed_indices():
194"""Coarse slice when blockwise uses different index ordering."""195arr=np.arange(100).reshape(10, 10)
196x=da.from_array(arr, chunks=(5, 5))
197198# Transpose with adjust_chunks199deftranspose_double(block):
200# Transpose and double first axis201t=block.T202returnnp.repeat(t, 2, axis=0)
203204y=da.map_blocks(
205transpose_double, x,
206chunks=(10, 5), # chunks change207dtype=arr.dtype208 )
209210# This is tricky - need to map output blocks to correct input blocks211result=y[:10, :]
212213expected=np.repeat(arr.T, 2, axis=0)[:10, :]
214assert_eq(result, expected)
215216217# =============================================================================218# Case 5: new_axes interaction219# =============================================================================220221222deftest_coarse_slice_with_new_axis():
223"""Coarse slice when blockwise has new_axes, slicing non-new axis."""224arr=np.arange(100)
225x=da.from_array(arr, chunks=10)
226227# Add a new axis AND adjust chunks on existing axis228defexpand_double(block):
229doubled=np.repeat(block, 2)
230returndoubled[:, np.newaxis]
231232y=da.map_blocks(
233expand_double, x,
234chunks=(20, 1),
235new_axis=1,
236dtype=arr.dtype237 )
238asserty.shape== (200, 1)
239240# Slice on axis 0 (not the new axis)241result=y[:20, :]
242243expected=np.repeat(arr, 2)[:20, np.newaxis]
244assert_eq(result, expected)
245246247# =============================================================================248# Case 6: Verify optimization is applied249# =============================================================================250251252deftest_coarse_optimization_reduces_tasks():
253"""Verify that coarse slice optimization reduces task count."""254arr=np.arange(1000)
255x=da.from_array(arr, chunks=10) # 100 blocks256257defdouble_elements(block):
258returnnp.repeat(block, 2)
259260y=da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
261262full_tasks=len(y.optimize().__dask_graph__())
263264# Slice selecting ~10% of output265sliced=y[:200] # 10 output blocks out of 100266sliced_tasks=len(sliced.optimize().__dask_graph__())
267268# Should have significantly fewer tasks (roughly 10% + overhead)269assertsliced_tasks<full_tasks/2, f"{sliced_tasks} >= {full_tasks/2}"270271272# =============================================================================273# Edge cases274# =============================================================================275276277deftest_coarse_slice_negative_indices():
278"""Coarse slice with negative indices."""279arr=np.arange(100)
280x=da.from_array(arr, chunks=10)
281282defdouble_elements(block):
283returnnp.repeat(block, 2)
284285y=da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
286287# Last 20 elements = output block 9 = input block 9288result=y[-20:]
289290expected=np.repeat(arr, 2)[-20:]
291assert_eq(result, expected)
292293294deftest_coarse_slice_with_step():
295"""Coarse slice with step > 1."""296arr=np.arange(100)
297x=da.from_array(arr, chunks=10)
298299defdouble_elements(block):
300returnnp.repeat(block, 2)
301302y=da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
303304# Every other element from first 40305result=y[:40:2]
306307expected=np.repeat(arr, 2)[:40:2]
308assert_eq(result, expected)
309310311deftest_coarse_slice_single_element():
312"""Coarse slice selecting single element (integer index)."""313arr=np.arange(100)
314x=da.from_array(arr, chunks=10)
315316defdouble_elements(block):
317returnnp.repeat(block, 2)
318319y=da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
320321# Single element from block 5322result=y[105]
323324expected=np.repeat(arr, 2)[105]
325assert_eq(result, expected)
326327328# =============================================================================329# Correctness tests with various chunk configurations330# =============================================================================331332333 @pytest.mark.parametrize("input_chunks,output_chunks,slice_", [
334 (10, 20, slice(0, 20)), # First block335 (10, 20, slice(40, 80)), # Middle blocks336 (10, 20, slice(180, 200)), # Last block337 (10, 5, slice(0, 5)), # Shrinking chunks338 (10, 15, slice(0, 15)), # Non-integer multiple339 (10, 20, slice(10, 30)), # Spans block boundary340 ])
341deftest_coarse_slice_correctness(input_chunks, output_chunks, slice_):
342"""Parametrized correctness tests for various configurations."""343arr=np.arange(100)
344x=da.from_array(arr, chunks=input_chunks)
345346scale=output_chunks/input_chunks347ifscale>=1:
348deftransform(block):
349returnnp.repeat(block, int(scale))
350else:
351deftransform(block):
352returnblock[:int(len(block) *scale)]
353354y=da.map_blocks(transform, x, chunks=(output_chunks,), dtype=arr.dtype)
355356result=y[slice_]
357358# Compute expected result359ifscale>=1:
360expected_full=np.repeat(arr, int(scale))
361else:
362expected_full=np.concatenate([arr[i:i+input_chunks][:int(input_chunks*scale)]
363foriinrange(0, len(arr), input_chunks)])
364expected=expected_full[slice_]
365366assert_eq(result, expected)
Not that I like those tests (I don't, and engaged with it a bit to get what I wanted) but mostly I'm sharing to say "Claude gets it pretty quickly, and can reason well for the sorts of things that we typically want".
Follow a certain pattern that checks not just for value equality in tests, but expression simplification
Then it did some work, but other tests failed. It did an overly simple job that the other tests pointed out. I encouraged it to solve the problem more generally (arbitrary tuples as chunks, not just uniform numbers)
My normal /cleanup command
Commit
Normally I'd fool around with it too, but I'm about to head out and wanted to push something up soon.
@dcherian it seems like the interaction above worked pretty well. You had a desire and did some work to boil that desire down to a simple situation and description. I fed that description into Claude and iterated with it briefly. We got something out that seems to be a strong improvement on the system.
I'd be happy to do more of this if you have more desires. I'd also be happy to work with you to empower you to do this without me in the loop (although to be clear I'm very happy being in the loop at the moment).
Yes I understand, and can work with Claude. My bandwidth is just quite low at the moment (I wouldn't have got to that optimization till this weekend or next weekend at best). So I'll keep writing up such issues, and either you or I can tackle them as time permits.
FWIW my next idea to explore is the groupby anomaly problem. groupby() - groupby().mean() I did some painful work here with input from Patrick and am curious if some rewriting would avoid the need for all that. The core of this is just array - dask.array.take(small_array, large_indices) and we'd like to apply chunk sizes of array to the take's shuffle layer (my understanding may be totally wrong; or you amy have done this already). The Xarray code is here; the isel is the take; g is operator.sub (for example); and the .chunk call was my attempt to do this kind of optimization with old dask.array.
For the clone problem I think a good approach is something like adding a salt= keyword to FromArray whose only job it is is to mix up the token, and then, on any expression we want to clone, we search through the expression and substitute all FromArrays (or other IO nodes) with equivalent nodes that have been salted (hopefully salting is an understood concept in this context). In general I think that the mechanics of cloning expressions is easy.
What's not easy, I think, is detecting when we should clone them. You've brought up an obvious case, but my guess is that finding a reliably good general solution will require some thought. I'd welcome your thinking on that problem. Probably we need to think a little adversarially as well. For any possible solution when might this go badly? What stituations should use it but wouldn't given our approach? etc..
binary_op needs to be smarter about "aligning" chunks
rechunk isn't pushed in to shuffle
Some repr feedback: it's not obvious that the FromArray layers are all the same! perhaps the first 6 characters of the token should be exposed in a new column?
In dask/dask@9af0e37 we implement an allternative to common_blockdim which tries to maintain the chunk size of the larger of the inputs. I think it solves the main problem there. Also looking at the shuffle stuff (but I'm not sure that thinking about pushing through rechunking is best here. That seems like making a more effective bandaid. I'm curious about what we should have done initially so that that wouldn't have been warranted)
OK, a potential change to shuffle to reduce number of chunks in dask/dask@68122e0
Scenario
Main
Our changes
np.repeat (contiguous)
120 chunks, 1 dep each
4 chunks, 1 dep each
np.tile (scattered)
120 chunks, 1 dep each
120 chunks, 1 dep each
Random permutation
5 chunks, 5 deps (shuffle-split)
5 chunks, 5 deps (shuffle-split)
Not sure that's highly relevant though given the coarse_blockdim change from earlier. I'd welcome your thoughts on this. I know that this is something you were thinking about with Patrick for a while.
>>>fromxarray.groupersimportTimeResampler>>>da.chunk(time=TimeResampler("ME")).chunks[0][:5] # 'ME' is a good frequency for the "time.month" mean.
(124, 112, 124, 120, 124)
Note I could teach Xarray to do this explicitly ( dask.array.shuffle(..., idxr, chunks=...), and I'm not sure the pattern of np.repeat should be detected by dask (but maybe it's common enough in other fields). The current result is weird though. Each chunk is split in 2: 124= 108 + 16; 112 = 92+20; etc. Why not just (108,...) like the bigger array in the binary_op: arr?
PS: pydata/xarray#9896 tries to implement an explicit call to shuffle for such grouped binary ops.
Also looking at the shuffle stuff (but I'm not sure that thinking about pushing through rechunking is best here. That seems like making a more effective bandaid. I'm curious about what we should have done initially so that that wouldn't have been warranted)
My thinking here is that users are likely to use vindex or take to make a small array "big" but those APIs don't let them control the chunking. So they are likely to apply if after the fact (I've done this ;) ). the real answer is to use dask.array.shuffle directly but there's no numpy equivalent, so it is much harder to discover. Hence it would be nice if take + rechunk => new shuffle
a potential change to shuffle to reduce number of chunks
This seems fine but also prone to failure; I left a couple of comments on the dask PR.
Activity
dcherian commentedon Dec 31, 2025
Here's a case where I would expect slices to be pushed down through Blockwise
PS: I'm happy to take a stab at resolving this tomorrow.
mrocklin commentedon Dec 31, 2025
Very happy to take a look (or have Claude take a look). Your example isn't working for me though:
arrsupposed to beds.air?chunks=keyword and I'm not sure whyAlso, hopefully if you install
richyou'll be able to get nicer reprs that will help explain what's going on.keewis commentedon Dec 31, 2025
Without having more context:
indeed.
you need to replace
load_datasetwithopen_dataset(otherwise the dask arrays will be computed immediately)dcherian commentedon Dec 31, 2025
Apologies, I was summarizing a slightly messy notebook. The example works now
mrocklin commentedon Dec 31, 2025
Sorry I'm still struggling. How did you produce the air.zarr file. You all may be assuming that I have more familiarity with xarray than I actually do.
mrocklin commentedon Dec 31, 2025
Never mind. Good now. Thanks.
dcherian commentedon Dec 31, 2025
🤦🏾♂️ fixed again; the zarr vs netcdf doesn't matter here; and i should be able to reproduce to pure dask.array blockwise + slicing later tonight.
mrocklin commentedon Dec 31, 2025
OK, so we have this:
Now you're saying that you want the getitem to traverse down through the groupby nanmean. It looks like the Getitem/Slice is slicing in the last dimension, but the groupby nanmean is also affecting that dimension, which is why dask array is being nervous about moving it through.
In dask array parlance the groupby nanmean is a blockwise (sorry, this is going to get a little ugly for a moment, but I figure it's good education).
Now, we're happy in general to push a slice through a blockwise, but we're nervous if that blockwise adjusts the chunking of the underlying array, which this certainly does.
[n:m]has to be translated somehow into[f(n): f(m)]and we don't know how to do that here in general. Probably Xarray does though, through the use of the time index. This might be a case where we need some sort of Xarray expression rather than a Dask array expression. I think that Dask array (or any underlying ndarray abstraction) doesn't have the necessary metadata to do this transformation safely. I suspect that this optimization has to be done within the Xarray abstraction.Open to thoughts. My main question right now is how much of the value of expression optimization requires Xarray knowledge, and how much of it can be done purely within the ndarray abstaction.
mrocklin commentedon Dec 31, 2025
Or, if we didn't want to Expr-ify Xarray, we could make some other traversal system that went through and applied optimizations. This would probably be less invasive and not that hard, but it would have to live here I think.
dcherian commentedon Dec 31, 2025
My thinking is that the blockwise takes in a chunk of size
m, outputs a chunk of sizen, so a slice that aligns with chunk boundaries e.g.slice(n, 3n)is fine to push down asslice(m, 3m)(or appropriately modified). Basically, block-slicing of blockwise is fine in theory. But now I can see that this is a little hard with general blockwise since there is an arbitrary function to transform chunks (them->nmapping).One thing I've been toying around with is whether flox needs to insert its own expr layer, instead of relying on general blockwise. This seems like a reason to do so.
mrocklin commentedon Dec 31, 2025
Having your own Expr layer thats more specific than Blockwise would make this much easier to resolve.
Yeah, historically we used to allow
adjust_chunksto be a function. I could imagine something like what you're describing being more possible (but still probably not doable in general) in that world. In our case we just store a dict of new chunks now (it's hard to send a callable to the scheduler).FWIW I suspect that Claude, given the context in the dask repo, could probably implement that new expression for you if given enough description of what you're trying to accomplish.
dcherian commentedon Dec 31, 2025
In that case if the applied slice indices are present in
cumsum(new_chunks), you can back out which "source" chunks are needed on all source arrays.Happy to do this in flox, but I bet someone is going to expect this. It's also a pretty high-impact optimization I would think (blockwise being so pervasive)
mrocklin commentedon Dec 31, 2025
Maybe I need to better understand what flox is doing. This is a cumreduction? If so, why did the shape change? I'm quite happy to add more optimizations into dask array expressions (that's what it's there for) I just don't understand this situation well enough to understand what the pattern is. My understanding currently is that Flox is doing some blockwise operation with highly custom chunk changing. In that situation there's not much we can do. If Flox is actually doing some other more specific dask array operation (like calling cumreduction) and if there's some optimization we can do there I'm more than happy to work on it. I just need to learn more.
dcherian commentedon Dec 31, 2025
I can work on a pure dask.array example tonight. Here is a visual from the docs [each square is a single array element; each color is a different group; gaps between groups of elements indicate a chunk boundary]:
If I apply a slicer aligned with blocks on the output (say
slice(0, 4)=> slice out the first two blocks); then to compute that i only needslice(0, 16)on the input (first two blocks of the input after rechunking). The blockwise applies a groupby-reduction per block which is why the chunk sizes change. Because of the intelligently chosen chunking, it happens to be a reduction without cross-block dependencies, so block-aligned slicing can be pushed down.Does the expr branch still
cullor are we relying on pushdown to remove the need tocull?mrocklin commentedon Dec 31, 2025
We're relying on slice pushdown to remove the need to cull. Beyond this, maybe the scheduler handles it. It's not something that task graphs are thinking about though.
We only know that we only need the first two blocks in this case because we get to look at the colors though, right? This
[:4]->[:16]result doesn't hold generally for all groupby-reduction operations, right? I suspect that in this case the colors are coming from the index, is that right? So we need to have the index on-hand in order to make this optimization safely. If so, my guess is that the Flox expression will have access to that Index as it performs the optimization. That's the piece of information that the Dask array expressions are missing.2 remaining items
dcherian commentedon Jan 1, 2026
Here you go
dcherian commentedon Jan 1, 2026
Here's an actual groupby
mrocklin commentedon Jan 1, 2026
I see, you're saying that we can map backwards through adjust chunks. That makes sense. I'll ask our mutual friend to take a look :)
mrocklin commentedon Jan 1, 2026
Here's the first 30s of the conversation. Mostly sharing here to convey that this is something that other people can do too:
⏺ This is an interesting optimization idea. Let me activate the relevant skills first.
⏺ /expr-optimization
⏺ This is a good optimization idea. The key insight is that even when adjust_chunks prevents full slice pushdown, we can still do "block-level" selection - if we only need output blocks 2-4, we only need input blocks 2-4 (for aligned dimensions).
Let me first explore the current slice pushdown implementation to understand what we're building on:
⏺ Search(pattern: "dask/array/_array_expr/slicing/*.py")
⎿ Found 7 files (ctrl+o to expand)
⏺ Search(pattern: "adjust_chunks", path: "dask/array/_array_expr/slicing")
⎿ Found 0 files
⏺ Search(pattern: "adjust_chunks", path: "dask/array/_array_expr")
⎿ Found 10 files (ctrl+o to expand)
⏺ Let me look at the current slice-through-blockwise implementation and the Blockwise class:
⏺ Read(dask/array/_array_expr/tests/test_slice_through_blockwise.py)
⎿ Read 655 lines
⏺ Read(dask/array/_array_expr/_blockwise.py)
⎿ Read 1304 lines
⏺ Now I understand the current state. Looking at _accept_slice in _blockwise.py:404-517, it currently rejects slices when adjust_chunks is set on a sliced dimension (lines 434-439).
The optimization you're proposing is: even when we can't push the exact slice through (because chunk sizes change), we can still do a "coarse" block-level selection. If output slice only needs blocks 2-4, we only need input blocks 2-4.
Let me create a test file to explore the cases:
Test file
mrocklin commentedon Jan 1, 2026
Not that I like those tests (I don't, and engaged with it a bit to get what I wanted) but mostly I'm sharing to say "Claude gets it pretty quickly, and can reason well for the sorts of things that we typically want".
dcherian commentedon Jan 1, 2026
Lol that's even better; it's culling!
mrocklin commentedon Jan 1, 2026
OK, pushed an attempt (although I haven't thought too much about it) here.
dask/dask@053e694
Just for education, ways that I prodded it:
/cleanupcommandNormally I'd fool around with it too, but I'm about to head out and wanted to push something up soon.
mrocklin commentedon Jan 2, 2026
@dcherian it seems like the interaction above worked pretty well. You had a desire and did some work to boil that desire down to a simple situation and description. I fed that description into Claude and iterated with it briefly. We got something out that seems to be a strong improvement on the system.
I'd be happy to do more of this if you have more desires. I'd also be happy to work with you to empower you to do this without me in the loop (although to be clear I'm very happy being in the loop at the moment).
dcherian commentedon Jan 2, 2026
Yes I understand, and can work with Claude. My bandwidth is just quite low at the moment (I wouldn't have got to that optimization till this weekend or next weekend at best). So I'll keep writing up such issues, and either you or I can tackle them as time permits.
FWIW my next idea to explore is the groupby anomaly problem.
groupby() - groupby().mean()I did some painful work here with input from Patrick and am curious if some rewriting would avoid the need for all that. The core of this is justarray - dask.array.take(small_array, large_indices)and we'd like to apply chunk sizes of array to the take's shuffle layer (my understanding may be totally wrong; or you amy have done this already). The Xarray code is here; theiselis thetake;gisoperator.sub(for example); and the.chunkcall was my attempt to do this kind of optimization with old dask.array.mrocklin commentedon Jan 2, 2026
For the
cloneproblem I think a good approach is something like adding asalt=keyword toFromArraywhose only job it is is to mix up the token, and then, on any expression we want to clone, we search through the expression and substitute all FromArrays (or other IO nodes) with equivalent nodes that have been salted (hopefully salting is an understood concept in this context). In general I think that the mechanics of cloning expressions is easy.What's not easy, I think, is detecting when we should clone them. You've brought up an obvious case, but my guess is that finding a reliably good general solution will require some thought. I'd welcome your thinking on that problem. Probably we need to think a little adversarially as well. For any possible solution when might this go badly? What stituations should use it but wouldn't given our approach? etc..
dcherian commentedon Jan 3, 2026
Here is a notebook: https://notebooksharing.space/view/8752de27c334f4b16e7f030900b1237c95ac4ef9a2ef8118bf3ca2336bbcbdf2
I made 2 observations
Some repr feedback: it's not obvious that the FromArray layers are all the same! perhaps the first 6 characters of the token should be exposed in a new column?
mrocklin commentedon Jan 3, 2026
Nice examples. I'll take a look.
mrocklin commentedon Jan 3, 2026
In dask/dask@9af0e37 we implement an allternative to common_blockdim which tries to maintain the chunk size of the larger of the inputs. I think it solves the main problem there. Also looking at the shuffle stuff (but I'm not sure that thinking about pushing through rechunking is best here. That seems like making a more effective bandaid. I'm curious about what we should have done initially so that that wouldn't have been warranted)
mrocklin commentedon Jan 3, 2026
OK, a potential change to shuffle to reduce number of chunks in dask/dask@68122e0
Not sure that's highly relevant though given the coarse_blockdim change from earlier. I'd welcome your thoughts on this. I know that this is something you were thinking about with Patrick for a while.
dcherian commentedon Jan 4, 2026
Just tried out your latest commit:
I get this chunking for the result of the binary op
The "optimal" one would be
Note I could teach Xarray to do this explicitly (
dask.array.shuffle(..., idxr, chunks=...), and I'm not sure the pattern ofnp.repeatshould be detected by dask (but maybe it's common enough in other fields). The current result is weird though. Each chunk is split in 2: 124= 108 + 16; 112 = 92+20; etc. Why not just (108,...) like the bigger array in the binary_op:arr?PS: pydata/xarray#9896 tries to implement an explicit call to shuffle for such grouped binary ops.
My thinking here is that users are likely to use
vindexortaketo make a small array "big" but those APIs don't let them control the chunking. So they are likely to apply if after the fact (I've done this ;) ). the real answer is to usedask.array.shuffledirectly but there's no numpy equivalent, so it is much harder to discover. Hence it would be nice iftake + rechunk => new shuffleThis seems fine but also prone to failure; I left a couple of comments on the dask PR.