| 1 |
Futures |
| 2 |
======= |
| 3 |
|
| 4 |
.. meta:: |
| 5 |
:description: Dask futures reimplements the Python futures API so you can scale your Python futures workflow across a Dask cluster. |
| 6 |
|
| 7 |
Dask supports a real-time task framework that extends Python's |
| 8 |
`concurrent.futures <https://docs.python.org/3/library/concurrent.futures.html>`_ |
| 9 |
interface. Dask futures allow you to scale generic Python workflows across |
| 10 |
a Dask cluster with minimal code changes. |
| 11 |
|
| 12 |
.. raw:: html |
| 13 |
|
| 14 |
<iframe width="560" |
| 15 |
height="315" |
| •16 |
src="https://www.youtube-nocookie.com/embed/07EiCpdhtDE" |
| 17 |
style="margin: 0 auto 20px auto; display: block;" |
| 18 |
frameborder="0" |
| 19 |
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" |
| 20 |
allowfullscreen></iframe> |
| 21 |
|
| 22 |
.. currentmodule:: distributed |
| 23 |
|
| 24 |
This interface is good for arbitrary task scheduling like |
| 25 |
:doc:`dask.delayed <delayed>`, but is immediate rather than lazy, which |
| 26 |
provides some more flexibility in situations where the computations may evolve |
| 27 |
over time. These features depend on the second generation task scheduler found in |
| 28 |
`dask.distributed <https://distributed.dask.org/en/latest>`_ (which, |
| 29 |
despite its name, runs very well on a single machine). |
| 30 |
|
| 31 |
|
| 32 |
Examples |
| 33 |
-------- |
| 34 |
|
| 35 |
Visit https://examples.dask.org/futures.html to see and run examples |
| 36 |
using futures with Dask. |
| 37 |
|
| 38 |
Start Dask Client |
| 39 |
----------------- |
| 40 |
|
| 41 |
You must start a ``Client`` to use the futures interface. This tracks state |
| 42 |
among the various worker processes or threads: |
| 43 |
|
| 44 |
.. code-block:: python |
| 45 |
|
| 46 |
from dask.distributed import Client |
| 47 |
|
| 48 |
client = Client() # start local workers as processes |
| 49 |
# or |
| 50 |
client = Client(processes=False) # start local workers as threads |
| 51 |
|
| 52 |
If you have `Bokeh <https://docs.bokeh.org>`_ installed, then this starts up a |
| 53 |
diagnostic dashboard at ``http://localhost:8787`` . |
| 54 |
|
| 55 |
Submit Tasks |
| 56 |
------------ |
| 57 |
|
| 58 |
.. autosummary:: |
| 59 |
Client.submit |
| 60 |
Client.map |
| 61 |
Future.result |
| 62 |
|
| 63 |
You can submit individual tasks using the ``submit`` method: |
| 64 |
|
| 65 |
.. code-block:: python |
| 66 |
|
| 67 |
def inc(x): |
| 68 |
return x + 1 |
| 69 |
|
| 70 |
def add(x, y): |
| 71 |
return x + y |
| 72 |
|
| 73 |
a = client.submit(inc, 10) # calls inc(10) in background thread or process |
| 74 |
b = client.submit(inc, 20) # calls inc(20) in background thread or process |
| 75 |
|
| 76 |
The ``submit`` function returns a ``Future``, which refers to a remote result. This result may |
| 77 |
not yet be completed: |
| 78 |
|
| 79 |
.. code-block:: python |
| 80 |
|
| 81 |
>>> a |
| 82 |
<Future: status: pending, key: inc-b8aaf26b99466a7a1980efa1ade6701d> |
| 83 |
|
| 84 |
Eventually it will complete. The result stays in the remote |
| 85 |
thread/process/worker until you ask for it back explicitly: |
| 86 |
|
| 87 |
.. code-block:: python |
| 88 |
|
| 89 |
>>> a |
| 90 |
<Future: status: finished, type: int, key: inc-b8aaf26b99466a7a1980efa1ade6701d> |
| 91 |
|
| 92 |
>>> a.result() # blocks until task completes and data arrives |
| 93 |
11 |
| 94 |
|
| 95 |
You can pass futures as inputs to submit. Dask automatically handles dependency |
| 96 |
tracking; once all input futures have completed, they will be moved onto a |
| 97 |
single worker (if necessary), and then the computation that depends on them |
| 98 |
will be started. You do not need to wait for inputs to finish before |
| 99 |
submitting a new task; Dask will handle this automatically: |
| 100 |
|
| 101 |
.. code-block:: python |
| 102 |
|
| 103 |
c = client.submit(add, a, b) # calls add on the results of a and b |
| 104 |
|
| 105 |
Similar to Python's ``map``, you can use ``Client.map`` to call the same |
| 106 |
function and many inputs: |
| 107 |
|
| 108 |
.. code-block:: python |
| 109 |
|
| 110 |
futures = client.map(inc, range(1000)) |
| 111 |
|
| 112 |
However, note that each task comes with about 1ms of overhead. If you want to |
| 113 |
map a function over a large number of inputs, then you might consider |
| 114 |
:doc:`dask.bag <bag>` or :doc:`dask.dataframe <dataframe>` instead. |
| 115 |
|
| 116 |
.. note: See `this page <https://docs.dask.org/en/latest/graphs.html>`_ for |
| 117 |
restrictions on what functions you use with Dask. |
| 118 |
|
| 119 |
Move Data |
| 120 |
--------- |
| 121 |
|
| 122 |
.. autosummary:: |
| 123 |
Future.result |
| 124 |
Client.gather |
| 125 |
Client.scatter |
| 126 |
|
| 127 |
Given any future, you can call the ``.result`` method to gather the result. |
| 128 |
This will block until the future is done computing and then transfer the result |
| 129 |
back to your local process if necessary: |
| 130 |
|
| 131 |
.. code-block:: python |
| 132 |
|
| 133 |
>>> c.result() |
| 134 |
32 |
| 135 |
|
| 136 |
You can gather many results concurrently using the ``Client.gather`` method. |
| 137 |
This can be more efficient than calling ``.result()`` on each future |
| 138 |
sequentially: |
| 139 |
|
| 140 |
.. code-block:: python |
| 141 |
|
| 142 |
>>> # results = [future.result() for future in futures] |
| 143 |
>>> results = client.gather(futures) # this can be faster |
| 144 |
|
| 145 |
If you have important local data that you want to include in your computation, |
| 146 |
you can either include it as a normal input to a submit or map call: |
| 147 |
|
| 148 |
.. code-block:: python |
| 149 |
|
| 150 |
>>> df = pd.read_csv('training-data.csv') |
| 151 |
>>> future = client.submit(my_function, df) |
| 152 |
|
| 153 |
Or you can ``scatter`` it explicitly. Scattering moves your data to a worker |
| 154 |
and returns a future pointing to that data: |
| 155 |
|
| 156 |
.. code-block:: python |
| 157 |
|
| 158 |
>>> remote_df = client.scatter(df) |
| 159 |
>>> remote_df |
| 160 |
<Future: status: finished, type: DataFrame, key: bbd0ca93589c56ea14af49cba470006e> |
| 161 |
|
| 162 |
>>> future = client.submit(my_function, remote_df) |
| 163 |
|
| 164 |
Both of these accomplish the same result, but using scatter can sometimes be |
| 165 |
faster. This is especially true if you use processes or distributed workers |
| 166 |
(where data transfer is necessary) and you want to use ``df`` in many |
| 167 |
computations. Scattering the data beforehand avoids excessive data movement. |
| 168 |
|
| 169 |
Calling scatter on a list scatters all elements individually. Dask will spread |
| 170 |
these elements evenly throughout workers in a round-robin fashion: |
| 171 |
|
| 172 |
.. code-block:: python |
| 173 |
|
| 174 |
>>> client.scatter([1, 2, 3]) |
| 175 |
[<Future: status: finished, type: int, key: c0a8a20f903a4915b94db8de3ea63195>, |
| 176 |
<Future: status: finished, type: int, key: 58e78e1b34eb49a68c65b54815d1b158>, |
| 177 |
<Future: status: finished, type: int, key: d3395e15f605bc35ab1bac6341a285e2>] |
| 178 |
|
| 179 |
References, Cancellation, and Exceptions |
| 180 |
---------------------------------------- |
| 181 |
|
| 182 |
.. autosummary:: |
| 183 |
Future.cancel |
| 184 |
Future.exception |
| 185 |
Future.traceback |
| 186 |
Client.cancel |
| 187 |
|
| 188 |
Dask will only compute and hold onto results for which there are active |
| 189 |
futures. In this way, your local variables define what is active in Dask. When |
| 190 |
a future is garbage collected by your local Python session, Dask will feel free |
| 191 |
to delete that data or stop ongoing computations that were trying to produce |
| 192 |
it: |
| 193 |
|
| 194 |
.. code-block:: python |
| 195 |
|
| 196 |
>>> del future # deletes remote data once future is garbage collected |
| 197 |
|
| 198 |
You can also explicitly cancel a task using the ``Future.cancel`` or |
| 199 |
``Client.cancel`` methods: |
| 200 |
|
| 201 |
.. code-block:: python |
| 202 |
|
| 203 |
>>> future.cancel() # deletes data even if other futures point to it |
| 204 |
|
| 205 |
If a future fails, then Dask will raise the remote exceptions and tracebacks if |
| 206 |
you try to get the result: |
| 207 |
|
| 208 |
.. code-block:: python |
| 209 |
|
| 210 |
def div(x, y): |
| 211 |
return x / y |
| 212 |
|
| 213 |
>>> a = client.submit(div, 1, 0) # 1 / 0 raises a ZeroDivisionError |
| 214 |
>>> a |
| 215 |
<Future: status: error, key: div-3601743182196fb56339e584a2bf1039> |
| 216 |
|
| 217 |
>>> a.result() |
| 218 |
1 def div(x, y): |
| 219 |
----> 2 return x / y |
| 220 |
|
| 221 |
ZeroDivisionError: division by zero |
| 222 |
|
| 223 |
All futures that depend on an erred future also err with the same exception: |
| 224 |
|
| 225 |
.. code-block:: python |
| 226 |
|
| 227 |
>>> b = client.submit(inc, a) |
| 228 |
>>> b |
| 229 |
<Future: status: error, key: inc-15e2e4450a0227fa38ede4d6b1a952db> |
| 230 |
|
| 231 |
You can collect the exception or traceback explicitly with the |
| 232 |
``Future.exception`` or ``Future.traceback`` methods. |
| 233 |
|
| 234 |
|
| 235 |
Waiting on Futures |
| 236 |
------------------ |
| 237 |
|
| 238 |
.. autosummary:: |
| 239 |
as_completed |
| 240 |
wait |
| 241 |
|
| 242 |
You can wait on a future or collection of futures using the ``wait`` function: |
| 243 |
|
| 244 |
.. code-block:: python |
| 245 |
|
| 246 |
from dask.distributed import wait |
| 247 |
|
| 248 |
>>> wait(futures) |
| 249 |
|
| 250 |
This blocks until all futures are finished or have erred. |
| 251 |
|
| 252 |
You can also iterate over the futures as they complete using the |
| 253 |
``as_completed`` function: |
| 254 |
|
| 255 |
.. code-block:: python |
| 256 |
|
| 257 |
from dask.distributed import as_completed |
| 258 |
|
| 259 |
futures = client.map(score, x_values) |
| 260 |
|
| 261 |
best = -1 |
| 262 |
for future in as_completed(futures): |
| 263 |
y = future.result() |
| 264 |
if y > best: |
| 265 |
best = y |
| 266 |
|
| 267 |
For greater efficiency, you can also ask ``as_completed`` to gather the results |
| 268 |
in the background: |
| 269 |
|
| 270 |
.. code-block:: python |
| 271 |
|
| 272 |
for future, result in as_completed(futures, with_results=True): |
| 273 |
# y = future.result() # don't need this |
| 274 |
... |
| 275 |
|
| 276 |
Or collect all futures in batches that had arrived since the last iteration: |
| 277 |
|
| 278 |
.. code-block:: python |
| 279 |
|
| 280 |
for batch in as_completed(futures, with_results=True).batches(): |
| 281 |
for future, result in batch: |
| 282 |
... |
| 283 |
|
| 284 |
Additionally, for iterative algorithms, you can add more futures into the |
| 285 |
``as_completed`` iterator *during* iteration: |
| 286 |
|
| 287 |
.. code-block:: python |
| 288 |
|
| 289 |
seq = as_completed(futures) |
| 290 |
|
| 291 |
for future in seq: |
| 292 |
y = future.result() |
| 293 |
if condition(y): |
| 294 |
new_future = client.submit(...) |
| 295 |
seq.add(new_future) # add back into the loop |
| 296 |
|
| 297 |
or use ``seq.update(futures)`` to add multiple futures at once. |
| 298 |
|
| 299 |
|
| 300 |
Fire and Forget |
| 301 |
--------------- |
| 302 |
|
| 303 |
.. autosummary:: |
| 304 |
fire_and_forget |
| 305 |
|
| 306 |
Sometimes we don't care about gathering the result of a task, and only care |
| 307 |
about side effects that it might have like writing a result to a file: |
| 308 |
|
| 309 |
.. code-block:: python |
| 310 |
|
| 311 |
>>> a = client.submit(load, filename) |
| 312 |
>>> b = client.submit(process, a) |
| 313 |
>>> c = client.submit(write, b, out_filename) |
| 314 |
|
| 315 |
As noted above, Dask will stop work that doesn't have any active futures. It |
| 316 |
thinks that because no one has a pointer to this data that no one cares. You |
| 317 |
can tell Dask to compute a task anyway, even if there are no active futures, |
| 318 |
using the ``fire_and_forget`` function: |
| 319 |
|
| 320 |
.. code-block:: python |
| 321 |
|
| 322 |
from dask.distributed import fire_and_forget |
| 323 |
|
| 324 |
>>> fire_and_forget(c) |
| 325 |
|
| 326 |
This is particularly useful when a future may go out of scope, for example, as |
| 327 |
part of a function: |
| 328 |
|
| 329 |
.. code-block:: python |
| 330 |
|
| 331 |
def process(filename): |
| 332 |
out_filename = 'out-' + filename |
| 333 |
a = client.submit(load, filename) |
| 334 |
b = client.submit(process, a) |
| 335 |
c = client.submit(write, b, out_filename) |
| 336 |
fire_and_forget(c) |
| 337 |
return # here we lose the reference to c, but that's now ok |
| 338 |
|
| 339 |
for filename in filenames: |
| 340 |
process(filename) |
| 341 |
|
| 342 |
|
| 343 |
Submit task and retrieve results from a different process |
| 344 |
--------------------------------------------------------- |
| 345 |
|
| 346 |
Sometimes we care about retrieving a result but not necessarily from the same process. |
| 347 |
|
| 348 |
.. code-block:: python |
| 349 |
|
| 350 |
from distributed import Variable |
| 351 |
|
| 352 |
var = Variable("my-result") |
| 353 |
fut = client.submit(...) |
| 354 |
var.set(fut) |
| 355 |
|
| 356 |
Using a ``Variable`` instructs dask to remember the result of this task under |
| 357 |
the given name so that it can be retrieved later without having to keep the |
| 358 |
Client alive in the meantime. |
| 359 |
|
| 360 |
.. code-block:: python |
| 361 |
|
| 362 |
var = Variable("my-result") |
| 363 |
fut = var.get() |
| 364 |
result = fut.result() |
| 365 |
|
| 366 |
|
| 367 |
Submit Tasks from Tasks |
| 368 |
----------------------- |
| 369 |
|
| 370 |
.. autosummary:: |
| 371 |
get_client |
| 372 |
rejoin |
| 373 |
secede |
| 374 |
|
| 375 |
*This is an advanced feature and is rarely necessary in the common case.* |
| 376 |
|
| 377 |
Tasks can launch other tasks by getting their own client. This enables complex |
| 378 |
and highly dynamic workloads: |
| 379 |
|
| 380 |
.. code-block:: python |
| 381 |
|
| 382 |
from dask.distributed import get_client |
| 383 |
|
| 384 |
def my_function(x): |
| 385 |
... |
| 386 |
|
| 387 |
# Get locally created client |
| 388 |
client = get_client() |
| 389 |
|
| 390 |
# Do normal client operations, asking cluster for computation |
| 391 |
a = client.submit(...) |
| 392 |
b = client.submit(...) |
| 393 |
a, b = client.gather([a, b]) |
| 394 |
|
| 395 |
return a + b |
| 396 |
|
| 397 |
It also allows you to set up long running tasks that watch other resources like |
| 398 |
sockets or physical sensors: |
| 399 |
|
| 400 |
.. code-block:: python |
| 401 |
|
| 402 |
def monitor(device): |
| 403 |
client = get_client() |
| 404 |
while True: |
| 405 |
data = device.read_data() |
| 406 |
future = client.submit(process, data) |
| 407 |
fire_and_forget(future) |
| 408 |
|
| 409 |
for device in devices: |
| 410 |
fire_and_forget(client.submit(monitor)) |
| 411 |
|
| 412 |
However, each running task takes up a single thread, and so if you launch many |
| 413 |
tasks that launch other tasks, then it is possible to deadlock the system if you |
| 414 |
are not careful. You can call the ``secede`` function from within a task to |
| 415 |
have it remove itself from the dedicated thread pool into an administrative |
| 416 |
thread that does not take up a slot within the Dask worker: |
| 417 |
|
| 418 |
.. code-block:: python |
| 419 |
|
| 420 |
from dask.distributed import get_client, secede |
| 421 |
|
| 422 |
def monitor(device): |
| 423 |
client = get_client() |
| 424 |
secede() # remove this task from the thread pool |
| 425 |
while True: |
| 426 |
data = device.read_data() |
| 427 |
future = client.submit(process, data) |
| 428 |
fire_and_forget(future) |
| 429 |
|
| 430 |
If you intend to do more work in the same thread after waiting on client work, |
| 431 |
you may want to explicitly block until the thread is able to *rejoin* the |
| 432 |
thread pool. This allows some control over the number of threads that are |
| 433 |
created and stops too many threads from being active at once, over-saturating |
| 434 |
your hardware: |
| 435 |
|
| 436 |
.. code-block:: python |
| 437 |
|
| 438 |
def f(n): # assume that this runs as a task |
| 439 |
client = get_client() |
| 440 |
|
| 441 |
secede() # secede while we wait for results to come back |
| 442 |
futures = client.map(func, range(n)) |
| 443 |
results = client.gather(futures) |
| 444 |
|
| 445 |
rejoin() # block until a slot is open in the thread pool |
| 446 |
result = analyze(results) |
| 447 |
return result |
| 448 |
|
| 449 |
|
| 450 |
Alternatively, you can just use the normal ``compute`` function *within* a |
| 451 |
task. This will automatically call ``secede`` and ``rejoin`` appropriately: |
| 452 |
|
| 453 |
.. code-block:: python |
| 454 |
|
| 455 |
def f(name, fn): |
| 456 |
df = dd.read_csv(fn) # note that this is a dask collection |
| 457 |
result = df[df.name == name].count() |
| 458 |
|
| 459 |
# This calls secede |
| 460 |
# Then runs the computation on the cluster (including this worker) |
| 461 |
# Then blocks on rejoin, and finally delivers the answer |
| 462 |
result = result.compute() |
| 463 |
|
| 464 |
return result |
| 465 |
|
| 466 |
|
| 467 |
Coordination Primitives |
| 468 |
----------------------- |
| 469 |
|
| 470 |
.. autosummary:: |
| 471 |
Queue |
| 472 |
Variable |
| 473 |
Lock |
| 474 |
Event |
| 475 |
Semaphore |
| 476 |
Pub |
| 477 |
Sub |
| 478 |
|
| 479 |
.. note: These are advanced features and are rarely necessary in the common case. |
| 480 |
|
| 481 |
Sometimes situations arise where tasks, workers, or clients need to coordinate |
| 482 |
with each other in ways beyond normal task scheduling with futures. In these |
| 483 |
cases Dask provides additional primitives to help in complex situations. |
| 484 |
|
| 485 |
Dask provides distributed versions of coordination primitives like locks, events, |
| 486 |
queues, global variables, and pub-sub systems that, where appropriate, match |
| 487 |
their in-memory counterparts. These can be used to control access to external |
| 488 |
resources, track progress of ongoing computations, or share data in |
| 489 |
side-channels between many workers, clients, and tasks sensibly. |
| 490 |
|
| 491 |
.. raw:: html |
| 492 |
|
| 493 |
<iframe width="560" |
| 494 |
height="315" |
| •495 |
src="https://www.youtube-nocookie.com/embed/Q-Y3BR1u7c0" |
| 496 |
style="margin: 0 auto 20px auto; display: block;" |
| 497 |
frameborder="0" |
| 498 |
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" |
| 499 |
allowfullscreen></iframe> |
| 500 |
|
| 501 |
These features are rarely necessary for common use of Dask. We recommend that |
| 502 |
beginning users stick with using the simpler futures found above (like |
| 503 |
``Client.submit`` and ``Client.gather``) rather than embracing needlessly |
| 504 |
complex techniques. |
| 505 |
|
| 506 |
|
| 507 |
Queues |
| 508 |
~~~~~~ |
| 509 |
|
| 510 |
.. autosummary:: |
| 511 |
Queue |
| 512 |
|
| 513 |
Dask queues follow the API for the standard Python Queue, but now move futures |
| 514 |
or small messages between clients. Queues serialize sensibly and reconnect |
| 515 |
themselves on remote clients if necessary: |
| 516 |
|
| 517 |
.. code-block:: python |
| 518 |
|
| 519 |
from dask.distributed import Queue |
| 520 |
|
| 521 |
def load_and_submit(filename): |
| 522 |
data = load(filename) |
| 523 |
client = get_client() |
| 524 |
future = client.submit(process, data) |
| 525 |
queue.put(future) |
| 526 |
|
| 527 |
client = Client() |
| 528 |
|
| 529 |
queue = Queue() |
| 530 |
|
| 531 |
for filename in filenames: |
| 532 |
future = client.submit(load_and_submit, filename) |
| 533 |
fire_and_forget(future) |
| 534 |
|
| 535 |
while True: |
| 536 |
future = queue.get() |
| 537 |
print(future.result()) |
| 538 |
|
| 539 |
|
| 540 |
Queues can also send small pieces of information, anything that is msgpack |
| 541 |
encodable (ints, strings, bools, lists, dicts, etc.). This can be useful to |
| 542 |
send back small scores or administrative messages: |
| 543 |
|
| 544 |
.. code-block:: python |
| 545 |
|
| 546 |
def func(x): |
| 547 |
try: |
| 548 |
... |
| 549 |
except Exception as e: |
| 550 |
error_queue.put(str(e)) |
| 551 |
|
| 552 |
error_queue = Queue() |
| 553 |
|
| 554 |
Queues are mediated by the central scheduler, and so they are not ideal for |
| 555 |
sending large amounts of data (everything you send will be routed through a |
| 556 |
central point). They are well suited to move around small bits of metadata, or |
| 557 |
futures. These futures may point to much larger pieces of data safely: |
| 558 |
|
| 559 |
.. code-block:: python |
| 560 |
|
| 561 |
>>> x = ... # my large numpy array |
| 562 |
|
| 563 |
# Don't do this! |
| 564 |
>>> q.put(x) |
| 565 |
|
| 566 |
# Do this instead |
| 567 |
>>> future = client.scatter(x) |
| 568 |
>>> q.put(future) |
| 569 |
|
| 570 |
# Or use futures for metadata |
| 571 |
>>> q.put({'status': 'OK', 'stage=': 1234}) |
| 572 |
|
| 573 |
If you're looking to move large amounts of data between workers, then you might |
| 574 |
also want to consider the Pub/Sub system described a few sections below. |
| 575 |
|
| 576 |
Global Variables |
| 577 |
~~~~~~~~~~~~~~~~ |
| 578 |
|
| 579 |
.. autosummary:: |
| 580 |
Variable |
| 581 |
|
| 582 |
Variables are like Queues in that they communicate futures and small data |
| 583 |
between clients. However, variables hold only a single value. You can get or |
| 584 |
set that value at any time: |
| 585 |
|
| 586 |
.. code-block:: python |
| 587 |
|
| 588 |
>>> var = Variable('stopping-criterion') |
| 589 |
>>> var.set(False) |
| 590 |
|
| 591 |
>>> var.get() |
| 592 |
False |
| 593 |
|
| 594 |
This is often used to signal stopping criteria or current parameters |
| 595 |
between clients. |
| 596 |
|
| 597 |
If you want to share large pieces of information, then scatter the data first: |
| 598 |
|
| 599 |
.. code-block:: python |
| 600 |
|
| 601 |
>>> parameters = np.array(...) |
| 602 |
>>> future = client.scatter(parameters) |
| 603 |
>>> var.set(future) |
| 604 |
|
| 605 |
|
| 606 |
Locks |
| 607 |
~~~~~ |
| 608 |
|
| 609 |
.. autosummary:: |
| 610 |
Lock |
| 611 |
|
| 612 |
You can also hold onto cluster-wide locks using the ``Lock`` object. |
| 613 |
Dask Locks have the same API as normal ``threading.Lock`` objects, except that |
| 614 |
they work across the cluster: |
| 615 |
|
| 616 |
.. code-block:: python |
| 617 |
|
| 618 |
from dask.distributed import Lock |
| 619 |
lock = Lock() |
| 620 |
|
| 621 |
with lock: |
| 622 |
# access protected resource |
| 623 |
|
| 624 |
You can manage several locks at the same time. Lock can either be given a |
| 625 |
consistent name or you can pass the lock object around itself. |
| 626 |
|
| 627 |
Using a consistent name is convenient when you want to lock some known named resource: |
| 628 |
|
| 629 |
.. code-block:: python |
| 630 |
|
| 631 |
from dask.distributed import Lock |
| 632 |
|
| 633 |
def load(fn): |
| 634 |
with Lock('the-production-database'): |
| 635 |
# read data from filename using some sensitive source |
| 636 |
return ... |
| 637 |
|
| 638 |
futures = client.map(load, filenames) |
| 639 |
|
| 640 |
Passing around a lock works as well and is easier when you want to create short-term |
| 641 |
locks for a particular situation: |
| 642 |
|
| 643 |
.. code-block:: python |
| 644 |
|
| 645 |
from dask.distributed import Lock |
| 646 |
lock = Lock() |
| 647 |
|
| 648 |
def load(fn, lock=None): |
| 649 |
with lock: |
| 650 |
# read data from filename using some sensitive source |
| 651 |
return ... |
| 652 |
|
| 653 |
futures = client.map(load, filenames, lock=lock) |
| 654 |
|
| 655 |
This can be useful if you want to control concurrent access to some external |
| 656 |
resource like a database or un-thread-safe library. |
| 657 |
|
| 658 |
|
| 659 |
Events |
| 660 |
~~~~~~ |
| 661 |
|
| 662 |
.. autosummary:: |
| 663 |
Event |
| 664 |
|
| 665 |
Dask Events mimic ``asyncio.Event`` objects, but on a cluster scope. |
| 666 |
They hold a single flag which can be set or cleared. |
| 667 |
Clients can wait until the event flag is set. |
| 668 |
Different from a ``Lock``, every client can set or clear the flag and there |
| 669 |
is no "ownership" of an event. |
| 670 |
|
| 671 |
You can use events to e.g. synchronize multiple clients: |
| 672 |
|
| 673 |
.. code-block:: python |
| 674 |
|
| 675 |
# One one client |
| 676 |
from dask.distributed import Event |
| 677 |
|
| 678 |
event = Event("my-event-1") |
| 679 |
event.wait() |
| 680 |
|
| 681 |
The call to wait will block until the event is set, e.g. in another client |
| 682 |
|
| 683 |
.. code-block:: python |
| 684 |
|
| 685 |
# In another client |
| 686 |
from dask.distributed import Event |
| 687 |
|
| 688 |
event = Event("my-event-1") |
| 689 |
|
| 690 |
# do some work |
| 691 |
|
| 692 |
event.set() |
| 693 |
|
| 694 |
Events can be set, cleared and waited on multiple times. |
| 695 |
Every waiter referencing the same event name will be notified on event set |
| 696 |
(and not only the first one as in the case of a lock): |
| 697 |
|
| 698 |
.. code-block:: python |
| 699 |
|
| 700 |
from dask.distributed import Event |
| 701 |
|
| 702 |
def wait_for_event(x): |
| 703 |
event = Event("my-event") |
| 704 |
|
| 705 |
event.wait() |
| 706 |
# at this point, all function calls |
| 707 |
# are in sync once the event is set |
| 708 |
|
| 709 |
futures = client.map(wait_for_event, range(10)) |
| 710 |
|
| 711 |
Event("my-event").set() |
| 712 |
client.gather(futures) |
| 713 |
|
| 714 |
|
| 715 |
Semaphore |
| 716 |
~~~~~~~~~ |
| 717 |
|
| 718 |
.. autosummary:: |
| 719 |
Semaphore |
| 720 |
|
| 721 |
Similar to the single-valued ``Lock`` it is also possible to use a cluster-wide |
| 722 |
semaphore to coordinate and limit access to a sensitive resource like a |
| 723 |
database. |
| 724 |
|
| 725 |
.. code-block:: python |
| 726 |
|
| 727 |
from dask.distributed import Semaphore |
| 728 |
|
| 729 |
sem = Semaphore(max_leases=2, name="database") |
| 730 |
|
| 731 |
def access_limited(val, sem): |
| 732 |
with sem: |
| 733 |
# Interact with the DB |
| 734 |
return |
| 735 |
|
| 736 |
futures = client.map(access_limited, range(10), sem=sem) |
| 737 |
client.gather(futures) |
| 738 |
sem.close() |
| 739 |
|
| 740 |
|
| 741 |
Publish-Subscribe |
| 742 |
~~~~~~~~~~~~~~~~~ |
| 743 |
|
| 744 |
.. autosummary:: |
| 745 |
Pub |
| 746 |
Sub |
| 747 |
|
| 748 |
Dask implements the `Publish Subscribe pattern <https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern>`_, |
| 749 |
providing an additional channel of communication between ongoing tasks. |
| 750 |
|
| 751 |
|
| 752 |
Actors |
| 753 |
------ |
| 754 |
|
| 755 |
Actors allow workers to manage rapidly changing state without coordinating with |
| 756 |
the central scheduler. This has the advantage of reducing latency |
| 757 |
(worker-to-worker roundtrip latency is around 1ms), reducing pressure on the |
| 758 |
centralized scheduler (workers can coordinate actors entirely among each other), |
| 759 |
and also enabling workflows that require stateful or in-place memory |
| 760 |
manipulation. |
| 761 |
|
| 762 |
However, these benefits come at a cost. The scheduler is unaware of actors and |
| 763 |
so they don't benefit from diagnostics, load balancing, or resilience. Once an |
| 764 |
actor is running on a worker it is forever tied to that worker. If that worker |
| 765 |
becomes overburdened or dies, then there is no opportunity to recover the |
| 766 |
workload. |
| 767 |
|
| 768 |
*Because Actors avoid the central scheduler they can be high-performing, but not resilient.* |
| 769 |
|
| 770 |
Example: Counter |
| 771 |
~~~~~~~~~~~~~~~~ |
| 772 |
|
| 773 |
An actor is a class containing both state and methods that is submitted to a |
| 774 |
worker: |
| 775 |
|
| 776 |
.. code-block:: python |
| 777 |
|
| 778 |
class Counter: |
| 779 |
n = 0 |
| 780 |
|
| 781 |
def __init__(self): |
| 782 |
self.n = 0 |
| 783 |
|
| 784 |
def increment(self): |
| 785 |
self.n += 1 |
| 786 |
return self.n |
| 787 |
|
| 788 |
from dask.distributed import Client |
| 789 |
client = Client() |
| 790 |
|
| 791 |
future = client.submit(Counter, actor=True) |
| 792 |
counter = future.result() |
| 793 |
|
| 794 |
>>> counter |
| 795 |
<Actor: Counter, key=Counter-afa1cdfb6b4761e616fa2cfab42398c8> |
| 796 |
|
| 797 |
Method calls on this object produce ``ActorFutures``, which are similar to |
| 798 |
normal Futures, but interact only with the worker holding the Actor: |
| 799 |
|
| 800 |
.. code-block:: python |
| 801 |
|
| 802 |
>>> future = counter.increment() |
| 803 |
>>> future |
| 804 |
<ActorFuture> |
| 805 |
|
| 806 |
>>> future.result() |
| 807 |
1 |
| 808 |
|
| 809 |
Attribute access is synchronous and blocking: |
| 810 |
|
| 811 |
.. code-block:: python |
| 812 |
|
| 813 |
>>> counter.n |
| 814 |
1 |
| 815 |
|
| 816 |
|
| 817 |
Example: Parameter Server |
| 818 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 819 |
|
| 820 |
This example will perform the following minimization with a parameter server: |
| 821 |
|
| 822 |
.. math:: |
| 823 |
|
| 824 |
\min_{p\in\mathbb{R}^{1000}} \sum_{i=1}^{1000} (p_i - 1)^2 |
| 825 |
|
| 826 |
This is a simple minimization that will serve as an illustrative example. |
| 827 |
|
| 828 |
The Dask Actor will serve as the parameter server that will hold the model. |
| 829 |
The client will calculate the gradient of the loss function above. |
| 830 |
|
| 831 |
.. code-block:: python |
| 832 |
|
| 833 |
import numpy as np |
| 834 |
|
| 835 |
from dask.distributed import Client |
| 836 |
client = Client(processes=False) |
| 837 |
|
| 838 |
class ParameterServer: |
| 839 |
def __init__(self): |
| 840 |
self.data = dict() |
| 841 |
|
| 842 |
def put(self, key, value): |
| 843 |
self.data[key] = value |
| 844 |
|
| 845 |
def get(self, key): |
| 846 |
return self.data[key] |
| 847 |
|
| 848 |
def train(params, lr=0.1): |
| 849 |
grad = 2 * (params - 1) # gradient of (params - 1)**2 |
| 850 |
new_params = params - lr * grad |
| 851 |
return new_params |
| 852 |
|
| 853 |
ps_future = client.submit(ParameterServer, actor=True) |
| 854 |
ps = ps_future.result() |
| 855 |
|
| 856 |
ps.put('parameters', np.random.default_rng().random(1000)) |
| 857 |
for k in range(20): |
| 858 |
params = ps.get('parameters').result() |
| 859 |
new_params = train(params) |
| 860 |
ps.put('parameters', new_params) |
| 861 |
print(new_params.mean()) |
| 862 |
# k=0: "0.5988202981316124" |
| 863 |
# k=10: "0.9569236575164062" |
| 864 |
|
| 865 |
This example works, and the loss function is minimized. The (simple) equation |
| 866 |
above is minimize, so each :math:`p_i` converges to 1. If desired, this example |
| 867 |
could be adapted to machine learning with a more complex function to minimize. |
| 868 |
|
| 869 |
Asynchronous Operation |
| 870 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 871 |
|
| 872 |
All operations that require talking to the remote worker are awaitable: |
| 873 |
|
| 874 |
.. code-block:: python |
| 875 |
|
| 876 |
async def f(): |
| 877 |
future = client.submit(Counter, actor=True) |
| 878 |
counter = await future # gather actor object locally |
| 879 |
|
| 880 |
counter.increment() # send off a request asynchronously |
| 881 |
await counter.increment() # or wait until it was received |
| 882 |
|
| 883 |
n = await counter.n # attribute access also must be awaited |
| 884 |
|
| 885 |
Generally, all I/O operations that trigger computations (e.g. ``to_parquet``) should be done using the ``compute=False`` |
| 886 |
parameter to avoid asynchronous blocking: |
| 887 |
|
| 888 |
.. code-block:: python |
| 889 |
|
| 890 |
await client.compute(ddf.to_parquet('/tmp/some.parquet', compute=False)) |
| 891 |
|
| 892 |
API |
| 893 |
--- |
| 894 |
|
| 895 |
**Client** |
| 896 |
|
| 897 |
.. autosummary:: |
| 898 |
Client |
| 899 |
Client.cancel |
| 900 |
Client.compute |
| 901 |
Client.gather |
| 902 |
Client.get |
| 903 |
Client.get_dataset |
| 904 |
Client.get_executor |
| 905 |
Client.has_what |
| 906 |
Client.list_datasets |
| 907 |
Client.map |
| 908 |
Client.ncores |
| 909 |
Client.persist |
| 910 |
Client.profile |
| 911 |
Client.publish_dataset |
| 912 |
Client.rebalance |
| 913 |
Client.replicate |
| 914 |
Client.restart |
| 915 |
Client.run |
| 916 |
Client.run_on_scheduler |
| 917 |
Client.scatter |
| 918 |
Client.shutdown |
| 919 |
Client.scheduler_info |
| 920 |
Client.submit |
| 921 |
Client.unpublish_dataset |
| 922 |
Client.upload_file |
| 923 |
Client.who_has |
| 924 |
|
| 925 |
**Future** |
| 926 |
|
| 927 |
.. autosummary:: |
| 928 |
Future |
| 929 |
Future.add_done_callback |
| 930 |
Future.cancel |
| 931 |
Future.cancelled |
| 932 |
Future.done |
| 933 |
Future.exception |
| 934 |
Future.result |
| 935 |
Future.traceback |
| 936 |
|
| 937 |
**Functions** |
| 938 |
|
| 939 |
.. autosummary:: |
| 940 |
as_completed |
| 941 |
fire_and_forget |
| 942 |
get_client |
| 943 |
secede |
| 944 |
rejoin |
| 945 |
wait |
| 946 |
print |
| 947 |
warn |
| 948 |
|
| 949 |
.. autofunction:: as_completed |
| 950 |
.. autofunction:: fire_and_forget |
| 951 |
.. autofunction:: get_client |
| 952 |
.. autofunction:: secede |
| 953 |
.. autofunction:: rejoin |
| 954 |
.. autofunction:: wait |
| 955 |
.. autofunction:: print |
| 956 |
.. autofunction:: warn |
| 957 |
|
| 958 |
.. autoclass:: Client |
| 959 |
:members: |
| 960 |
|
| 961 |
.. autoclass:: Future |
| 962 |
:members: |
| 963 |
|
| 964 |
.. autoclass:: Queue |
| 965 |
:members: |
| 966 |
|
| 967 |
.. autoclass:: Variable |
| 968 |
:members: |
| 969 |
|
| 970 |
.. autoclass:: Lock |
| 971 |
:members: |
| 972 |
|
| 973 |
.. autoclass:: Event |
| 974 |
:members: |
| 975 |
|
| 976 |
.. autoclass:: Semaphore |
| 977 |
:members: |
| 978 |
|
| 979 |
.. autoclass:: Pub |
| 980 |
:members: |
| 981 |
|
| 982 |
.. autoclass:: Sub |
| 983 |
:members: |