Debian Codegraph @

docs/source/array-chunks.rst

raw
1 .. _array.chunks:
2
3 Chunks
4 ======
5
6 Dask arrays are composed of many NumPy (or NumPy-like) arrays. How these arrays
7 are arranged can significantly affect performance. For example, for a square
8 array you might arrange your chunks along rows, along columns, or in a more
9 square-like fashion. Different arrangements of NumPy arrays will be faster or
10 slower for different algorithms.
11
12 Thinking about and controlling chunking is important to optimize advanced
13 algorithms.
14
15 Specifying Chunk shapes
16 -----------------------
17
18 We always specify a ``chunks`` argument to tell dask.array how to break up the
19 underlying array into chunks. We can specify ``chunks`` in a variety of ways:
20
21 1. A uniform dimension size like ``1000``, meaning chunks of size ``1000`` in each dimension
22 2. A uniform chunk shape like ``(1000, 2000, 3000)``, meaning chunks of size ``1000`` in the
23 first axis, ``2000`` in the second axis, and ``3000`` in the third
24 3. Fully explicit sizes of all blocks along all dimensions,
25 like ``((1000, 1000, 500), (400, 400), (5, 5, 5, 5, 5))``
26 4. A dictionary specifying chunk size per dimension like ``{0: 1000, 1: 2000,
27 2: 3000}``. This is just another way of writing the forms 2 and 3 above
28
29 Your chunks input will be normalized and stored in the third and most explicit
30 form. Note that ``chunks`` stands for "chunk shape" rather than "number of
31 chunks", so specifying ``chunks=1`` means that you will have many chunks,
32 each with exactly one element.
33
34 For performance, a good choice of ``chunks`` follows the following rules:
35
36 1. A chunk should be small enough to fit comfortably in memory. We'll
37 have many chunks in memory at once
38 2. A chunk must be large enough so that computations on that chunk take
39 significantly longer than the 1ms overhead per task that Dask scheduling
40 incurs. A task should take longer than 100ms
41 3. Chunk sizes between 10MB-1GB are common, depending on the availability of
42 RAM and the duration of computations
43 4. Chunks should align with the computation that you want to do.
44
45 For example, if you plan to frequently slice along a particular dimension,
46 then it's more efficient if your chunks are aligned so that you have to
47 touch fewer chunks. If you want to add two arrays, then its convenient if
48 those arrays have matching chunks patterns
49
50 5. Chunks should align with your storage, if applicable.
51
52 Array data formats are often chunked as well. When loading or saving data,
53 if is useful to have Dask array chunks that are aligned with the chunking
54 of your storage, often an even multiple times larger in each direction
55
56 Learn more in `Choosing good chunk sizes in Dask`_ by Genevieve Buckley.
57
58
59 Unknown Chunks
60 --------------
61
62 Some arrays have unknown chunk sizes. This arises whenever the size of an
63 array depends on lazy computations that we haven't yet performed like the
64 following:
65
66 .. code-block:: python
67
68 >>> rng = np.random.default_rng()
69 >>> x = da.from_array(rng.standard_normal(100), chunks=20)
70 >>> x += 0.1
71 >>> y = x[x > 0] # don't know how many values are greater than 0 ahead of time
72
73 Operations like the above result in arrays with unknown shapes and unknown
74 chunk sizes. Unknown values within shape or chunks are designated using
75 ``np.nan`` rather than an integer. These arrays support many (but not all)
76 operations. In particular, operations like slicing are not possible and will
77 result in an error.
78
79 .. code-block:: python
80
81 >>> y.shape
82 (np.nan,)
83 >>> y[4]
84 ...
85 ValueError: Array chunk sizes unknown
86
87 A possible solution: https://docs.dask.org/en/latest/array-chunks.html#unknown-chunks.
88 Summary: to compute chunks sizes, use
89
90 x.compute_chunk_sizes() # for Dask Array
91 ddf.to_dask_array(lengths=True) # for Dask DataFrame ddf
92
93 Using :func:`~dask.array.Array.compute_chunk_sizes` allows this example run:
94
95 .. code-block:: python
96
97 >>> y.compute_chunk_sizes()
98 dask.array<..., chunksize=(19,), ...>
99 >>> y.shape
100 (44,)
101 >>> y[4].compute()
102 0.78621774046566
103
104 Note that :func:`~dask.array.Array.compute_chunk_sizes` immediately performs computation and
105 modifies the array in-place.
106
107 Unknown chunksizes also occur when using a Dask DataFrame to create a Dask array:
108
109 .. code-block:: python
110
111 >>> ddf = dask.dataframe.from_pandas(...)
112 >>> ddf.to_dask_array()
113 dask.array<..., shape=(nan, 2), ..., chunksize=(nan, 2)>
114
115 Using :func:`~dask.dataframe.DataFrame.to_dask_array` resolves this issue:
116
117 .. code-block:: python
118
119 >>> ddf.to_dask_array(lengths=True)
120 dask.array<..., shape=(100, 2), ..., chunksize=(20, 2)>
121
122 More details on :func:`~dask.dataframe.DataFrame.to_dask_array` are in mentioned in how to create a Dask
123 array from a Dask DataFrame in the :doc:`documentation on Dask array creation
124 <array-creation>`.
125
126 Chunks Examples
127 ---------------
128
129 In this example we show how different inputs for ``chunks=`` cut up the following array::
130
131 1 2 3 4 5 6
132 7 8 9 0 1 2
133 3 4 5 6 7 8
134 9 0 1 2 3 4
135 5 6 7 8 9 0
136 1 2 3 4 5 6
137
138 Here, we show how different ``chunks=`` arguments split the array into different blocks
139
140 **chunks=3**: Symmetric blocks of size 3::
141
142 1 2 3 4 5 6
143 7 8 9 0 1 2
144 3 4 5 6 7 8
145
146 9 0 1 2 3 4
147 5 6 7 8 9 0
148 1 2 3 4 5 6
149
150 **chunks=2**: Symmetric blocks of size 2::
151
152 1 2 3 4 5 6
153 7 8 9 0 1 2
154
155 3 4 5 6 7 8
156 9 0 1 2 3 4
157
158 5 6 7 8 9 0
159 1 2 3 4 5 6
160
161 **chunks=(3, 2)**: Asymmetric but repeated blocks of size ``(3, 2)``::
162
163 1 2 3 4 5 6
164 7 8 9 0 1 2
165 3 4 5 6 7 8
166
167 9 0 1 2 3 4
168 5 6 7 8 9 0
169 1 2 3 4 5 6
170
171 **chunks=(1, 6)**: Asymmetric but repeated blocks of size ``(1, 6)``::
172
173 1 2 3 4 5 6
174
175 7 8 9 0 1 2
176
177 3 4 5 6 7 8
178
179 9 0 1 2 3 4
180
181 5 6 7 8 9 0
182
183 1 2 3 4 5 6
184
185 **chunks=((2, 4), (3, 3))**: Asymmetric and non-repeated blocks::
186
187 1 2 3 4 5 6
188 7 8 9 0 1 2
189
190 3 4 5 6 7 8
191 9 0 1 2 3 4
192 5 6 7 8 9 0
193 1 2 3 4 5 6
194
195 **chunks=((2, 2, 1, 1), (3, 2, 1))**: Asymmetric and non-repeated blocks::
196
197 1 2 3 4 5 6
198 7 8 9 0 1 2
199
200 3 4 5 6 7 8
201 9 0 1 2 3 4
202
203 5 6 7 8 9 0
204
205 1 2 3 4 5 6
206
207 **Discussion**
208
209 The latter examples are rarely provided by users on original data but arise from complex slicing and broadcasting operations. Generally people use the simplest form until they need more complex forms. The choice of chunks should align with the computations you want to do.
210
211 For example, if you plan to take out thin slices along the first dimension, then you might want to make that dimension skinnier than the others. If you plan to do linear algebra, then you might want more symmetric blocks.
212
213
214 Loading Chunked Data
215 --------------------
216
217 Modern NDArray storage formats like HDF5, NetCDF, TIFF, and Zarr, allow arrays
218 to be stored in chunks or tiles so that blocks of data can be pulled out
219 efficiently without having to seek through a linear data stream. It is best to
220 align the chunks of your Dask array with the chunks of your underlying data
221 store.
222
223 However, data stores often chunk more finely than is ideal for Dask array, so
224 it is common to choose a chunking that is a multiple of your storage chunk
225 size, otherwise you might incur high overhead.
226
227 For example, if you are loading a data store that is chunked in blocks of
228 ``(100, 100)``, then you might choose a chunking more like ``(1000, 2000)`` that
229 is larger, but still evenly divisible by ``(100, 100)``. Data storage
230 technologies will be able to tell you how their data is chunked.
231
232
233 Rechunking
234 ----------
235
236 .. currentmodule:: dask.array
237
238 .. autosummary:: rechunk
239
240 Sometimes you need to change the chunking layout of your data. For example,
241 perhaps it comes to you chunked row-wise, but you need to do an operation that
242 is much faster if done across columns. You can change the chunking with the
243 ``rechunk`` method.
244
245 .. code-block:: python
246
247 x = x.rechunk((50, 1000))
248
249 Rechunking across axes can be expensive and incur a lot of communication, but
250 Dask array has fairly efficient algorithms to accomplish this.
251
252 Note: The rechunk method expects the output array to have the same shape as the input array and does not support reshaping. It is important to ensure that the desired output shape matches the input shape before using rechunk.
253
254 You can pass rechunk any valid chunking form:
255
256 .. code-block:: python
257
258 x = x.rechunk(1000)
259 x = x.rechunk((50, 1000))
260 x = x.rechunk({0: 50, 1: 1000})
261
262
263 .. _array-chunks.reshaping:
264
265 Reshaping
266 ---------
267
268 The efficiency of :func:`dask.array.reshape` can depend strongly on the chunking
269 of the input array. In reshaping operations, there's the concept of "fast-moving"
270 or "high" axes. For a 2d array the second axis (``axis=1``) is the fastest-moving,
271 followed by the first. This means that if we draw a line indicating how values
272 are filled, we move across the "columns" first (along ``axis=1``), and then down
273 to the next row. Consider ``np.ones((3, 4)).reshape(12)``:
274
275 .. image:: images/reshape.png
276 :alt: Visual representation of a 2-dimensional (3 rows by 4 colurmns) NumPy array being reshaped to 1 dimension (12 columns by 1 row). Arrows indicate the order in which values from the original array are copied to the new array, moving across the columns in axis 1 first before moving down to the next row in axis 0.
277
278 Now consider the impact of Dask's chunking on this operation. If the slow-moving
279 axis (just ``axis=0`` in this case) has chunks larger than size 1, we run into
280 a problem.
281
282 .. image:: images/reshape_problem.png
283
284 The first block has a shape ``(2, 2)``. Following the rules of ``reshape`` we
285 take the two values from the first row of block 1. But then we cross a chunk
286 boundary (from 1 to 2) while we still have two "unused" values in the first
287 block. There's no way to line up the input blocks with the output shape. We
288 need to somehow rechunk the input to be compatible with the output shape. We
289 have two options
290
291 1. Merge chunks using the logic in :meth:`dask.array.rechunk`. This avoids
292 making two many tasks / blocks, at the cost of some communication and
293 larger intermediates. This is the default behavior.
294 2. Use ``da.reshape(x, shape, merge_chunks=False)`` to avoid merging chunks
295 by *splitting the input*. In particular, we can rechunk all the
296 slow-moving axes to have a chunksize of 1. This avoids
297 communication and moving around large amounts of data, at the cost of
298 a larger task graph (potentially much larger, since the number of chunks
299 on the slow-moving axes will equal the length of those axes.).
300
301 Visually, here's the second option:
302
303 .. image:: images/reshape_rechunked.png
304
305 Which if these is better depends on your problem. If communication is very
306 expensive and your data is relatively small along the slow-moving axes, then
307 ``merge_chunks=False`` may be better. Let's compare the task graphs of these
308 two on a problem reshaping a 3-d array to a 2-d, where the input array doesn't
309 have ``chunksize=1`` on the slow-moving axes.
310
311 .. code-block:: python
312
313 >>> a = da.from_array(np.arange(24).reshape(2, 3, 4), chunks=((2,), (2, 1), (2, 2)))
314 >>> a
315 dask.array<array, shape=(2, 3, 4), dtype=int64, chunksize=(2, 2, 2), chunktype=numpy.ndarray>
316 >>> a.reshape(6, 4).visualize()
317
318 .. image:: images/merge_chunks.png
319
320 .. code-block:: python
321
322 >>> a.reshape(6, 4, merge_chunks=False).visualize()
323
324 .. image:: images/merge_chunks_false.png
325
326 By default, some intermediate chunks chunks are merged, leading to a more complicated task
327 graph. With ``merge_chunks=False`` we split the input chunks (leading to more overall tasks,
328 depending on the size of the array) but avoid later communication.
329
330 Automatic Chunking
331 ------------------
332
333 Chunks also includes three special values:
334
335 1. ``-1``: no chunking along this dimension
336 2. ``None``: no change to the chunking along this dimension (useful for rechunk)
337 3. ``"auto"``: allow the chunking in this dimension to accommodate ideal chunk sizes
338
339 So, for example, one could rechunk a 3D array to have no chunking along the zeroth
340 dimension, but still have sensible chunk sizes as follows:
341
342 .. code-block:: python
343
344 x = x.rechunk({0: -1, 1: 'auto', 2: 'auto'})
345
346 Or one can allow *all* dimensions to be auto-scaled to get to a good chunk
347 size:
348
349 .. code-block:: python
350
351 x = x.rechunk('auto')
352
353 Automatic chunking expands or contracts all dimensions marked with ``"auto"``
354 to try to reach chunk sizes with a number of bytes equal to the config value
355 ``array.chunk-size``, which is set to 128MiB by default, but which you can
356 change in your :doc:`configuration <configuration>`.
357
358 .. code-block:: python
359
360 >>> dask.config.get('array.chunk-size')
361 '128MiB'
362
363 Automatic rechunking tries to respect the median chunk shape of the
364 auto-rescaled dimensions, but will modify this to accommodate the shape of the
365 full array (can't have larger chunks than the array itself) and to find
366 chunk shapes that nicely divide the shape.
367
368 These values can also be used when creating arrays with operations like
369 ``dask.array.ones`` or ``dask.array.from_array``
370
371 .. code-block:: python
372
373 >>> dask.array.ones((10000, 10000), chunks=(-1, 'auto'))
374 dask.array<wrapped, shape=(10000, 10000), dtype=float64, chunksize=(10000, 1250), chunktype=numpy.ndarray>
375
376 .. _`Choosing good chunk sizes in Dask`: https://blog.dask.org/2021/11/02/choosing-dask-chunk-sizes