Debian Codegraph @

docs/source/delayed-best-practices.rst

raw
1 Best Practices
2 ==============
3
4 It is easy to get started with Dask delayed, but using it *well* does require
5 some experience. This page contains suggestions for best practices, and
6 includes solutions to common problems.
7
8
9 Call delayed on the function, not the result
10 --------------------------------------------
11
12 Dask delayed operates on functions like ``dask.delayed(f)(x, y)``, not on their results like ``dask.delayed(f(x, y))``. When you do the latter, Python first calculates ``f(x, y)`` before Dask has a chance to step in.
13
14 +------------------------------------------------+--------------------------------------------------------------+
15 | **Don't** | **Do** |
16 +------------------------------------------------+--------------------------------------------------------------+
17 | .. code-block:: python | .. code-block:: python |
18 | | |
19 | # This executes immediately | # This makes a delayed function, acting lazily |
20 | | |
21 | dask.delayed(f(x, y)) | dask.delayed(f)(x, y) |
22 | | |
23 +------------------------------------------------+--------------------------------------------------------------+
24
25
26 Compute on lots of computation at once
27 --------------------------------------
28
29 To improve parallelism, you want to include lots of computation in each compute call.
30 Ideally, you want to make many ``dask.delayed`` calls to define your computation and
31 then call ``dask.compute`` only at the end. It is ok to call ``dask.compute``
32 in the middle of your computation as well, but everything will stop there as
33 Dask computes those results before moving forward with your code.
34
35 +--------------------------------------------------------+-------------------------------------------+
36 | **Don't** | **Do** |
37 +--------------------------------------------------------+-------------------------------------------+
38 | .. code-block:: python | .. code-block:: python |
39 | | |
40 | # Avoid calling compute repeatedly | # Collect many calls for one compute |
41 | | |
42 | results = [] | results = [] |
43 | for x in L: | for x in L: |
44 | y = dask.delayed(f)(x) | y = dask.delayed(f)(x) |
45 | results.append(y.compute()) | results.append(y) |
46 | | |
47 | results | results = dask.compute(*results) |
48 +--------------------------------------------------------+-------------------------------------------+
49
50 Calling `y.compute()` within the loop would await the result of the computation every time, and
51 so inhibit parallelism.
52
53 Don't mutate inputs
54 -------------------
55
56 Your functions should not change the inputs directly.
57
58 +-----------------------------------------+--------------------------------------+
59 | **Don't** | **Do** |
60 +-----------------------------------------+--------------------------------------+
61 | .. code-block:: python | .. code-block:: python |
62 | | |
63 | # Mutate inputs in functions | # Return new values or copies |
64 | | |
65 | @dask.delayed | @dask.delayed |
66 | def f(x): | def f(x): |
67 | x += 1 | x = x + 1 |
68 | return x | return x |
69 +-----------------------------------------+--------------------------------------+
70
71 If you need to use a mutable operation, then make a copy within your function first:
72
73 .. code-block:: python
74
75 @dask.delayed
76 def f(x):
77 x = copy(x)
78 x += 1
79 return x
80
81
82 Avoid global state
83 ------------------
84
85 Ideally, your operations shouldn't rely on global state. Using global state
86 *might* work if you only use threads, but when you move to multiprocessing or
87 distributed computing then you will likely encounter confusing errors.
88
89 +-------------------------------------------+
90 | **Don't** |
91 +-------------------------------------------+
92 | .. code-block:: python |
93 | |
94 | L = [] |
95 | |
96 | # This references global variable L |
97 | |
98 | @dask.delayed |
99 | def f(x): |
100 | L.append(x) |
101 | |
102 +-------------------------------------------+
103
104
105
106 Don't rely on side effects
107 --------------------------
108
109 Delayed functions only do something if they are computed. You will always need
110 to pass the output to something that eventually calls compute.
111
112 +--------------------------------+-----------------------------------------+
113 | **Don't** | **Do** |
114 +--------------------------------+-----------------------------------------+
115 | .. code-block:: python | .. code-block:: python |
116 | | |
117 | # Forget to call compute | # Ensure delayed tasks are computed |
118 | | |
119 | dask.delayed(f)(1, 2, 3) | x = dask.delayed(f)(1, 2, 3) |
120 | | ... |
121 | ... | dask.compute(x, ...) |
122 +--------------------------------+-----------------------------------------+
123
124 In the first case here, nothing happens, because ``compute()`` is never called.
125
126 Break up computations into many pieces
127 --------------------------------------
128
129 Every ``dask.delayed`` function call is a single operation from Dask's perspective.
130 You achieve parallelism by having many delayed calls, not by using only a
131 single one: Dask will not look inside a function decorated with ``@dask.delayed``
132 and parallelize that code internally. To accomplish that, it needs your help to
133 find good places to break up a computation.
134
135 +------------------------------------+--------------------------------------+
136 | **Don't** | **Do** |
137 +------------------------------------+--------------------------------------+
138 | .. code-block:: python | .. code-block:: python |
139 | | |
140 | # One giant task | # Break up into many tasks |
141 | | |
142 | | @dask.delayed |
143 | def load(filename): | def load(filename): |
144 | ... | ... |
145 | | |
146 | | @dask.delayed |
147 | def process(data): | def process(data): |
148 | ... | ... |
149 | | |
150 | | @dask.delayed |
151 | def save(data): | def save(data): |
152 | ... | ... |
153 | | |
154 | @dask.delayed | |
155 | def f(filenames): | def f(filenames): |
156 | results = [] | results = [] |
157 | for filename in filenames: | for filename in filenames: |
158 | data = load(filename) | data = load(filename) |
159 | data = process(data) | data = process(data) |
160 | result = save(data) | result = save(data) |
161 | results.append(result) | results.append(result) |
162 | | |
163 | return results | return results |
164 | | |
165 | dask.compute(f(filenames)) | dask.compute(f(filenames)) |
166 +------------------------------------+--------------------------------------+
167
168 The first version only has one delayed task, and so cannot parallelize.
169
170 Avoid too many tasks
171 --------------------
172
173 Every delayed task has an overhead of a few hundred microseconds. Usually this
174 is ok, but it can become a problem if you apply ``dask.delayed`` too finely. In
175 this case, it's often best to break up your many tasks into batches or use one
176 of the Dask collections to help you.
177
178 +------------------------------------+-------------------------------------------------------------+
179 | **Don't** | **Do** |
180 +------------------------------------+-------------------------------------------------------------+
181 | .. code-block:: python | .. code-block:: python |
182 | | |
183 | # Too many tasks | # Use collections |
184 | | |
185 | results = [] | import dask.bag as db |
186 | for x in range(10000000): | b = db.from_sequence(range(10000000), npartitions=1000) |
187 | y = dask.delayed(f)(x) | b = b.map(f) |
188 | results.append(y) | ... |
189 | | |
190 +------------------------------------+-------------------------------------------------------------+
191
192 Here we use ``dask.bag`` to automatically batch applying our function. We could also have constructed
193 our own batching as follows
194
195 .. code-block:: python
196
197 def batch(seq):
198 sub_results = []
199 for x in seq:
200 sub_results.append(f(x))
201 return sub_results
202
203 batches = []
204 for i in range(0, 10000000, 10000):
205 result_batch = dask.delayed(batch)(range(i, i + 10000))
206 batches.append(result_batch)
207
208
209 Here we construct batches where each delayed function call computes for many data points from
210 the original input.
211
212 Avoid calling delayed within delayed functions
213 ----------------------------------------------
214
215 Often, if you are new to using Dask delayed, you place ``dask.delayed`` calls
216 everywhere and hope for the best. While this may actually work, it's usually
217 slow and results in hard-to-understand solutions.
218
219 Usually you never call ``dask.delayed`` within ``dask.delayed`` functions.
220
221 +----------------------------------------+--------------------------------------+
222 | **Don't** | **Do** |
223 +----------------------------------------+--------------------------------------+
224 | .. code-block:: python | .. code-block:: python |
225 | | |
226 | # Delayed function calls delayed | # Normal function calls delayed |
227 | | |
228 | @dask.delayed | |
229 | def process_all(L): | def process_all(L): |
230 | result = [] | result = [] |
231 | for x in L: | for x in L: |
232 | y = dask.delayed(f)(x) | y = dask.delayed(f)(x) |
233 | result.append(y) | result.append(y) |
234 | return result | return result |
235 +----------------------------------------+--------------------------------------+
236
237 Because the normal function only does delayed work it is very fast and so
238 there is no reason to delay it.
239
240 Don't call dask.delayed on other Dask collections
241 -------------------------------------------------
242
243 When you place a Dask array or Dask DataFrame into a delayed call, that function
244 will receive the NumPy or Pandas equivalent. Beware that if your array is
245 large, then this might crash your workers.
246
247 Instead, it's more common to use methods like ``da.map_blocks``
248
249 +--------------------------------------------------+---------------------------------------------+
250 | **Don't** | **Do** |
251 +--------------------------------------------------+---------------------------------------------+
252 | .. code-block:: python | .. code-block:: python |
253 | | |
254 | # Call delayed functions on Dask collections | # Use mapping methods if applicable |
255 | | |
256 | import dask.dataframe as dd | import dask.dataframe as dd |
257 | df = dd.read_csv('/path/to/*.csv') | df = dd.read_csv('/path/to/*.csv') |
258 | | |
259 | dask.delayed(train)(df) | df.map_partitions(train) |
260 +--------------------------------------------------+---------------------------------------------+
261
262 Alternatively, if the procedure doesn't fit into a mapping, you can always
263 turn your arrays or dataframes into *many* delayed
264 objects, for example
265
266 .. code-block:: python
267
268 partitions = df.to_delayed()
269 delayed_values = [dask.delayed(train)(part)
270 for part in partitions]
271
272 However, if you don't mind turning your Dask array/DataFrame into a single
273 chunk, then this is ok.
274
275 .. code-block:: python
276
277 dask.delayed(train)(..., y=df.sum())
278
279
280 Avoid repeatedly putting large inputs into delayed calls
281 --------------------------------------------------------
282
283 Every time you pass a concrete result (anything that isn't delayed) Dask will
284 hash it by default to give it a name. This is fairly fast (around 500 MB/s)
285 but can be slow if you do it over and over again. Instead, it is better to
286 delay your data as well.
287
288 This is especially important when using a distributed cluster to avoid sending
289 your data separately for each function call.
290
291 +------------------------------------------+---------------------------------------------------------+
292 | **Don't** | **Do** |
293 +------------------------------------------+---------------------------------------------------------+
294 | .. code-block:: python | .. code-block:: python |
295 | | |
296 | x = np.array(...) # some large array | x = np.array(...) # some large array |
297 | | x = dask.delayed(x) # delay the data once |
298 | results = [dask.delayed(train)(x, i) | results = [dask.delayed(train)(x, i) |
299 | for i in range(1000)] | for i in range(1000)] |
300 +------------------------------------------+---------------------------------------------------------+
301
302
303 Every call to ``dask.delayed(train)(x, ...)`` has to hash the NumPy array ``x``, which slows things down.