<jupyter_start><jupyter_text>Real-Time Workloads with Dask Futures=====================================<img src="http://dask.readthedocs.io/en/latest/_images/dask_horizontal.svg"      width="30%"      align=right     alt="Dask logo">Dask futures provide fine-grained real-time execution for custom situations.  This is the foundation for other APIs like Dask arrays and dataframes.  Start Dask ClientUnlike for arrays and dataframes, you need the Dask client to use the Futures interface.  Additionally the client provides a dashboard which is useful to gain insight on the computation.The link to the dashboard will become visible when you create the client below.  We recommend having it open on one side of your screen while using your notebook on the other side.  This can take some effort to arrange your windows, but seeing them both at the same is very useful when learning.<jupyter_code>from dask.distributed import Client, progress
client = Client()
client<jupyter_output><empty_output><jupyter_text>Create simple functionsThese functions do simple operations like add two numbers together, but they sleep for a random amount of time to simulate real work.<jupyter_code>import time
import random

def inc(x):
    time.sleep(random.random())
    return x + 1

def double(x):
    time.sleep(random.random())
    return 2 * x
    
def add(x, y):
    time.sleep(random.random())
    return x + y<jupyter_output><empty_output><jupyter_text>We can run them locally<jupyter_code>inc(1)<jupyter_output><empty_output><jupyter_text>Or we can submit them to run remotely with Dask.  This immediately returns a future that points to the ongoing computation, and eventually to the stored result.<jupyter_code>future = client.submit(inc, 1)  # returns immediately with pending future
future<jupyter_output><empty_output><jupyter_text>If you wait a second, and then check on the future again, you'll see that it has finished.<jupyter_code>future  # scheduler and client talk constantly<jupyter_output><empty_output><jupyter_text>You can block on the computation and gather the result with the `.result()` method.<jupyter_code>future.result()<jupyter_output><empty_output><jupyter_text>Chain dependenciesYou can submit tasks on other futures.  This will create a dependency between the inputs and outputs.  Dask will track the execution of all tasks, ensuring that downstream tasks are run at the proper time and place and with the proper data.<jupyter_code>x = client.submit(inc, 1)
y = client.submit(double, 2)
z = client.submit(add, x, y)
z
z.result()<jupyter_output><empty_output><jupyter_text>Note that we never blocked on `x` or `y` nor did we ever have to move their data back to our notebook.  Submit many tasksSo we've learned how to run Python functions remotely.  This becomes useful when we add two things:1.  We can submit thousands of tasks per second2.  Tasks can depend on each other by consuming futures as inputsWe submit many tasks that depend on each other in a normal Python for loop<jupyter_code>%%time
zs = []
for i in range(256):
    x = client.submit(inc, i)     # x = inc(i)
    y = client.submit(double, x)  # y = inc(x)
    z = client.submit(add, x, y)  # z = inc(y)
    zs.append(z)
    
total = client.submit(sum, zs)<jupyter_output><empty_output><jupyter_text>To make this go faster, add an additional workers with more cores (although we're still only working on our local machine, this is more practical when using an actual cluster)  Custom computation: Tree summationAs an example of a non-trivial algorithm, consider the classic tree reduction.  We accomplish this with a nested for loop and a bit of normal Python logic.```finish           total             single output    ^          /        \    |        c1          c2        neighbors merge    |       /  \        /  \    |     b1    b2    b3    b4     neighbors merge    ^    / \   / \   / \   / \start   a1 a2 a3 a4 a5 a6 a7 a8    many inputs```<jupyter_code>L = zs
while len(L) > 1:
    new_L = []
    for i in range(0, len(L), 2):
        future = client.submit(add, L[i], L[i + 1])  # add neighbors
        new_L.append(future)
    L = new_L                                   # swap old list for new<jupyter_output><empty_output><jupyter_text>If you're watching the [dashboard's status page](../proxy/8787/status) then you may want to note two things:1.  The red bars are for inter-worker communication.  They happen as different workers need to combine their intermediate values2.  There is lots of parallelism at the beginning but less towards the end as we reach the top of the tree where there is less work to do.Alternatively you may want to navigate to the [dashboard's graph page](../proxy/8787/graph) and then run the cell above again.  You will be able to see the task graph evolve during the computation. Build a computation dynamically-------------------------------In the examples above we explicitly specify the task graph ahead of time.  We know for example that the first two futures in the list `L` will be added together.  Sometimes this isn't always best though, sometimes you want to dynamically define a computation as it is happening.  For example we might want to sum up these values based on whichever futures show up first, rather than the order in which they were placed in the list to start with.For this, we can use operations like [as_completed](http://dask.pydata.org/en/latest/futures.htmldistributed.as_completed).We recommend watching the dashboard's graph page when running this computation.  You should see the graph construct itself during execution.<jupyter_code>del future, L, new_L, total, zs  # clear out some old work
from dask.distributed import as_completed

zs = client.map(inc, range(500), priority=-1)
seq = as_completed(zs)

while seq.count() > 2:  # at least two futures left
    a = next(seq)
    b = next(seq)
    new = client.submit(add, a, b)  # add them together
    seq.add(new)                    # add new future back into loop<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08179243711477595, 'fraction_numerical': 0.007662835249042145, 'mean_word_length': 3.7462450592885377, 'pattern_counts': {'":': 0, '<': 42, '<?xml version=': 0, '>': 44, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '459636', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1712, 'n_tokens_neox': 1649, 'n_words': 746, 'path': 'notebook/examples/02-custom-futures.ipynb', 'repo_name': 'rpanai/dask-docker', 'size': '6003'}