Skip to content

expr #482

Open
Open

Description

@dcherian

This is a running thread to discuss dask-expr optimizations. I intend to add small examples in separate messages

cc @mrocklin

Activity

  1. dcherian commented on Dec 31, 2025

    @dcherian
    CollaboratorAuthor

    Here's a case where I would expect slices to be pushed down through Blockwise

    import dask
    dask.config.set({'array.query-planning': True})
    
    import xarray as xr
    
    # This `108` chunksize is important; it is large enough to trigger automatic rechunking by flox
    # FIXME: be more aggressive about rechunking with expr
    ds = 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 chunks
    subset = clim.sel(time=slice("2013-01", "2013-03"))
    
    # I would expect the slice to be pushed down to both FromArray layers, but it is not
    subset.data.expr.simplify()

    PS: I'm happy to take a stab at resolving this tomorrow.

  2. mrocklin commented on Dec 31, 2025

    @mrocklin

    Very happy to take a look (or have Claude take a look). Your example isn't working for me though:

    • is arr supposed to be ds.air?
    • I'm not getting dask arrays even with the chunks= keyword and I'm not sure why

    Also, hopefully if you install rich you'll be able to get nicer reprs that will help explain what's going on.

  3. keewis commented on Dec 31, 2025

    @keewis
    Member

    Without having more context:

    is arr supposed to be ds.air

    indeed.

    I'm not getting dask arrays even with the chunks= keyword and I'm not sure why

    you need to replace load_dataset with open_dataset (otherwise the dask arrays will be computed immediately)

  4. dcherian commented on Dec 31, 2025

    @dcherian
    CollaboratorAuthor

    Apologies, I was summarizing a slightly messy notebook. The example works now

  5. mrocklin commented on Dec 31, 2025

    @mrocklin

    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.

  6. mrocklin commented on Dec 31, 2025

    @mrocklin

    Never mind. Good now. Thanks.

  7. dcherian commented on Dec 31, 2025

    @dcherian
    CollaboratorAuthor

    🤦🏾‍♂️ 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.

  8. mrocklin commented on Dec 31, 2025

    @mrocklin

    OK, so we have this:

    >>> subset.expr
    
     Operation                Shape        Bytes 
     Getitem                  3×25×53     31 kiB 
     └ Transpose              24×25×53   248 kiB 
       └ Groupby Nanmean      25×53×24   248 kiB 
         └ Groupby Nanmean    25×53×2920  30 MiB 
           ├ Rechunk          25×53×2920  30 MiB 
           │ └ Transpose      25×53×2920  30 MiB 
           │   └ Open Dataset 2920×25×53  30 MiB 
           └ Array            2920        23 kiB 
    
    >>> subset.expr.simplify()
    
     Operation              Shape        Bytes 
     Transpose              3×25×53     31 kiB 
     └ Getitem              25×53×3     31 kiB 
       └ Groupby Nanmean    25×53×24   248 kiB 
         └ Groupby Nanmean  25×53×2920  30 MiB 
           ├ Transpose      25×53×2920  30 MiB 
           │ └ Open Dataset 2920×25×53  30 MiB 
           └ Array          2920        23 kiB 

    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).

    >>> print(subset.data.expr.simplify().tree_repr())
    
    Transpose: axes=(2, 0, 1)
      SliceSlicesIntegers: index=(slice(None, None, None), slice(None, None, None), slice(None, 3, None)) allow_getitem_optimization=True
        Blockwise: func='_extract_result' out_ind=(0, 1, 2) name='groupby_nanmean-11e1f256e8e6e275b89d6f0da934d110' adjust_chunks={0: (25,), 1: (53,), 2: (2, 1, 2, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1)} new_axes={} concatenate=False _meta_provided='<array>' kwargs={'key': 'nanmean'}(0, 1, 2)
          Blockwise: func='_reduce_blockwise' out_ind=(0, 1, 2) name='groupby_nanmean-chunk-11e1f256e8e6e275b89d6f0da934d110' dtype='float64' new_axes={} align_arrays=False concatenate=False _meta_provided='<array>' kwargs={}(0, 1, 2)(2,)
            Transpose: axes=(1, 2, 0)
              FromArray: array='<ImplicitToExplicitIndexingAdapter>' _chunks=((236, 124, 244, 244, 124, 244, 244, 124, 236, 120, 244, 248, 120, 244, 124), (25,), (53,)) meta='<array>' _name_override='open_dataset-air-a5b61afff50733bab97ed2df986e37c3'
            FromArray: array='<array>' _chunks=((236, 124, 244, 244, 124, 244, 244, 124, 236, 120, 244, 248, 120, 244, 124),) _name_override='array'
    

    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.

  9. mrocklin commented on Dec 31, 2025

    @mrocklin

    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.

  10. dcherian commented on Dec 31, 2025

    @dcherian
    CollaboratorAuthor

    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.

  11. mrocklin commented on Dec 31, 2025

    @mrocklin

    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.

  12. dcherian commented on Dec 31, 2025

    @dcherian
    CollaboratorAuthor

    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)

  13. mrocklin commented on Dec 31, 2025

    @mrocklin

    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.

  14. dcherian commented on Dec 31, 2025

    @dcherian
    CollaboratorAuthor

    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]:

    Image

    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?

  15. mrocklin commented on Dec 31, 2025

    @mrocklin

    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.

  16. 2 remaining items

  17. dcherian commented on Jan 1, 2026

    @dcherian
    CollaboratorAuthor

    Here you go

    import dask.array
    import numpy as np
    
    array = dask.array.ones((10,), chunks=((2, 3, 4, 1),))
    
    def func(a):
        return a.sum(keepdims=True)
    
    res = dask.array.blockwise(
        func,
        "i",
        array,
        "i",
        # this seems unnecessary
        adjust_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 result
    dask.array.assert_eq(res[:2].compute(), np.array([2., 3]))
  18. dcherian commented on Jan 1, 2026

    @dcherian
    CollaboratorAuthor

    Here's an actual groupby

    import dask.array
    import numpy as np
    
    array = dask.array.ones((10,), chunks=((2, 3, 4, 1),))
    
    by =  np.array([0, 1, 2, 2, 3, 4, 4, 4, 4, 5])
    
    def func(a, b):
        out = np.zeros(b.max() + 1)
        print('\n', a, b, out)
        np.add.at(out, b, a)
        return out[b.min():b.max() + 1]
    
    res = dask.array.blockwise(
        func,
        "i",
        array,
        "i",
        by,
        "i",
        adjust_chunks={0: (2, 2, 1, 1)},  # this seems unnecessary
        meta=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 result
    dask.array.assert_eq(res[:2].compute(), np.array([1., 1]))
  19. mrocklin commented on Jan 1, 2026

    @mrocklin

    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 :)

  20. mrocklin commented on Jan 1, 2026

    @mrocklin

    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:

    ⏺ 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
    ⏺ Write(dask/array/_array_expr/tests/test_coarse_slice_through_blockwise.py)
    
    ──────────────────────────────────────────────────────────────────────────────────────────────────────────
     Create file dask/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 """
       10
       11 from __future__ import annotations
       12
       13 import numpy as np
       14 import pytest
       15
       16 import dask.array as da
       17 from dask.array.utils import assert_eq
       18
       19 pytestmark = pytest.mark.skipif(
       20     not da._array_expr_enabled(), reason="array_expr not enabled"
       21 )
       22
       23
       24 # =============================================================================
       25 # Case 1: Simple - single input with adjust_chunks
       26 # =============================================================================
       27
       28
       29 def test_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     """
       36     arr = np.arange(100)
       37     x = da.from_array(arr, chunks=10)
       38
       39     # Each block doubles in size
       40     def double_elements(block):
       41         return np.repeat(block, 2)
       42
       43     y = da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
       44     assert y.shape == (200,)
       45
       46     # Slice first 20 elements - this is exactly output block 0
       47     result = y[:20]
       48
       49     # Should be correct
       50     expected = np.repeat(arr, 2)[:20]
       51     assert_eq(result, expected)
       52
       53     # Optimization check: should need fewer tasks than full computation
       54     full_tasks = len(y.optimize().__dask_graph__())
       55     sliced_tasks = len(result.optimize().__dask_graph__())
       56
       57     # With coarse slice optimization, should need ~1/10 the tasks
       58     # (1 input block + 1 map_blocks + 1 slice vs 10+10)
       59     assert sliced_tasks < full_tasks, f"{sliced_tasks} >= {full_tasks}"
       60
       61
       62 def test_coarse_slice_middle_blocks():
       63     """Coarse slice selecting blocks in the middle."""
       64     arr = np.arange(100)
       65     x = da.from_array(arr, chunks=10)
       66
       67     def double_elements(block):
       68         return np.repeat(block, 2)
       69
       70     y = da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
       71
       72     # Slice [40:80] needs output blocks 2-3, which need input blocks 2-3
       73     result = y[40:80]
       74
       75     expected = np.repeat(arr, 2)[40:80]
       76     assert_eq(result, expected)
       77
       78     # Task count check
       79     full_tasks = len(y.optimize().__dask_graph__())
       80     sliced_tasks = len(result.optimize().__dask_graph__())
       81     assert sliced_tasks < full_tasks
       82
       83
       84 def test_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     """
       90     arr = np.arange(100)
       91     x = da.from_array(arr, chunks=10)
       92
       93     def double_elements(block):
       94         return np.repeat(block, 2)
       95
       96     y = da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
       97
       98     # Slice [15:45] spans partial blocks 0 and 1, plus full block 2
       99     # Needs output blocks 0, 1, 2 -> input blocks 0, 1, 2
      100     result = y[15:45]
      101
      102     expected = np.repeat(arr, 2)[15:45]
      103     assert_eq(result, expected)
      104
      105
      106 # =============================================================================
      107 # Case 2: Multi-dimensional
      108 # =============================================================================
      109
      110
      111 def test_coarse_slice_2d():
      112     """Coarse slice through 2D blockwise with adjust_chunks."""
      113     arr = np.arange(100).reshape(10, 10)
      114     x = da.from_array(arr, chunks=(5, 5))
      115
      116     # Double along axis 0
      117     def double_rows(block):
      118         return np.repeat(block, 2, axis=0)
      119
      120     y = da.map_blocks(double_rows, x, chunks=(10, 5), dtype=arr.dtype)
      121     assert y.shape == (20, 10)
      122
      123     # Slice [:10, :5] needs output block (0,0), input block (0,0)
      124     result = y[:10, :5]
      125
      126     expected = np.repeat(arr, 2, axis=0)[:10, :5]
      127     assert_eq(result, expected)
      128
      129     # Task count check
      130     full_tasks = len(y.optimize().__dask_graph__())
      131     sliced_tasks = len(result.optimize().__dask_graph__())
      132     assert sliced_tasks < full_tasks
      133
      134
      135 def test_coarse_slice_2d_one_axis_adjusted():
      136     """Slice on non-adjusted axis can still push through fully."""
      137     arr = np.arange(100).reshape(10, 10)
      138     x = da.from_array(arr, chunks=(5, 5))
      139
      140     # Only axis 0 has adjusted chunks
      141     def double_rows(block):
      142         return np.repeat(block, 2, axis=0)
      143
      144     y = da.map_blocks(double_rows, x, chunks=(10, 5), dtype=arr.dtype)
      145
      146     # Slice [:, :3] - axis 1 is NOT adjusted, so can push through
      147     # But axis 0 would need coarse handling if we also sliced it
      148     result = y[:, :3]
      149
      150     expected = np.repeat(arr, 2, axis=0)[:, :3]
      151     assert_eq(result, expected)
      152
      153
      154 # =============================================================================
      155 # Case 3: Multi-input Blockwise
      156 # =============================================================================
      157
      158
      159 def test_coarse_slice_multi_input():
      160     """Coarse slice through blockwise with multiple inputs."""
      161     arr1 = np.arange(100)
      162     arr2 = np.arange(100, 200)
      163
      164     x = da.from_array(arr1, chunks=10)
      165     y = da.from_array(arr2, chunks=10)
      166
      167     # Blockwise that combines two inputs and changes chunk size
      168     def combine_double(a, b):
      169         return np.repeat(a + b, 2)
      170
      171     # Use blockwise directly
      172     z = da.blockwise(
      173         combine_double, 'i',
      174         x, 'i',
      175         y, 'i',
      176         dtype=arr1.dtype,
      177         adjust_chunks={'i': lambda c: c * 2}
      178     )
      179     assert z.shape == (200,)
      180
      181     # Slice [:20] needs output block 0, which needs input blocks (0, 0)
      182     result = z[:20]
      183
      184     expected = np.repeat(arr1 + arr2, 2)[:20]
      185     assert_eq(result, expected)
      186
      187
      188 # =============================================================================
      189 # Case 4: Dimension reordering
      190 # =============================================================================
      191
      192
      193 def test_coarse_slice_with_transposed_indices():
      194     """Coarse slice when blockwise uses different index ordering."""
      195     arr = np.arange(100).reshape(10, 10)
      196     x = da.from_array(arr, chunks=(5, 5))
      197
      198     # Transpose with adjust_chunks
      199     def transpose_double(block):
      200         # Transpose and double first axis
      201         t = block.T
      202         return np.repeat(t, 2, axis=0)
      203
      204     y = da.map_blocks(
      205         transpose_double, x,
      206         chunks=(10, 5),  # chunks change
      207         dtype=arr.dtype
      208     )
      209
      210     # This is tricky - need to map output blocks to correct input blocks
      211     result = y[:10, :]
      212
      213     expected = np.repeat(arr.T, 2, axis=0)[:10, :]
      214     assert_eq(result, expected)
      215
      216
      217 # =============================================================================
      218 # Case 5: new_axes interaction
      219 # =============================================================================
      220
      221
      222 def test_coarse_slice_with_new_axis():
      223     """Coarse slice when blockwise has new_axes, slicing non-new axis."""
      224     arr = np.arange(100)
      225     x = da.from_array(arr, chunks=10)
      226
      227     # Add a new axis AND adjust chunks on existing axis
      228     def expand_double(block):
      229         doubled = np.repeat(block, 2)
      230         return doubled[:, np.newaxis]
      231
      232     y = da.map_blocks(
      233         expand_double, x,
      234         chunks=(20, 1),
      235         new_axis=1,
      236         dtype=arr.dtype
      237     )
      238     assert y.shape == (200, 1)
      239
      240     # Slice on axis 0 (not the new axis)
      241     result = y[:20, :]
      242
      243     expected = np.repeat(arr, 2)[:20, np.newaxis]
      244     assert_eq(result, expected)
      245
      246
      247 # =============================================================================
      248 # Case 6: Verify optimization is applied
      249 # =============================================================================
      250
      251
      252 def test_coarse_optimization_reduces_tasks():
      253     """Verify that coarse slice optimization reduces task count."""
      254     arr = np.arange(1000)
      255     x = da.from_array(arr, chunks=10)  # 100 blocks
      256
      257     def double_elements(block):
      258         return np.repeat(block, 2)
      259
      260     y = da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
      261
      262     full_tasks = len(y.optimize().__dask_graph__())
      263
      264     # Slice selecting ~10% of output
      265     sliced = y[:200]  # 10 output blocks out of 100
      266     sliced_tasks = len(sliced.optimize().__dask_graph__())
      267
      268     # Should have significantly fewer tasks (roughly 10% + overhead)
      269     assert sliced_tasks < full_tasks / 2, f"{sliced_tasks} >= {full_tasks / 2}"
      270
      271
      272 # =============================================================================
      273 # Edge cases
      274 # =============================================================================
      275
      276
      277 def test_coarse_slice_negative_indices():
      278     """Coarse slice with negative indices."""
      279     arr = np.arange(100)
      280     x = da.from_array(arr, chunks=10)
      281
      282     def double_elements(block):
      283         return np.repeat(block, 2)
      284
      285     y = da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
      286
      287     # Last 20 elements = output block 9 = input block 9
      288     result = y[-20:]
      289
      290     expected = np.repeat(arr, 2)[-20:]
      291     assert_eq(result, expected)
      292
      293
      294 def test_coarse_slice_with_step():
      295     """Coarse slice with step > 1."""
      296     arr = np.arange(100)
      297     x = da.from_array(arr, chunks=10)
      298
      299     def double_elements(block):
      300         return np.repeat(block, 2)
      301
      302     y = da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
      303
      304     # Every other element from first 40
      305     result = y[:40:2]
      306
      307     expected = np.repeat(arr, 2)[:40:2]
      308     assert_eq(result, expected)
      309
      310
      311 def test_coarse_slice_single_element():
      312     """Coarse slice selecting single element (integer index)."""
      313     arr = np.arange(100)
      314     x = da.from_array(arr, chunks=10)
      315
      316     def double_elements(block):
      317         return np.repeat(block, 2)
      318
      319     y = da.map_blocks(double_elements, x, chunks=(20,), dtype=arr.dtype)
      320
      321     # Single element from block 5
      322     result = y[105]
      323
      324     expected = np.repeat(arr, 2)[105]
      325     assert_eq(result, expected)
      326
      327
      328 # =============================================================================
      329 # Correctness tests with various chunk configurations
      330 # =============================================================================
      331
      332
      333 @pytest.mark.parametrize("input_chunks,output_chunks,slice_", [
      334     (10, 20, slice(0, 20)),      # First block
      335     (10, 20, slice(40, 80)),    # Middle blocks
      336     (10, 20, slice(180, 200)),  # Last block
      337     (10, 5, slice(0, 5)),       # Shrinking chunks
      338     (10, 15, slice(0, 15)),     # Non-integer multiple
      339     (10, 20, slice(10, 30)),    # Spans block boundary
      340 ])
      341 def test_coarse_slice_correctness(input_chunks, output_chunks, slice_):
      342     """Parametrized correctness tests for various configurations."""
      343     arr = np.arange(100)
      344     x = da.from_array(arr, chunks=input_chunks)
      345
      346     scale = output_chunks / input_chunks
      347     if scale >= 1:
      348         def transform(block):
      349             return np.repeat(block, int(scale))
      350     else:
      351         def transform(block):
      352             return block[:int(len(block) * scale)]
      353
      354     y = da.map_blocks(transform, x, chunks=(output_chunks,), dtype=arr.dtype)
      355
      356     result = y[slice_]
      357
      358     # Compute expected result
      359     if scale >= 1:
      360         expected_full = np.repeat(arr, int(scale))
      361     else:
      362         expected_full = np.concatenate([arr[i:i+input_chunks][:int(input_chunks*scale)]
      363                                         for i in range(0, len(arr), input_chunks)])
      364     expected = expected_full[slice_]
      365
      366     assert_eq(result, expected)
  21. mrocklin commented on Jan 1, 2026

    @mrocklin

    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".

  22. dcherian commented on Jan 1, 2026

    @dcherian
    CollaboratorAuthor

    Lol that's even better; it's culling!

  23. mrocklin commented on Jan 1, 2026

    @mrocklin

    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:

    • Start with fewer, but better thought out tests
    • 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.

  24. mrocklin commented on Jan 2, 2026

    @mrocklin

    @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).

  25. dcherian commented on Jan 2, 2026

    @dcherian
    CollaboratorAuthor

    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.

  26. mrocklin commented on Jan 2, 2026

    @mrocklin

    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..

  27. dcherian commented on Jan 3, 2026

    @dcherian
    CollaboratorAuthor

    Here is a notebook: https://notebooksharing.space/view/8752de27c334f4b16e7f030900b1237c95ac4ef9a2ef8118bf3ca2336bbcbdf2

    I made 2 observations

    1. binary_op needs to be smarter about "aligning" chunks
    2. 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?

  28. mrocklin commented on Jan 3, 2026

    @mrocklin

    Nice examples. I'll take a look.

  29. mrocklin commented on Jan 3, 2026

    @mrocklin

    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)

  30. mrocklin commented on Jan 3, 2026

    @mrocklin

    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.

  31. dcherian commented on Jan 4, 2026

    @dcherian
    CollaboratorAuthor

    Just tried out your latest commit:

    I get this chunking for the result of the binary op

    >>> sub_arr.chunks[0][:10]
    (108, 16, 92, 20, 88, 36, 72, 48, 60, 64)

    The "optimal" one would be

    >>> from xarray.groupers import TimeResampler
    >>> 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.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions