Live Notebook

You can run this notebook in a live session Binder or view it on Github.

Handle Evolving Workflows

For some workflows we don’t know the extent of the computation at the outset. We need to do some computation in order to figure out the rest of the computation that we need to do. The computation grows and evolves as we do more work.

As an example, consider a situuation where you need to read many files and then based on the contents of those files, fire off additional work. You would like to read the files in parallel, and then then within each file expose more parallelism.

This example goes through three ways to handle this situation using Dask Futures

  1. Using as_completed

  2. Using async/await

  3. Launching tasks from tasks

But first, lets run our code sequentially.

0: Sequential code

[1]:
filenames = ["file.{}.txt".format(i) for i in range(10)]

filenames[:3]
[1]:
['file.0.txt', 'file.1.txt', 'file.2.txt']
[2]:
import random, time


def parse_file(fn: str) -> list:
    """ Returns a list work items of unknown length """
    time.sleep(random.random())
    return [random.random() for _ in range(random.randint(1, 10))]

def process_item(x: float):
    """ Process each work item """
    time.sleep(random.random() / 4)
    return x + 1
[3]:
%%time

# This takes around 10-20s

results = []

for fn in filenames:
    L = parse_file(fn)
    for x in L:
        out = process_item(x)
        results.append(out)
CPU times: user 4.74 ms, sys: 657 µs, total: 5.39 ms
Wall time: 9.27 s

Start Dask Client

We’ll need a Dask client in order to manage dynamic workloads

[4]:
from dask.distributed import Client

client = Client(processes=False, n_workers=1, threads_per_worker=6)
client
[4]:

Client

Cluster

  • Workers: 1
  • Cores: 6
  • Memory: 7.84 GB

1: Use as_completed

The as_completed iterator lets us handle futures as they complete. We can then submit more data on the fly.

  • We submit a task for each of our filenames

  • We also compute the length of each of the returned lists

  • As those lengths return, we submit off a new task to get each item of that list. We do this at higher priority, so that we process existing data before we collect new data.

  • We wait on all of the returned results

[5]:
%%time

from dask.distributed import as_completed
import operator

lists = client.map(parse_file, filenames, pure=False)
lengths = client.map(len, lists)

mapping = dict(zip(lengths, lists))

futures = []

for future in as_completed(lengths):
    n = future.result()
    L = mapping[future]
    for i in range(n):
        new = client.submit(operator.getitem, L, i, priority=1)
        new = client.submit(process_item, new, priority=1)
        futures.append(new)

client.gather(futures)
CPU times: user 487 ms, sys: 42.4 ms, total: 529 ms
Wall time: 2.53 s
[5]:
[1.861617265655,
 1.1181946337951234,
 1.4634800028430521,
 1.5518843875570107,
 1.9997497645885376,
 1.5974950023547794,
 1.6013729898931535,
 1.2913174166465466,
 1.1088542306776505,
 1.6803368014102533,
 1.3931724336746103,
 1.4505171815262123,
 1.514662661569599,
 1.3007653916970479,
 1.4484428632457367,
 1.7837556132706194,
 1.4286051508685023,
 1.4168488548869353,
 1.555351893036611,
 1.0434129695612357,
 1.7869621314967348,
 1.1355354414221361,
 1.0836517404223691,
 1.6956244054050695,
 1.119132898026768,
 1.3415492197772934,
 1.547403439797637,
 1.8172647985875159,
 1.7560389000590988,
 1.4660854986453187,
 1.9754919665510313,
 1.098763167504297,
 1.6950165329479652,
 1.2323947894639518,
 1.069429285321855,
 1.3827208806088573,
 1.8807991374675217,
 1.9334069792133948,
 1.6917721889180983,
 1.2003520781890413,
 1.6690518305154995,
 1.6525955476527585,
 1.5245360052092969,
 1.2217772087296637,
 1.575223781123822,
 1.3884054646130717,
 1.1829765966897938,
 1.6236121716339622,
 1.8417562774035976,
 1.4343578707721565,
 1.4107534504929928,
 1.2767907100186937,
 1.475431984183905,
 1.8293968518752504,
 1.9642532337535976,
 1.3372845089090184,
 1.4565861539376543,
 1.970186797562918,
 1.5604012566876495,
 1.5867805855100117]

2: Use async/await to handle each locally

We can also handle the concurrency here within our local process. This requires you to understand async/await syntax, but is generally powerful and arguably simpler than the as_completed approach above.

[6]:
import asyncio

async def f(fn):
    """ Handle the lifecycle of a single file """
    future = client.submit(parse_file, fn, pure=False)
    length_future = client.submit(len, future)
    length = await length_future

    futures = [client.submit(operator.getitem, future, i, priority=10)
               for i in range(length)]
    futures = client.map(process_item, futures, priority=10)
    return futures

async def run_all(filenames):
    list_of_list_of_futures = await asyncio.gather(*[f(fn) for fn in filenames])
    futures = sum(list_of_list_of_futures, [])
    return await client.gather(futures)

We now need to run this function in the same event loop as our client is running. If we had started our client asynchronously, then we could have done this:

client = await Client(asynchronous=True)

await run_all(filenames)

However, because we started our client without the asynchronous=True flag the event loop is actually running in a separate thread, so we’ll have to ask the client to run this for us.

[7]:
client.sync(run_all, filenames)
[7]:
[1.6083388373679266,
 1.1016716728755223,
 1.3132611896260298,
 1.3328026368323713,
 1.4257314026696624,
 1.1936159314185328,
 1.8897127750101648,
 1.2354297363514006,
 1.8802068482717487,
 1.5320143385455136,
 1.4398403977908583,
 1.2339195923018265,
 1.6019302889464944,
 1.81639625459966,
 1.179275630413414,
 1.3831144753690219,
 1.9249483832418606,
 1.35010066394407,
 1.331241906302138,
 1.1123098114039742,
 1.4456616504444075,
 1.133217094289558,
 1.6531892013279592,
 1.250252490186578,
 1.1436760688690644,
 1.2589645401031313,
 1.2584280667442231,
 1.490089461826648,
 1.56005796922964,
 1.8357666650309261,
 1.6356552038355172,
 1.2617091115534778,
 1.368040643599839,
 1.5646271521501522,
 1.01074301901736,
 1.210808395167602,
 1.318759817882991,
 1.006667069147979,
 1.8989847270493787,
 1.4319656511895353,
 1.1862224919734516,
 1.9770508765076107,
 1.9543755989804068,
 1.617042459399057,
 1.6129320020893794,
 1.7180123765662008]

3: Submit tasks from tasks

We can also submit tasks that themselves submit more tasks. See documentation here.

[8]:
%%time

from dask.distributed import get_client, secede, rejoin

def f(fn):
    L = parse_file(fn)
    client = get_client()

    futures = client.map(process_item, L, priority=10)
    secede()
    results = client.gather(futures)
    rejoin()
    return results

futures = client.map(f, filenames, pure=False)
results = client.gather(futures)
CPU times: user 357 ms, sys: 24.9 ms, total: 382 ms
Wall time: 2.51 s