Debian Codegraph @

docs/source/scheduling.rst

raw ◀ ▶
1 Debian patch touch this file
1 Scheduling
2 ==========
3
4 All of the large-scale Dask collections like
5 :doc:`Dask Array <array>`, :doc:`Dask DataFrame <dataframe>`, and :doc:`Dask Bag <bag>`
6 and the fine-grained APIs like :doc:`delayed <delayed>` and :doc:`futures <futures>`
7 generate task graphs where each node in the graph is a normal Python function
8 and edges between nodes are normal Python objects
9 that are created by one task as outputs and used as inputs in another task.
10 After Dask generates these task graphs, it needs to execute them on parallel hardware.
11 This is the job of a *task scheduler*.
12 Different task schedulers exist, and each will consume a task graph and compute the
13 same result, but with different performance characteristics.
14
15 Dask has two families of task schedulers:
16
17 1. **Single-machine scheduler**: This scheduler provides basic features on a
18 local process or thread pool. This scheduler was made first and is the
19 default. It is simple and cheap to use, although it can only be used on
20 a single machine and does not scale
21 2. **Distributed scheduler**: This scheduler is more sophisticated, offers
22 more features, but also requires a bit more effort to set up. It can
23 run locally or distributed across a cluster
24
25 |
26
27 .. image:: images/dask-overview-schedulers.svg
28 :alt: Dask is composed of three parts. "Collections" create "Task Graphs" which are then sent to the "Scheduler" for execution. There are two types of schedulers that are described in more detail below.
29 :align: center
30 :scale: 135%
31
32 |
33
34 For different computations you may find better performance with particular scheduler settings.
35 This document helps you understand how to choose between and configure different schedulers,
36 and provides guidelines on when one might be more appropriate.
37
38 .. _threaded-scheduler:
39
40 Local Threads
41 -------------
42
43 .. code-block:: python
44
45 import dask
46 dask.config.set(scheduler='threads') # overwrite default with threaded scheduler
47
48 The threaded scheduler executes computations with a local
49 ``concurrent.futures.ThreadPoolExecutor``.
50 It is lightweight and requires no setup.
51 It introduces very little task overhead (around 50us per task)
52 and, because everything occurs in the same process,
53 it incurs no costs to transfer data between tasks.
54 However, due to Python's Global Interpreter Lock (GIL),
55 this scheduler only provides parallelism when your computation is dominated by non-Python code,
56 as is primarily the case when operating on numeric data in NumPy arrays, Pandas DataFrames,
57 or using any of the other C/C++/Cython based projects in the ecosystem.
58
59 The threaded scheduler is the default choice for
60 :doc:`Dask Array <array>`, :doc:`Dask DataFrame <dataframe>`, and :doc:`Dask Delayed <delayed>`.
61 However, if your computation is dominated by processing pure Python objects
62 like strings, dicts, or lists,
63 then you may want to try one of the process-based schedulers below
64 (we currently recommend the distributed scheduler on a local machine).
65
66
67 Local Processes
68 ---------------
69
70 .. note::
71
72 The :ref:`distributed scheduler <local distributed>` described below is often a better choice today.
73 We encourage readers to continue reading after this section.
74
75 .. tip::
76
77 Be sure to include an ``if __name__ == "__main__":`` block when using the multiprocessing scheduler
78 in a standalone Python script. See `Standalone Python scripts`_ for more details.
79
80 .. code-block:: python
81
82 import dask
83 dask.config.set(scheduler='processes') # overwrite default with multiprocessing scheduler
84
85
86 The multiprocessing scheduler executes computations with a local
87 ``concurrent.futures.ProcessPoolExecutor``.
88 It is lightweight to use and requires no setup.
89 Every task and all of its dependencies are shipped to a local process,
90 executed, and then their result is shipped back to the main process.
91 This means that it is able to bypass issues with the GIL and provide parallelism
92 even on computations that are dominated by pure Python code,
93 such as those that process strings, dicts, and lists.
94
95 However, moving data to remote processes and back can introduce performance penalties,
96 particularly when the data being transferred between processes is large.
97 The multiprocessing scheduler is an excellent choice when workflows are relatively linear,
98 and so does not involve significant inter-task data transfer
99 as well as when inputs and outputs are both small, like filenames and counts.
100
101 This is common in basic data ingestion workloads,
102 such as those are common in :doc:`Dask Bag <bag>`,
103 where the multiprocessing scheduler is the default:
104
105 .. code-block:: python
106
107 >>> import dask.bag as db
108 >>> db.read_text('*.json').map(json.loads).pluck('name').frequencies().compute()
109 {'alice': 100, 'bob': 200, 'charlie': 300}
110
111 For more complex workloads,
112 where large intermediate results may be depended upon by multiple downstream tasks,
113 we generally recommend the use of the distributed scheduler on a local machine.
114 The distributed scheduler is more intelligent about moving around large intermediate results.
115
116 .. _single-threaded-scheduler:
117
118 Single Thread
119 -------------
120
121 .. code-block:: python
122
123 import dask
124 dask.config.set(scheduler='synchronous') # overwrite default with single-threaded scheduler
125
126 The single-threaded synchronous scheduler executes all computations in the local thread
127 with no parallelism at all.
128 This is particularly valuable for debugging and profiling,
129 which are more difficult when using threads or processes.
130
131 For example, when using IPython or Jupyter notebooks, the ``%debug``, ``%pdb``, or ``%prun`` magics
132 will not work well when using the parallel Dask schedulers
133 (they were not designed to be used in a parallel computing context).
134 However, if you run into an exception and want to step into the debugger,
135 you may wish to rerun your computation under the single-threaded scheduler
136 where these tools will function properly.
137
138
139 .. _local distributed:
140
141 Dask Distributed (local)
142 ------------------------
143
144 .. tip::
145
146 Be sure to include an ``if __name__ == "__main__":`` block when using the local distributed scheduler
147 in a standalone Python script. See `Standalone Python scripts`_ for more details.
148
149 .. code-block:: python
150
151 from dask.distributed import Client
152 client = Client()
153 # or
154 client = Client(processes=False)
155
156 The Dask distributed scheduler can either be :doc:`setup on a cluster <deploying>`
157 or run locally on a personal machine. Despite having the name "distributed",
158 it is often pragmatic on local machines for a few reasons:
159
160 1. It provides access to asynchronous API, notably :doc:`Futures <futures>`
161 2. It provides a diagnostic dashboard that can provide valuable insight on
162 performance and progress
163 3. It handles data locality with more sophistication, and so can be more
164 efficient than the multiprocessing scheduler on workloads that require
165 multiple processes
166
167 You can read more about using the Dask distributed scheduler on a single machine in
168 :doc:`these docs <deploying>`.
169
170
171 Dask Distributed (Cluster)
172 --------------------------
173
174 You can also run Dask on a distributed cluster.
175 There are a variety of ways to set this up depending on your cluster.
176 We recommend referring to :doc:`how to deploy Dask clusters <deploying>` for more information.
177
178 .. _scheduling-configuration:
179
180 Configuration
181 -------------
182
183 You can configure the global default scheduler by using the ``dask.config.set(scheduler...)`` command.
184 This can be done globally:
185
186 .. code-block:: python
187
188 dask.config.set(scheduler='threads')
189
190 x.compute()
191
192 or as a context manager:
193
194 .. code-block:: python
195
196 with dask.config.set(scheduler='threads'):
197 x.compute()
198
199 or within a single compute call:
200
201 .. code-block:: python
202
203 x.compute(scheduler='threads')
204
205 Each scheduler may support extra keywords specific to that scheduler. For example,
206 the pool-based single-machine scheduler allows you to provide custom pools or
207 specify the desired number of workers:
208
209 .. code-block:: python
210
211 from concurrent.futures import ThreadPoolExecutor
212 with dask.config.set(pool=ThreadPoolExecutor(4)):
213 x.compute()
214
215 with dask.config.set(num_workers=4):
216 x.compute()
217
218 Note that Dask also supports custom ``concurrent.futures.Executor`` subclasses,
219 such as the ``ReusablePoolExecutor`` from loky_:
220
221 .. _loky: https://github.com/joblib/loky
222
223 .. code-block:: python
224
225 from loky import get_reusable_executor
226 with dask.config.set(scheduler=get_reusable_executor()):
227 x.compute()
228
229 Other libraries like ipyparallel_ and mpi4py_ also supply
230 ``concurrent.futures.Executor`` subclasses that could be used as well.
231
232 .. _ipyparallel: https://ipyparallel.readthedocs.io/en/latest/examples/Futures.html#Executors
233 .. _mpi4py: https://mpi4py.readthedocs.io/en/latest/mpi4py.futures.html
234
235
236 Standalone Python scripts
237 -------------------------
238
239 Some care needs to be taken when running Dask schedulers in a standalone Python script.
240 Specifically, when using the single-machine multiprocessing scheduler or the local distributed
241 scheduler, Dask will create additional Python processes. As part of Python's normal subprocess
242 initialization, Python will import the contents of the script in every child process that is created
243 (this is true for any Python code where child processes are created -- not just in Dask).
244 This import initialization can lead to subprocesses recursively creating other subprocesses
245 and eventually an error is raised.
246
•247 Common error encountered
248
249 .. code-block:: python
250
251 An attempt has been made to start a new process before the
252 current process has finished its bootstrapping phase.
253
254 This probably means that you are not using fork to start your
255 child processes and you have forgotten to use the proper idiom
256 in the main module:
257
258 if __name__ == '__main__':
259 freeze_support()
260 ...
261
262 The "freeze_support()" line can be omitted if the program
263 is not going to be frozen to produce an executable.
264
265 To avoid this types of error, you should place any Dask code that create subprocesses
266 (for example, all ``compute()`` calls that use the multiprocessing scheduler, or when creating
267 a local distributed cluster) inside a ``if __name__ == "__main__":`` block. This ensures
268 subprocesses are only created when your script is run as the main program.
269
270 For example, running ``python myscript.py`` with the script below will raise an error:
271
272 .. code-block:: python
273
274 # myscript.py
275
276 from dask.distributed import Client
277 client = Client() # Will raise an error when creating local subprocesses
278
279
280 Instead one should place the contents of the script inside a ``if __name__ == "__main__":`` block:
281
282 .. code-block:: python
283
284 # myscript.py
285
286 if __name__ == "__main__": # This avoids infinite subprocess creation
287
288 from dask.distributed import Client
289 client = Client()
290
291 For more details on this topic see
292 `Python's multiprocessing guidelines <https://docs.python.org/3/library/multiprocessing.html#programming-guidelines>`_.