Debian Codegraph @

docs/source/how-to/debug.rst

raw
1 Debug
2 =====
3
4 Debugging parallel programs is hard. Normal debugging tools like logging and
5 using ``pdb`` to interact with tracebacks stop working normally when exceptions
6 occur in far-away machines, different processes, or threads.
7
8 Dask has a variety of mechanisms to make this process easier. Depending on
9 your situation, some of these approaches may be more appropriate than others.
10
11 These approaches are ordered from lightweight or easy solutions to more
12 involved solutions.
13
14 Printing
15 --------
16
17 One of the most basic methods of debugging is to simply print values and inspect them.
18 However, when using Python's built-in :func:`print` function with Dask, those prints
19 often happen on remote machines instead of in the user's Python session, which typically
20 isn't the experience developers want when debugging.
21
22 Because of this, Dask offers a :func:`dask.distributed.print <distributed.print>` function which acts
23 just like Python's built-in :func:`print` but also forwards the printed output to the
24 client side Python session. This makes distributed debugging feel more like debugging
25 locally.
26
27 Exceptions
28 ----------
29
30 When a task in your computation fails, the standard way of understanding what
31 went wrong is to look at the exception and traceback. Often people do this
32 with the ``pdb`` module, IPython ``%debug`` or ``%pdb`` magics, or by just
33 looking at the traceback and investigating where in their code the exception
34 occurred.
35
36 Normally when a computation executes in a separate thread or a different
37 machine, these approaches break down. To address this, Dask provides a few
38 mechanisms to recreate the normal Python debugging experience.
39
40 Inspect Exceptions and Tracebacks
41 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
42
43 By default, Dask already copies the exception and traceback wherever they
44 occur and reraises that exception locally. If your task failed with a
45 ``ZeroDivisionError`` remotely, then you'll get a ``ZeroDivisionError`` in your
46 interactive session. Similarly you'll see a full traceback of where this error
47 occurred, which, just like in normal Python, can help you to identify the
48 troublesome spot in your code.
49
50 However, you cannot use the ``pdb`` module or ``%debug`` IPython magics with
51 these tracebacks to look at the value of variables during failure. You can
52 only inspect things visually. Additionally, the top of the traceback may be
53 filled with functions that are Dask-specific and not relevant to your
54 problem, so you can safely ignore these.
55
56 Both the single-machine and distributed schedulers do this.
57
58
59 Use the Single-Threaded Scheduler
60 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
61
62 Dask ships with a simple single-threaded scheduler. This doesn't offer any
63 parallel performance improvements but does run your Dask computation
64 faithfully in your local thread, allowing you to use normal tools like ``pdb``,
65 ``%debug`` IPython magics, the profiling tools like the ``cProfile`` module, and
66 `snakeviz <https://jiffyclub.github.io/snakeviz/>`_. This allows you to use
67 all of your normal Python debugging tricks in Dask computations, as long as you
68 don't need parallelism.
69
70 The single-threaded scheduler can be used, for example, by setting
71 ``scheduler='single-threaded'`` in a compute call:
72
73 .. code-block:: python
74
75 >>> x.compute(scheduler='single-threaded')
76
77 For more ways to configure schedulers, see the :ref:`scheduler configuration
78 documentation <scheduling-configuration>`.
79
80 This only works for single-machine schedulers. It does not work with
81 ``dask.distributed`` unless you are comfortable using the Tornado API (look at the
82 `testing infrastructure
83 <https://distributed.dask.org/en/latest/develop.html#writing-tests>`_
84 docs, which accomplish this). Also, because this operates on a single machine,
85 it assumes that your computation can run on a single machine without exceeding
86 memory limits. It may be wise to use this approach on smaller versions of your
87 problem if possible.
88
89
90 Rerun Failed Task Locally
91 ~~~~~~~~~~~~~~~~~~~~~~~~~
92
93 If a remote task fails, we can collect the function and all inputs, bring them
94 to the local thread, and then rerun the function in hopes of triggering the
95 same exception locally where normal debugging tools can be used.
96
97 With the single-machine schedulers, use the ``rerun_exceptions_locally=True``
98 keyword:
99
100 .. code-block:: python
101
102 >>> x.compute(rerun_exceptions_locally=True)
103
104 On the distributed scheduler use the ``recreate_error_locally`` method on
105 anything that contains ``Futures``:
106
107 .. code-block:: python
108
109 >>> x.compute()
110 ZeroDivisionError(...)
111
112 >>> %pdb
113 >>> future = client.compute(x)
114 >>> client.recreate_error_locally(future)
115
116
117 Remove Failed Futures Manually
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119
120 Sometimes only parts of your computations fail, for example, if some rows of a
121 CSV dataset are faulty in some way. When running with the distributed
122 scheduler, you can remove chunks of your data that have produced bad results if
123 you switch to dealing with Futures:
124
125 .. code-block:: python
126
127 >>> import dask.dataframe as dd
128 >>> df = ... # create dataframe
129 >>> df = df.persist() # start computing on the cluster
130
131 >>> from distributed.client import futures_of
132 >>> futures = futures_of(df) # get futures behind dataframe
133 >>> futures
134 [<Future: status: finished, type: pd.DataFrame, key: load-1>
135 <Future: status: finished, type: pd.DataFrame, key: load-2>
136 <Future: status: error, key: load-3>
137 <Future: status: pending, key: load-4>
138 <Future: status: error, key: load-5>]
139
140 >>> # wait until computation is done
141 >>> while any(f.status == 'pending' for f in futures):
142 ... sleep(0.1)
143
144 >>> # pick out only the successful futures and reconstruct the dataframe
145 >>> good_futures = [f for f in futures if f.status == 'finished']
146 >>> df = dd.from_delayed(good_futures, meta=df._meta)
147
148 This is a bit of a hack, but often practical when first exploring messy data.
149 If you are using the concurrent.futures API (map, submit, gather), then this
150 approach is more natural.
151
152
153 Inspect Scheduling State
154 ------------------------
155
156 Not all errors present themselves as exceptions. For example, in a distributed
157 system workers may die unexpectedly, your computation may be unreasonably
158 slow due to inter-worker communication or scheduler overhead, or one of several
159 other issues. Getting feedback about what's going on can help to identify
160 both failures and general performance bottlenecks.
161
162 For the single-machine scheduler, see :doc:`local diagnostic
163 <../diagnostics-local>` documentation. The rest of the section will
164 assume that you are using the `distributed scheduler
165 <https://distributed.dask.org/en/latest/>`_ where these issues arise more
166 commonly.
167
168 Web Diagnostics
169 ~~~~~~~~~~~~~~~
170
171 First, the distributed scheduler has a number of `diagnostic tools
172 <https://distributed.dask.org/en/latest/diagnosing-performance.html>`_ showing dozens of
173 recorded metrics like CPU, memory, network, and disk use, a history of previous
174 tasks, allocation of tasks to workers, worker memory pressure, work stealing,
175 open file handle limits, etc. *Many* problems can be correctly diagnosed by
176 inspecting these pages. By default, these are available at
177 ``http://scheduler:8787/`` where ``scheduler`` should be replaced by the address of the
178 scheduler. See `diagnosing performance docs
179 <https://distributed.dask.org/en/latest/diagnosing-performance.html>`_ for more information.
180
181 Logs
182 ~~~~
183
184 The scheduler, workers, and client all emits logs using `Python's standard
185 logging module <https://docs.python.org/3/library/logging.html>`_. By default,
186 these emit to standard error. When Dask is launched by a cluster job scheduler
187 (SGE/SLURM/YARN/Mesos/Marathon/Kubernetes/whatever), that system will track
188 these logs and will have an interface to help you access them. If you are
189 launching Dask on your own, they will probably dump to the screen unless you
190 `redirect stderr to a file
191 <https://en.wikipedia.org/wiki/Redirection_(computing)#Redirecting_to_and_from_the_standard_file_handles>`_
192 .
193
194 You can control the logging verbosity in the :doc:`../configuration`, for example,
195 the ``~/.config/dask/*.yaml`` files.
196 Defaults currently look like the following:
197
198 .. code-block:: yaml
199
200 logging:
201 distributed: info
202 distributed.client: warning
203 bokeh: error
204
205 Logging for specific components like ``distributed.client``, ``distributed.scheduler``,
206 ``distributed.nanny``, ``distributed.worker``, etc. can each be independently configured.
207 So, for example, you could add a line like ``distributed.worker: debug`` to get
208 *very* verbose output from the workers.
209
210 Furthermore, you can explicitly assign handlers to loggers. The following example
211 assigns both file ("output.log") and console output to the scheduler and workers.
212 See the `python logging`_ documentation for information on the meaning of
213 specific terms here.
214
215 .. code-block:: yaml
216
217 logging:
218 version: 1
219 handlers:
220 file:
221 class: logging.handlers.RotatingFileHandler
222 filename: output.log
223 level: INFO
224 console:
225 class: logging.StreamHandler
226 level: INFO
227 loggers:
228 distributed.worker:
229 level: INFO
230 handlers:
231 - file
232 - console
233 distributed.scheduler:
234 level: INFO
235 handlers:
236 - file
237 - console
238
239 .. _python logging: https://docs.python.org/3/library/logging.html
240
241
242 LocalCluster
243 ------------
244
245 If you are using the distributed scheduler from a single machine, you may be
246 setting up workers manually using the command line interface or you may be
247 using `LocalCluster <https://distributed.dask.org/en/latest/api.html#cluster>`_
248 which is what runs when you just call ``Client()``:
249
250 .. code-block:: python
251
252 >>> from dask.distributed import Client, LocalCluster
253 >>> client = Client() # This is actually the following two commands
254
255 >>> cluster = LocalCluster()
256 >>> client = Client(cluster.scheduler.address)
257
258 LocalCluster is useful because the scheduler and workers are in the same
259 process with you, so you can easily inspect their `state
260 <https://distributed.dask.org/en/latest/scheduling-state.html>`_ while
261 they run (they are running in a separate thread):
262
263 .. code-block:: python
264
265 >>> cluster.scheduler.processing
266 {'worker-one:59858': {'inc-123', 'add-443'},
267 'worker-two:48248': {'inc-456'}}
268
269 You can also do this for the workers *if* you run them without nanny processes:
270
271 .. code-block:: python
272
273 >>> cluster = LocalCluster(nanny=False)
274 >>> client = Client(cluster)
275
276 This can be very helpful if you want to use the Dask distributed API and still
277 want to investigate what is going on directly within the workers. Information
278 is not distilled for you like it is in the web diagnostics, but you have full
279 low-level access.