Debian Codegraph @

docs/source/diagnostics-local.rst

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 :orphan:
2
3 Diagnostics (local)
4 ====================
5
6 Profiling parallel code can be challenging, but ``dask.diagnostics`` provides
7 functionality to aid in profiling and inspecting execution with the
8 :doc:`local task scheduler <scheduling>`.
9
10 This page describes the following few built-in options:
11
12 1. ProgressBar
13 2. Profiler
14 3. ResourceProfiler
15 4. CacheProfiler
16
17 Furthermore, this page then provides instructions on how to build your own custom diagnostic.
18
19 .. currentmodule:: dask.diagnostics
20
21
22 Progress Bar
23 ------------
24
25 .. autosummary::
26 ProgressBar
27
28 The ``ProgressBar`` class builds on the scheduler callbacks described above to
29 display a progress bar in the terminal or notebook during computation. This can
30 give a nice feedback during long running graph execution. It can be used as a
31 context manager around calls to ``get`` or ``compute`` to profile the
32 computation:
33
34 .. code-block:: python
35
36 >>> import dask.array as da
37 >>> from dask.diagnostics import ProgressBar
38 >>> a = da.random.default_rng().normal(size=(10000, 10000), chunks=(1000, 1000))
39 >>> res = a.dot(a.T).mean(axis=0)
40
41 >>> with ProgressBar():
42 ... out = res.compute()
43 [########################################] | 100% Completed | 17.1 s
44
45 or registered globally using the ``register`` method:
46
47 .. code-block:: python
48
49 >>> pbar = ProgressBar()
50 >>> pbar.register()
51 >>> out = res.compute()
52 [########################################] | 100% Completed | 17.1 s
53
54 To unregister from the global callbacks, call the ``unregister`` method:
55
56 .. code-block:: python
57
58 >>> pbar.unregister()
59
60
61
62 Profiler
63 --------
64
65 .. autosummary::
66 Profiler
67
68 Dask provides a few tools for profiling execution. As with the ``ProgressBar``,
69 they each can be used as context managers or registered globally.
70
71 The ``Profiler`` class is used to profile Dask's execution at the task level.
72 During execution, it records the following information for each task:
73
74 1. Key
75 2. Task
76 3. Start time in seconds since the epoch
77 4. Finish time in seconds since the epoch
78 5. Worker id
79
80
81 ResourceProfiler
82 ----------------
83
84 .. autosummary::
85 ResourceProfiler
86
87 The ``ResourceProfiler`` class is used to profile Dask's execution at the
88 resource level. During execution, it records the following information
89 for each timestep:
90
91 1. Time in seconds since the epoch
92 2. Memory usage in MB
93 3. % CPU usage
94
95 The default timestep is 1 second, but can be set manually using the ``dt``
96 keyword:
97
98 .. code-block:: python
99
100 >>> from dask.diagnostics import ResourceProfiler
101 >>> rprof = ResourceProfiler(dt=0.5)
102
103
104 CacheProfiler
105 -------------
106
107 .. autosummary::
108 CacheProfiler
109
110 The ``CacheProfiler`` class is used to profile Dask's execution at the scheduler
111 cache level. During execution, it records the following information for each
112 task:
113
114 1. Key
115 2. Task
116 3. Size metric
117 4. Cache entry time in seconds since the epoch
118 5. Cache exit time in seconds since the epoch
119
120 Here the size metric is the output of a function called on the result of each
121 task. The default metric is to count each task (``metric`` is 1 for all tasks).
122 Other functions may be used as a metric instead through the ``metric`` keyword.
123 For example, the ``nbytes`` function found in ``cachey`` can be used to measure
124 the number of bytes in the scheduler cache:
125
126 .. code-block:: python
127
128 >>> from dask.diagnostics import CacheProfiler
129 >>> from cachey import nbytes
130 >>> cprof = CacheProfiler(metric=nbytes)
131
132
133 Example
134 -------
135
136 As an example to demonstrate using the diagnostics, we'll profile some linear
137 algebra done with Dask Array. We'll create a random array, take its QR
138 decomposition, and then reconstruct the initial array by multiplying the Q and
139 R components together. Note that since the profilers (and all diagnostics) are
140 just context managers, multiple profilers can be used in a with block:
141
142 .. code-block:: python
143
144 >>> import dask.array as da
145 >>> from dask.diagnostics import Profiler, ResourceProfiler, CacheProfiler
146 >>> a = da.random.random(size=(10000, 1000), chunks=(1000, 1000))
147 >>> q, r = da.linalg.qr(a)
148 >>> a2 = q.dot(r)
149
150 >>> with Profiler() as prof, ResourceProfiler(dt=0.25) as rprof,
151 ... CacheProfiler() as cprof:
152 ... out = a2.compute()
153
154 The results of each profiler are stored in their ``results`` attribute as a
155 list of ``namedtuple`` objects:
156
157 .. code-block:: python
158
159 >>> prof.results[0]
160 TaskData(key=('tsqr-8d16e396b237bf7a731333130d310cb9_QR_st1', 5, 0),
161 task=(qr, (_apply_random, 'random_sample', 1060164455, (1000, 1000), (), {})),
162 start_time=1454368444.493292,
163 end_time=1454368444.902987,
164 worker_id=4466937856)
165
166 >>> rprof.results[0]
167 ResourceData(time=1454368444.078748, mem=74.100736, cpu=0.0)
168
169 >>> cprof.results[0]
170 CacheData(key=('tsqr-8d16e396b237bf7a731333130d310cb9_QR_st1', 7, 0),
171 task=(qr, (_apply_random, 'random_sample', 1310656009, (1000, 1000), (), {})),
172 metric=1,
173 cache_time=1454368444.49662,
174 free_time=1454368446.769452)
175
176 These can be analyzed separately or viewed in a bokeh plot using the provided
177 ``visualize`` method on each profiler:
178
179 .. code-block:: python
180
181 >>> prof.visualize()
182
183
184 .. raw:: html
185
186 <iframe src="_static/profile.html"
187 marginwidth="0" marginheight="0" scrolling="no"
188 width="650" height="300" style="border:none"></iframe>
189
190 To view multiple profilers at the same time, the :func:`dask.diagnostics.visualize`
191 function can be used. This takes a list of profilers and creates a vertical
192 stack of plots aligned along the x-axis:
193
194 .. code-block:: python
195
196 >>> from dask.diagnostics import visualize
197 >>> visualize([prof, rprof, cprof])
198
199
200 .. raw:: html
201
202 <iframe src="_static/stacked_profile.html"
203 marginwidth="0" marginheight="0" scrolling="no"
204 width="650" height="700" style="border:none"></iframe>
205
206
207 Looking at the above figure, from top to bottom:
208
209 1. The results from the ``Profiler`` object: This shows the execution time for
210 each task as a rectangle, organized along the y-axis by worker (in this case
211 threads). Similar tasks are grouped by color and, by hovering over each task,
212 one can see the key and task that each block represents.
213
214 2. The results from the ``ResourceProfiler`` object: This shows two lines, one
215 for total CPU percentage used by all the workers, and one for total memory
216 usage.
217
218 3. The results from the ``CacheProfiler`` object: This shows a line for each
219 task group, plotting the sum of the current ``metric`` in the cache against
220 time. In this case it's the default metric (count) and the lines represent
221 the number of each object in the cache at time. Note that the grouping and
222 coloring is the same as for the ``Profiler`` plot, and that the task
223 represented by each line can be found by hovering over the line.
224
225 From these plots we can see that the initial tasks (calls to
226 ``numpy.random.random`` and ``numpy.linalg.qr`` for each chunk) are run
227 concurrently, but only use slightly more than 100\% CPU. This is because the
228 call to ``numpy.linalg.qr`` currently doesn't release the Global Interpreter
229 Lock (GIL), so those calls can't truly be done in parallel. Next, there's a reduction
230 step where all the blocks are combined. This requires all the results from the
231 first step to be held in memory, as shown by the increased number of results in
232 the cache, and increase in memory usage. Immediately after this task ends, the
233 number of elements in the cache decreases, showing that they were only needed
234 for this step. Finally, there's an interleaved set of calls to ``dot`` and
235 ``sum``. Looking at the CPU plot, it shows that these run both concurrently and in
236 parallel, as the CPU percentage spikes up to around 350\%.
237
238
239 Custom Callbacks
240 ----------------
241
242 .. autosummary:: Callback
243
244 Schedulers based on ``dask.local.get_async`` (currently
245 ``dask.get``, ``dask.threaded.get``, and ``dask.multiprocessing.get``)
246 accept five callbacks, allowing for inspection of scheduler execution.
247
248 The callbacks are:
249
250 1. ``start(dsk)``: Run at the beginning of execution, right before the
251 state is initialized. Receives the Dask graph
252
253 2. ``start_state(dsk, state)``: Run at the beginning of execution, right
254 after the state is initialized. Receives the Dask graph and scheduler state
255
256 3. ``pretask(key, dsk, state)``: Run every time a new task is started.
257 Receives the key of the task to be run, the Dask graph, and the scheduler state
258
259 4. ``posttask(key, result, dsk, state, id)``: Run every time a task is finished.
260 Receives the key of the task that just completed, the result, the Dask graph,
261 the scheduler state, and the id of the worker that ran the task
262
263 5. ``finish(dsk, state, errored)``: Run at the end of execution, right before the
264 result is returned. Receives the Dask graph, the scheduler state, and a boolean
265 indicating whether or not the exit was due to an error
266
267 Custom diagnostics can be created either by instantiating the ``Callback``
268 class with the some of the above methods as keywords or by subclassing the
269 ``Callback`` class.
270 Here we create a class that prints the name of every key as it's computed:
271
272 .. code-block:: python
273
274 from dask.callbacks import Callback
275 class PrintKeys(Callback):
276 def _pretask(self, key, dask, state):
277 """Print the key of every task as it's started"""
278 print("Computing: {0}!".format(repr(key)))
279
280 This can now be used as a context manager during computation:
281
282 .. code-block:: python
283
284 >>> from operator import add, mul
285 >>> dsk = {'a': (add, 1, 2), 'b': (add, 3, 'a'), 'c': (mul, 'a', 'b')}
286
287 >>> with PrintKeys():
288 ... get(dsk, 'c')
289 Computing 'a'!
290 Computing 'b'!
291 Computing 'c'!
292
293 Alternatively, functions may be passed in as keyword arguments to ``Callback``:
294
295 .. code-block:: python
296
297 >>> def printkeys(key, dask, state):
298 ... print("Computing: {0}!".format(repr(key)))
299
300 >>> with Callback(pretask=printkeys):
301 ... get(dsk, 'c')
302 Computing 'a'!
303 Computing 'b'!
304 Computing 'c'!
305
306
307 API
308 ---
309
310 .. autosummary::
311 CacheProfiler
312 Callback
313 Profiler
314 ProgressBar
315 ResourceProfiler
316 visualize
317
318 .. autofunction:: ProgressBar
319 .. autofunction:: Profiler
320 .. autofunction:: ResourceProfiler
321 .. autofunction:: CacheProfiler
322 .. autofunction:: Callback
323 .. autofunction:: visualize