Distributed Computing with dask

In this portion of the course, we’ll explore distributed computing with a Python library called dask.

Dask is a library designed to help facilitate (a) the manipulation of very large datasets, and (b) the distribution of computation across lots of cores or physical computers. It is very similar to Apache Spark in the functionality it provides, but it is tightly integrated into numpy and pandas, making it much easier to learn than spark for users of those libraries.

What can dask do for me?

To get a sense of why dask is so nice, let’s begin with a demonstration. Suppose I have a pretty big dataset (say, an 100GB CSV of all drug shipments in the United States from 2006 to 2014). This data is too large for me to load into ram on my laptop directly, so if I were to work with it on my own, I’d do so by chunking the data by hand. But using dask, I can do the following:

[1]:
# Standard setups
import pandas as pd
import os

os.chdir("/users/nce8/dropbox/MIDS_Data_Prep/arcos")

[2]:
# Here we start up a dask cluster.
# This creates a set of "workers".
# In this case, these workers are all on
# my computer, but if we wanted to connect
# to a cluster, we'd just past an IP address
# to `Client()`.

# You can see how many cores your computer
# has using `os.cpu_count()` in the `os` library.

# Note you may get some warnings about
# Python wanting to accept incoming
# connections from your firewall.
# You need to approve those
# so workers can talk to one another.

import os

print(f"I have {os.cpu_count()} logical cores.")

from dask.distributed import Client

client = Client()
client

I have 10 logical cores.
[2]:

Client

Client-56aae5aa-772b-11ed-96cb-f623161a15eb

Connection method: Cluster object Cluster type: distributed.LocalCluster
Dashboard: http://127.0.0.1:8787/status

Cluster Info

[3]:
# ARCOS Data on all drug shipments in US from 2006 to 2014
# I was unable to get this data
# into my repo, but you can download it here:
# https://www.dropbox.com/s/oiv3k3sfwiviup5/all_prescriptions.csv?dl=0

# Note that while pandas can read compressed files like this .tsv.gz,
# file, dask cannot. So if you want to do this at home,
# you have to decompress the data.

import dask.dataframe as dd

df = dd.read_csv(
    "all_prescriptions.csv",
    dtype={
        "ACTION_INDICATOR": "object",
        "ORDER_FORM_NO": "object",
        "REPORTER_ADDRESS2": "object",
        "REPORTER_ADDL_CO_INFO": "object",
        "BUYER_ADDL_CO_INFO": "object",
        "BUYER_ADDRESS2": "object",
        "NDC_NO": "object",
        "UNIT": "object",
        "STRENGTH": "float64",
        "BUYER_ZIP": "object",
        "DRUG_CODE": "object",
        "MME_Conversion_Factor": "object",
        "QUANTITY": "object",
        "TRANSACTION_DATE": "float64",
        "TRANSACTION_ID": "float64",
        "dos_str": "object",
    },
)

[4]:
# Extract year
df["date"] = dd.to_datetime(df.TRANSACTION_DATE, format="%m%d%Y")
df["year"] = df.date.dt.year

# Make an estimate of total morphine equivalent shipments
df["morphine_equivalent_g"] = (df["CALC_BASE_WT_IN_GM"]) * df["MME_Conversion_Factor"]

# Drop extra vars
df = df[["year", "morphine_equivalent_g", "BUYER_STATE", "BUYER_COUNTY"]]

# Collapse to total shipments to each county in each year.
collapsed = df.groupby(
    ["year", "BUYER_STATE", "BUYER_COUNTY"]
).morphine_equivalent_g.sum()
collapsed

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/array_ops.py:165, in _na_arithmetic_op(left, right, op, is_cmp)
    164 try:
--> 165     result = func(left, right)
    166 except TypeError:

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/computation/expressions.py:241, in evaluate(op, a, b, use_numexpr)
    239     if use_numexpr:
    240         # error: "None" not callable
--> 241         return _evaluate(op, op_str, a, b)  # type: ignore[misc]
    242 return _evaluate_standard(op, op_str, a, b)

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/computation/expressions.py:70, in _evaluate_standard(op, op_str, a, b)
     69     _store_test_result(False)
---> 70 return op(a, b)

TypeError: can't multiply sequence by non-int of type 'float'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/dataframe/utils.py:195, in raise_on_meta_error(funcname, udf)
    194 try:
--> 195     yield
    196 except Exception as e:

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/dataframe/core.py:6239, in elemwise(op, meta, out, transform_divisions, *args, **kwargs)
   6238     with raise_on_meta_error(funcname(op)):
-> 6239         meta = partial_by_order(*parts, function=op, other=other)
   6241 result = new_dd_object(graph, _name, meta, divisions)

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/utils.py:1325, in partial_by_order(*args, **kwargs)
   1324     args2.insert(i, arg)
-> 1325 return function(*args2, **kwargs)

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/common.py:72, in _unpack_zerodim_and_defer.<locals>.new_method(self, other)
     70 other = item_from_zerodim(other)
---> 72 return method(self, other)

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/arraylike.py:118, in OpsMixin.__mul__(self, other)
    116 @unpack_zerodim_and_defer("__mul__")
    117 def __mul__(self, other):
--> 118     return self._arith_method(other, operator.mul)

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/series.py:6259, in Series._arith_method(self, other, op)
   6258 self, other = ops.align_method_SERIES(self, other)
-> 6259 return base.IndexOpsMixin._arith_method(self, other, op)

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/base.py:1325, in IndexOpsMixin._arith_method(self, other, op)
   1324 with np.errstate(all="ignore"):
-> 1325     result = ops.arithmetic_op(lvalues, rvalues, op)
   1327 return self._construct_result(result, name=res_name)

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/array_ops.py:226, in arithmetic_op(left, right, op)
    224     # error: Argument 1 to "_na_arithmetic_op" has incompatible type
    225     # "Union[ExtensionArray, ndarray[Any, Any]]"; expected "ndarray[Any, Any]"
--> 226     res_values = _na_arithmetic_op(left, right, op)  # type: ignore[arg-type]
    228 return res_values

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/array_ops.py:172, in _na_arithmetic_op(left, right, op, is_cmp)
    167 if not is_cmp and (is_object_dtype(left.dtype) or is_object_dtype(right)):
    168     # For object dtype, fallback to a masked operation (only operating
    169     #  on the non-missing values)
    170     # Don't do this for comparisons, as that will handle complex numbers
    171     #  incorrectly, see GH#32047
--> 172     result = _masked_arith_op(left, right, op)
    173 else:

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/array_ops.py:110, in _masked_arith_op(x, y, op)
    109     if mask.any():
--> 110         result[mask] = op(xrav[mask], yrav[mask])
    112 else:

TypeError: can't multiply sequence by non-int of type 'float'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
Cell In [4], line 6
      3 df["year"] = df.date.dt.year
      5 # Make an estimate of total morphine equivalent shipments
----> 6 df["morphine_equivalent_g"] = (df["CALC_BASE_WT_IN_GM"]) * df["MME_Conversion_Factor"]
      8 # Drop extra vars
      9 df = df[["year", "morphine_equivalent_g", "BUYER_STATE", "BUYER_COUNTY"]]

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/dataframe/core.py:1784, in _Frame._get_binary_operator.<locals>.<lambda>(self, other)
   1782     return lambda self, other: elemwise(op, other, self)
   1783 else:
-> 1784     return lambda self, other: elemwise(op, self, other)

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/dataframe/core.py:6238, in elemwise(op, meta, out, transform_divisions, *args, **kwargs)
   6229     # For broadcastable series, use no rows.
   6230     parts = [
   6231         d._meta
   6232         if _is_broadcastable(d)
   (...)
   6236         for d in dasks
   6237     ]
-> 6238     with raise_on_meta_error(funcname(op)):
   6239         meta = partial_by_order(*parts, function=op, other=other)
   6241 result = new_dd_object(graph, _name, meta, divisions)

File ~/opt/miniconda3/envs/dask/lib/python3.10/contextlib.py:153, in _GeneratorContextManager.__exit__(self, typ, value, traceback)
    151     value = typ()
    152 try:
--> 153     self.gen.throw(typ, value, traceback)
    154 except StopIteration as exc:
    155     # Suppress StopIteration *unless* it's the same exception that
    156     # was passed to throw().  This prevents a StopIteration
    157     # raised inside the "with" statement from being suppressed.
    158     return exc is not value

File ~/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/dataframe/utils.py:216, in raise_on_meta_error(funcname, udf)
    207 msg += (
    208     "Original error is below:\n"
    209     "------------------------\n"
   (...)
    213     "{2}"
    214 )
    215 msg = msg.format(f" in `{funcname}`" if funcname else "", repr(e), tb)
--> 216 raise ValueError(msg) from e

ValueError: Metadata inference failed in `mul`.

Original error is below:
------------------------
TypeError("can't multiply sequence by non-int of type 'float'")

Traceback:
---------
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/dataframe/utils.py", line 195, in raise_on_meta_error
    yield
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/dataframe/core.py", line 6239, in elemwise
    meta = partial_by_order(*parts, function=op, other=other)
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/dask/utils.py", line 1325, in partial_by_order
    return function(*args2, **kwargs)
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/common.py", line 72, in new_method
    return method(self, other)
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/arraylike.py", line 118, in __mul__
    return self._arith_method(other, operator.mul)
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/series.py", line 6259, in _arith_method
    return base.IndexOpsMixin._arith_method(self, other, op)
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/base.py", line 1325, in _arith_method
    result = ops.arithmetic_op(lvalues, rvalues, op)
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/array_ops.py", line 226, in arithmetic_op
    res_values = _na_arithmetic_op(left, right, op)  # type: ignore[arg-type]
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/array_ops.py", line 172, in _na_arithmetic_op
    result = _masked_arith_op(left, right, op)
  File "/Users/nce8/opt/miniconda3/envs/dask/lib/python3.10/site-packages/pandas/core/ops/array_ops.py", line 110, in _masked_arith_op
    result[mask] = op(xrav[mask], yrav[mask])

[8]:
%%time
final = collapsed.compute()
final.sample(10)

Voila! I get back my thinned-out dataset with the new variable I wanted, all while never using more than about 2GB of RAM at any point.

So let’s discuss what just happened.

  1. First, when I ran Client(), dask started up a set of 10 new python processes on my computer (called “workers”) it could call on for help. These are fully independent agents that could be running on different machines in a true cluster (though in this case, they’re all on my laptop).

  2. It then collected all the instructions I gave it for reading in the file, generating a new column, deleting extra columns, and grouping. But it didn’t actually execute any code. That’s why when I typed collapsed, what I got back was a dataframe with structure but no data—dask had figured out roughly what the result of my commands would look like, but hadn’t actually computed the result.

  3. Then, when I ran collapsed.compute(), dask came up with a set of assignments it could give to its workers to get me what I wanted and it started to actually compute the table I requested. In particular:

    • each worker loaded a chunk of the data, did the observation-level manipulations I wanted, and dropped extra columns.

    • then to execute the groupby, it then collapsed the data in each chunk, passed those collapsed chunks to a common worker who then re-collapsed them further, then gathered them again under (potentially) another worker and collapsed further until all the data had been collapsed.

    • Finally, after all the data had been collapsed, the data was passed back to me (the client session) as the variable final.

And it did it all in under 5 minutes!

“Um… why didn’t you tell us about this before?” I hear you say…

“This sure seems like this is easier than chunking by hand!!!!”

The answer is that these distributed computing tools are often very fragile and opaque, and it’s easy to get in trouble using them, and hard to figure out why if you don’t understand the underlying principles that govern their operation.

This example was carefully chosen. I used only manipulations that dask is really good at, and I have the experience to implement them in a way that works. But do what I did above in slightly different ways, and chaos would ensure. Ok, not chaos. But your computer would probably crash.

The biggest challenge in using a tool like dask or spark (they operate on the same principles – more on that below) is that to prevent crashes, you have to understand how and why dask is chunking your data. And the best way to do that is to get experience chunking by hand.

For example, one of the key features of distributing computing is that they don’t run code as soon as you type it. Instead, they just keep track of what you want and wait until you run .compute() to actually execute your code. Why? Because if dask had run each command as I entered it and passed the result back to me, it would have crashed my computer.

Recall that the whole reason we’re using dask is precisely because we knew that loading the whole dataset at once would take up more memory than I have available. It’s only because we only loaded a few chunks of the data at a time, thinned out those chunks by dropping variables, and then collapsed by county-state-year that we ended up with a dataset that was small enough that it would fit in memory.

In other words, this only worked because I knew that the steps after the initial load would reduce the size of the dataset enough that when I ran .compute(), the result I got back would be small enough to fit in memory. Had I just run:

df = dd.read_csv(
    "arcos_all_washpost_2006_2012.tsv",
    sep="\t",
    dtype={
        "ACTION_INDICATOR": "object",
        "ORDER_FORM_NO": "object",
        "REPORTER_ADDRESS2": "object",
        "REPORTER_ADDL_CO_INFO": "object",
        "BUYER_ADDL_CO_INFO": "object",
        "BUYER_ADDRESS2": "object",
        "NDC_NO": "object",
        "UNIT": "object",
    },
)
df.compute()

dask would have tried to hand the full dataset back to me, and my computer would have crashed, just as it would have had I tried to read the full dataset with pandas.

So understanding the intuition of chunking is basically a prerequisite to using these tools effectively.

Vocabulary

Now that we’ve seen this example, let’s formally introduce some distributed computing vocabulary:

  • Lazy Evaluation (also sometimes called “delayed execution”): The practice of not executing code as soon as you type it, but rather accumulating a set of requests, then executing them when instructed. This allows distributing computing systems to optimize how they move around data and get things done, and ensures that you don’t end up with the system trying to shove a massive dataset into ram that’s too small.

  • Client: The central process (here, Python process) where code is being entered.

  • Workers: Other processes that are assigned work, and which eventually pass results back to the client.

  • Scheduler: The part of the system that manages the assignment of tasks to different workers.

  • map-reduce: The name for the process of distributing sub-problems to workers (map), then processing them in a way that allows the results to be recombined (reduce). maps and reduces are kind of the building blocks of distributed systems, though when working with dask you won’t usually have to manage the assignment or recombination of tasks yourself (they’re happening behind the scenes).

Let’s Learn More dask!

OK, now that we have the basic idea of dask in hand, please watch the following set of seven short videos on dask, then come back here and we can talk some more!

Dask Tutorial from Coiled—7 videos, about 1 hour in total

There is no magic here

As noted in that video, one of the very nice things about dask (and one of the reasons it’s been able to offer so much functionality so quickly) is that it really is just an extension of numpy and pandas. There is no magic here.

For example, suppose we wanted to find the largest number of pills in a single shipment in our ARCOS dataset, but we don’t have the memory to load the whole dataset into memory at once. How would we get that number? Probably by doing something like:

[6]:
import pandas as pd
import numpy as np
import os

os.chdir("/users/nce8/dropbox/MIDS_Data_Prep/arcos")

# Create an interator of the data so
# it doesn't all load at once
df = pd.read_csv(
    "arcos_all_washpost_2006_2012.tsv",
    delimiter="\t",
    iterator=True,
    chunksize=100_000,
    usecols=["DOSAGE_UNIT", "Measure"],
)


# Find the max from each chunk
max_candidates = list()
for chunk in df:
    # Subset for pill shipments
    chunk = chunk[chunk["Measure"] == "TAB"]

    # Find largest in this chunk
    max_candidates.append(chunk["DOSAGE_UNIT"].max())

# Now gather those candidates together and
# find the maximum of all the chunk maximums.
np.max(max_candidates)

[6]:
3115000.0

Wow… that is a LOT of pills!

Now suppose we asked dask to do the same thing:

[7]:
df = dd.read_csv(
    "arcos_all_washpost_2006_2012.tsv",
    sep="\t",
    dtype={
        "ACTION_INDICATOR": "object",
        "ORDER_FORM_NO": "object",
        "REPORTER_ADDRESS2": "object",
        "REPORTER_ADDL_CO_INFO": "object",
        "BUYER_ADDL_CO_INFO": "object",
        "BUYER_ADDRESS2": "object",
        "NDC_NO": "object",
        "UNIT": "object",
    },
)

df = df[df["Measure"] == "TAB"]
max_shipment = df["DOSAGE_UNIT"].max()
max_shipment.compute()

[7]:
3115000.0

What dask is actually doing is exactly what you just did! It reads in chunks of the dataset, calculates morphine_equivalent_g for each chunk, then calculates the maximum value for that chunk. Then it gathers all those maximium values, and finds the maximum of all those chunk maximums. The only difference is that it loads and evaluations chunks in parallel, and it’s parallel workers then have to pass their maximum value candidates to a central node for the final evaluation.

Moreover, when I said that’s exactly what dask did, I don’t just mean that you and dask are doing the same thing in principle—dask is built on pandas, so it really is calling pd.read_csv, and the pandas .max() method, just like you.

Dask’s developers were smart, and didn’t want to reinvent the wheel—they just created a package full or recipes for using numpy/pandas to (a) divide tasks into smaller pieces it can distribute to different workers (map), and to (b) recombine the results of sub-problems to give you a single answer (reduce).

But those recipes are just made of the pandas and numpy code you know and love. Or at least tolerate begrudingly.

Lazy Evaluation

You’ve already seen this above, but I think this is THE concept that is central to understanding not just dask, but any distributed computing platform (e.g. Spark, Hadoop, etc.), so I really want to drive home the importance of this concept.

The fact that you can give dask a handful of commands and then tell it to execute them is at the absolute core of what makes it effective. The more commands you can give dask up front, the more it can optimize how it distributes that work—and how it moves data between different computers. Moving data between processes and between computers is by far the slowest part of distributed computing, so the more dask can minimize those transfers, the faster it will be.

Moreover, lazy evaluation is how you protect yourself from crashing your computer. Consider the following code:

df = dd.read_csv(
    "arcos_all_washpost_2006_2012.tsv",
    sep="\t",
    dtype={
        "ACTION_INDICATOR": "object",
        "ORDER_FORM_NO": "object",
        "REPORTER_ADDRESS2": "object",
        "REPORTER_ADDL_CO_INFO": "object",
        "BUYER_ADDL_CO_INFO": "object",
        "BUYER_ADDRESS2": "object",
        "NDC_NO": "object",
        "UNIT": "object",
    },
)

df = df[df['Measure'] == "TAB"]
df.compute()

If dd.read_csv() executed immediately and tried to load all the data and pass it back to you before subsetting, it’d crash your computer! After all, if you could load it all at once, we probably wouldn’t be using dask, would we? It’s only because dask knows you want to load each chunk then subset it before collecting all those pieces that this code works.

Visualizing Task Graphs

You can actually see how your computer is developing a plan with the .dask method, which you can run on any dask object before you’ve run .compute(). Let’s see this in practice with our code from the top of this notebook (You get an HTML object you can manipulate and explore):

[8]:
df = dd.read_csv(
    "arcos_all_washpost_2006_2012.tsv",
    sep="\t",
    dtype={
        "ACTION_INDICATOR": "object",
        "ORDER_FORM_NO": "object",
        "REPORTER_ADDRESS2": "object",
        "REPORTER_ADDL_CO_INFO": "object",
        "BUYER_ADDL_CO_INFO": "object",
        "BUYER_ADDRESS2": "object",
        "NDC_NO": "object",
        "UNIT": "object",
    },
)

# Extract year
df["date"] = dd.to_datetime(df.TRANSACTION_DATE, format="%m%d%Y")
df["year"] = df.date.dt.year

# Make an estimate of total morphine equivalent shipments
df["morphine_equivalent_g"] = (df["CALC_BASE_WT_IN_GM"]) * df["MME_Conversion_Factor"]

# Drop extra vars
df = df[["year", "morphine_equivalent_g", "BUYER_STATE", "BUYER_COUNTY"]]

# Collapse to total shipments to each county in each year.
collapsed = df.groupby(
    ["year", "BUYER_STATE", "BUYER_COUNTY"]
).morphine_equivalent_g.sum()

collapsed.dask

[8]:

HighLevelGraph

HighLevelGraph with 14 layers and 16238 keys from all layers.

Layer1: read-csv

read-csv-98dc9420c2f021fb4e0bb3d80c72065d

layer_type DataFrameIOLayer
is_materialized False
number of outputs 1249
npartitions 1249
columns ['REPORTER_DEA_NO', 'REPORTER_BUS_ACT', 'REPORTER_NAME', 'REPORTER_ADDL_CO_INFO', 'REPORTER_ADDRESS1', 'REPORTER_ADDRESS2', 'REPORTER_CITY', 'REPORTER_STATE', 'REPORTER_ZIP', 'REPORTER_COUNTY', 'BUYER_DEA_NO', 'BUYER_BUS_ACT', 'BUYER_NAME', 'BUYER_ADDL_CO_INFO', 'BUYER_ADDRESS1', 'BUYER_ADDRESS2', 'BUYER_CITY', 'BUYER_STATE', 'BUYER_ZIP', 'BUYER_COUNTY', 'TRANSACTION_CODE', 'DRUG_CODE', 'NDC_NO', 'DRUG_NAME', 'QUANTITY', 'UNIT', 'ACTION_INDICATOR', 'ORDER_FORM_NO', 'CORRECTION_NO', 'STRENGTH', 'TRANSACTION_DATE', 'CALC_BASE_WT_IN_GM', 'DOSAGE_UNIT', 'TRANSACTION_ID', 'Product_Name', 'Ingredient_Name', 'Measure', 'MME_Conversion_Factor', 'Combined_Labeler_Name', 'Revised_Company_Name', 'Reporter_family', 'dos_str']
type dask.dataframe.core.DataFrame
dataframe_type pandas.core.frame.DataFrame
series_dtypes {'REPORTER_DEA_NO': dtype('O'), 'REPORTER_BUS_ACT': dtype('O'), 'REPORTER_NAME': dtype('O'), 'REPORTER_ADDL_CO_INFO': dtype('O'), 'REPORTER_ADDRESS1': dtype('O'), 'REPORTER_ADDRESS2': dtype('O'), 'REPORTER_CITY': dtype('O'), 'REPORTER_STATE': dtype('O'), 'REPORTER_ZIP': dtype('int64'), 'REPORTER_COUNTY': dtype('O'), 'BUYER_DEA_NO': dtype('O'), 'BUYER_BUS_ACT': dtype('O'), 'BUYER_NAME': dtype('O'), 'BUYER_ADDL_CO_INFO': dtype('O'), 'BUYER_ADDRESS1': dtype('O'), 'BUYER_ADDRESS2': dtype('O'), 'BUYER_CITY': dtype('O'), 'BUYER_STATE': dtype('O'), 'BUYER_ZIP': dtype('int64'), 'BUYER_COUNTY': dtype('O'), 'TRANSACTION_CODE': dtype('O'), 'DRUG_CODE': dtype('int64'), 'NDC_NO': dtype('O'), 'DRUG_NAME': dtype('O'), 'QUANTITY': dtype('float64'), 'UNIT': dtype('O'), 'ACTION_INDICATOR': dtype('O'), 'ORDER_FORM_NO': dtype('O'), 'CORRECTION_NO': dtype('float64'), 'STRENGTH': dtype('float64'), 'TRANSACTION_DATE': dtype('int64'), 'CALC_BASE_WT_IN_GM': dtype('float64'), 'DOSAGE_UNIT': dtype('float64'), 'TRANSACTION_ID': dtype('int64'), 'Product_Name': dtype('O'), 'Ingredient_Name': dtype('O'), 'Measure': dtype('O'), 'MME_Conversion_Factor': dtype('float64'), 'Combined_Labeler_Name': dtype('O'), 'Revised_Company_Name': dtype('O'), 'Reporter_family': dtype('O'), 'dos_str': dtype('float64')}

Layer2: getitem

getitem-b4fc17c18d2b87711188593a28c0412d

layer_type Blockwise
is_materialized False
number of outputs 1249
depends on read-csv-98dc9420c2f021fb4e0bb3d80c72065d

Layer3: to_datetime

to_datetime-52eca15982ab857959b3001545bb57fa

layer_type Blockwise
is_materialized False
number of outputs 1249
depends on getitem-b4fc17c18d2b87711188593a28c0412d

Layer4: assign

assign-df1f62c87a9d21a7c2e1959a33e7735a

layer_type Blockwise
is_materialized False
number of outputs 1249
npartitions 1249
columns ['REPORTER_DEA_NO', 'REPORTER_BUS_ACT', 'REPORTER_NAME', 'REPORTER_ADDL_CO_INFO', 'REPORTER_ADDRESS1', 'REPORTER_ADDRESS2', 'REPORTER_CITY', 'REPORTER_STATE', 'REPORTER_ZIP', 'REPORTER_COUNTY', 'BUYER_DEA_NO', 'BUYER_BUS_ACT', 'BUYER_NAME', 'BUYER_ADDL_CO_INFO', 'BUYER_ADDRESS1', 'BUYER_ADDRESS2', 'BUYER_CITY', 'BUYER_STATE', 'BUYER_ZIP', 'BUYER_COUNTY', 'TRANSACTION_CODE', 'DRUG_CODE', 'NDC_NO', 'DRUG_NAME', 'QUANTITY', 'UNIT', 'ACTION_INDICATOR', 'ORDER_FORM_NO', 'CORRECTION_NO', 'STRENGTH', 'TRANSACTION_DATE', 'CALC_BASE_WT_IN_GM', 'DOSAGE_UNIT', 'TRANSACTION_ID', 'Product_Name', 'Ingredient_Name', 'Measure', 'MME_Conversion_Factor', 'Combined_Labeler_Name', 'Revised_Company_Name', 'Reporter_family', 'dos_str', 'date']
type dask.dataframe.core.DataFrame
dataframe_type pandas.core.frame.DataFrame
series_dtypes {'REPORTER_DEA_NO': dtype('O'), 'REPORTER_BUS_ACT': dtype('O'), 'REPORTER_NAME': dtype('O'), 'REPORTER_ADDL_CO_INFO': dtype('O'), 'REPORTER_ADDRESS1': dtype('O'), 'REPORTER_ADDRESS2': dtype('O'), 'REPORTER_CITY': dtype('O'), 'REPORTER_STATE': dtype('O'), 'REPORTER_ZIP': dtype('int64'), 'REPORTER_COUNTY': dtype('O'), 'BUYER_DEA_NO': dtype('O'), 'BUYER_BUS_ACT': dtype('O'), 'BUYER_NAME': dtype('O'), 'BUYER_ADDL_CO_INFO': dtype('O'), 'BUYER_ADDRESS1': dtype('O'), 'BUYER_ADDRESS2': dtype('O'), 'BUYER_CITY': dtype('O'), 'BUYER_STATE': dtype('O'), 'BUYER_ZIP': dtype('int64'), 'BUYER_COUNTY': dtype('O'), 'TRANSACTION_CODE': dtype('O'), 'DRUG_CODE': dtype('int64'), 'NDC_NO': dtype('O'), 'DRUG_NAME': dtype('O'), 'QUANTITY': dtype('float64'), 'UNIT': dtype('O'), 'ACTION_INDICATOR': dtype('O'), 'ORDER_FORM_NO': dtype('O'), 'CORRECTION_NO': dtype('float64'), 'STRENGTH': dtype('float64'), 'TRANSACTION_DATE': dtype('int64'), 'CALC_BASE_WT_IN_GM': dtype('float64'), 'DOSAGE_UNIT': dtype('float64'), 'TRANSACTION_ID': dtype('int64'), 'Product_Name': dtype('O'), 'Ingredient_Name': dtype('O'), 'Measure': dtype('O'), 'MME_Conversion_Factor': dtype('float64'), 'Combined_Labeler_Name': dtype('O'), 'Revised_Company_Name': dtype('O'), 'Reporter_family': dtype('O'), 'dos_str': dtype('float64'), 'date': dtype('<M8[ns]')}
depends on read-csv-98dc9420c2f021fb4e0bb3d80c72065d
to_datetime-52eca15982ab857959b3001545bb57fa

Layer5: getitem

getitem-06023399ad03ddb0261ddd8d1b79d5e3

layer_type Blockwise
is_materialized False
number of outputs 1249
depends on assign-df1f62c87a9d21a7c2e1959a33e7735a

Layer6: dt-year

dt-year-a9efa4ff5a9d6612f62c70f567177170

layer_type Blockwise
is_materialized False
number of outputs 1249
depends on getitem-06023399ad03ddb0261ddd8d1b79d5e3

Layer7: assign

assign-f485e25f94f5664c192e73df6d42002d

layer_type Blockwise
is_materialized False
number of outputs 1249
npartitions 1249
columns ['REPORTER_DEA_NO', 'REPORTER_BUS_ACT', 'REPORTER_NAME', 'REPORTER_ADDL_CO_INFO', 'REPORTER_ADDRESS1', 'REPORTER_ADDRESS2', 'REPORTER_CITY', 'REPORTER_STATE', 'REPORTER_ZIP', 'REPORTER_COUNTY', 'BUYER_DEA_NO', 'BUYER_BUS_ACT', 'BUYER_NAME', 'BUYER_ADDL_CO_INFO', 'BUYER_ADDRESS1', 'BUYER_ADDRESS2', 'BUYER_CITY', 'BUYER_STATE', 'BUYER_ZIP', 'BUYER_COUNTY', 'TRANSACTION_CODE', 'DRUG_CODE', 'NDC_NO', 'DRUG_NAME', 'QUANTITY', 'UNIT', 'ACTION_INDICATOR', 'ORDER_FORM_NO', 'CORRECTION_NO', 'STRENGTH', 'TRANSACTION_DATE', 'CALC_BASE_WT_IN_GM', 'DOSAGE_UNIT', 'TRANSACTION_ID', 'Product_Name', 'Ingredient_Name', 'Measure', 'MME_Conversion_Factor', 'Combined_Labeler_Name', 'Revised_Company_Name', 'Reporter_family', 'dos_str', 'date', 'year']
type dask.dataframe.core.DataFrame
dataframe_type pandas.core.frame.DataFrame
series_dtypes {'REPORTER_DEA_NO': dtype('O'), 'REPORTER_BUS_ACT': dtype('O'), 'REPORTER_NAME': dtype('O'), 'REPORTER_ADDL_CO_INFO': dtype('O'), 'REPORTER_ADDRESS1': dtype('O'), 'REPORTER_ADDRESS2': dtype('O'), 'REPORTER_CITY': dtype('O'), 'REPORTER_STATE': dtype('O'), 'REPORTER_ZIP': dtype('int64'), 'REPORTER_COUNTY': dtype('O'), 'BUYER_DEA_NO': dtype('O'), 'BUYER_BUS_ACT': dtype('O'), 'BUYER_NAME': dtype('O'), 'BUYER_ADDL_CO_INFO': dtype('O'), 'BUYER_ADDRESS1': dtype('O'), 'BUYER_ADDRESS2': dtype('O'), 'BUYER_CITY': dtype('O'), 'BUYER_STATE': dtype('O'), 'BUYER_ZIP': dtype('int64'), 'BUYER_COUNTY': dtype('O'), 'TRANSACTION_CODE': dtype('O'), 'DRUG_CODE': dtype('int64'), 'NDC_NO': dtype('O'), 'DRUG_NAME': dtype('O'), 'QUANTITY': dtype('float64'), 'UNIT': dtype('O'), 'ACTION_INDICATOR': dtype('O'), 'ORDER_FORM_NO': dtype('O'), 'CORRECTION_NO': dtype('float64'), 'STRENGTH': dtype('float64'), 'TRANSACTION_DATE': dtype('int64'), 'CALC_BASE_WT_IN_GM': dtype('float64'), 'DOSAGE_UNIT': dtype('float64'), 'TRANSACTION_ID': dtype('int64'), 'Product_Name': dtype('O'), 'Ingredient_Name': dtype('O'), 'Measure': dtype('O'), 'MME_Conversion_Factor': dtype('float64'), 'Combined_Labeler_Name': dtype('O'), 'Revised_Company_Name': dtype('O'), 'Reporter_family': dtype('O'), 'dos_str': dtype('float64'), 'date': dtype('<M8[ns]'), 'year': dtype('int64')}
depends on assign-df1f62c87a9d21a7c2e1959a33e7735a
dt-year-a9efa4ff5a9d6612f62c70f567177170

Layer8: getitem

getitem-65b082a7179bbd179d42b1f248add400

layer_type Blockwise
is_materialized False
number of outputs 1249
depends on assign-f485e25f94f5664c192e73df6d42002d

Layer9: getitem

getitem-9b67ae1a2bd7fb1817a63efa1994d7b4

layer_type Blockwise
is_materialized False
number of outputs 1249
depends on assign-f485e25f94f5664c192e73df6d42002d

Layer10: mul

mul-9ab4fa814864c801e2cba6374dc6a7ac

layer_type Blockwise
is_materialized False
number of outputs 1249
depends on getitem-9b67ae1a2bd7fb1817a63efa1994d7b4
getitem-65b082a7179bbd179d42b1f248add400

Layer11: assign

assign-499e0f8d8a2531f815b06b72dcbc9adc

layer_type Blockwise
is_materialized False
number of outputs 1249
npartitions 1249
columns ['REPORTER_DEA_NO', 'REPORTER_BUS_ACT', 'REPORTER_NAME', 'REPORTER_ADDL_CO_INFO', 'REPORTER_ADDRESS1', 'REPORTER_ADDRESS2', 'REPORTER_CITY', 'REPORTER_STATE', 'REPORTER_ZIP', 'REPORTER_COUNTY', 'BUYER_DEA_NO', 'BUYER_BUS_ACT', 'BUYER_NAME', 'BUYER_ADDL_CO_INFO', 'BUYER_ADDRESS1', 'BUYER_ADDRESS2', 'BUYER_CITY', 'BUYER_STATE', 'BUYER_ZIP', 'BUYER_COUNTY', 'TRANSACTION_CODE', 'DRUG_CODE', 'NDC_NO', 'DRUG_NAME', 'QUANTITY', 'UNIT', 'ACTION_INDICATOR', 'ORDER_FORM_NO', 'CORRECTION_NO', 'STRENGTH', 'TRANSACTION_DATE', 'CALC_BASE_WT_IN_GM', 'DOSAGE_UNIT', 'TRANSACTION_ID', 'Product_Name', 'Ingredient_Name', 'Measure', 'MME_Conversion_Factor', 'Combined_Labeler_Name', 'Revised_Company_Name', 'Reporter_family', 'dos_str', 'date', 'year', 'morphine_equivalent_g']
type dask.dataframe.core.DataFrame
dataframe_type pandas.core.frame.DataFrame
series_dtypes {'REPORTER_DEA_NO': dtype('O'), 'REPORTER_BUS_ACT': dtype('O'), 'REPORTER_NAME': dtype('O'), 'REPORTER_ADDL_CO_INFO': dtype('O'), 'REPORTER_ADDRESS1': dtype('O'), 'REPORTER_ADDRESS2': dtype('O'), 'REPORTER_CITY': dtype('O'), 'REPORTER_STATE': dtype('O'), 'REPORTER_ZIP': dtype('int64'), 'REPORTER_COUNTY': dtype('O'), 'BUYER_DEA_NO': dtype('O'), 'BUYER_BUS_ACT': dtype('O'), 'BUYER_NAME': dtype('O'), 'BUYER_ADDL_CO_INFO': dtype('O'), 'BUYER_ADDRESS1': dtype('O'), 'BUYER_ADDRESS2': dtype('O'), 'BUYER_CITY': dtype('O'), 'BUYER_STATE': dtype('O'), 'BUYER_ZIP': dtype('int64'), 'BUYER_COUNTY': dtype('O'), 'TRANSACTION_CODE': dtype('O'), 'DRUG_CODE': dtype('int64'), 'NDC_NO': dtype('O'), 'DRUG_NAME': dtype('O'), 'QUANTITY': dtype('float64'), 'UNIT': dtype('O'), 'ACTION_INDICATOR': dtype('O'), 'ORDER_FORM_NO': dtype('O'), 'CORRECTION_NO': dtype('float64'), 'STRENGTH': dtype('float64'), 'TRANSACTION_DATE': dtype('int64'), 'CALC_BASE_WT_IN_GM': dtype('float64'), 'DOSAGE_UNIT': dtype('float64'), 'TRANSACTION_ID': dtype('int64'), 'Product_Name': dtype('O'), 'Ingredient_Name': dtype('O'), 'Measure': dtype('O'), 'MME_Conversion_Factor': dtype('float64'), 'Combined_Labeler_Name': dtype('O'), 'Revised_Company_Name': dtype('O'), 'Reporter_family': dtype('O'), 'dos_str': dtype('float64'), 'date': dtype('<M8[ns]'), 'year': dtype('int64'), 'morphine_equivalent_g': dtype('float64')}
depends on mul-9ab4fa814864c801e2cba6374dc6a7ac
assign-f485e25f94f5664c192e73df6d42002d

Layer12: getitem

getitem-9b6041b75a79c3e71d6d7acd7239fd91

layer_type Blockwise
is_materialized False
number of outputs 1249
npartitions 1249
columns ['year', 'morphine_equivalent_g', 'BUYER_STATE', 'BUYER_COUNTY']
type dask.dataframe.core.DataFrame
dataframe_type pandas.core.frame.DataFrame
series_dtypes {'year': dtype('int64'), 'morphine_equivalent_g': dtype('float64'), 'BUYER_STATE': dtype('O'), 'BUYER_COUNTY': dtype('O')}
depends on assign-499e0f8d8a2531f815b06b72dcbc9adc

Layer13: series-groupby-sum-chunk

series-groupby-sum-chunk-3fbadc183a38ae4572bc0a532c474cd5-d5a6d15d0b1463d80fbfbb777dc826f7

layer_type Blockwise
is_materialized False
number of outputs 1249
depends on getitem-9b6041b75a79c3e71d6d7acd7239fd91

Layer14: series-groupby-sum-agg

series-groupby-sum-agg-3fbadc183a38ae4572bc0a532c474cd5

layer_type DataFrameTreeReduction
is_materialized False
number of outputs 1
depends on series-groupby-sum-chunk-3fbadc183a38ae4572bc0a532c474cd5-d5a6d15d0b1463d80fbfbb777dc826f7

Or you can plot out a task graph. You can do this at a high level with .dask.visualize(), or in excruciating detail for a task this big with just .visualize(). Note visualize() does require you install additional libraries, so install ipycytoscape and python-graphviz with conda first. But these get so big I’m not gonna include one here—you can find examples here if you’d like to see more.

dask versus Spark / PySpark

Dask is something of a late-comer to the distributed computing game. Before its rise, the most popular platforms were Hadoop and Spark (spark is basically “Hadoop v2.0”). So… how does dask compare to these? Or more specifically, how does dask compare to Spark (since no one uses Hadoop anymore) and the various Python libraries for using Spark (e.g. PySpark and koalas)?

In terms of functionality, dask and Spark basically do the same things. Both are tools for distributed computing across many computers, and conceptually they work in basically the same ways:

  • Both offer both low-level tools (things like map/filter in pyspark, and delayed in dask) as well as higher-level data structures (spark has spark dataframes, dask has dask arrays; spark has RDDs, dask has dask arrays).

  • Both are fault tolerant (if one machine in your cluster dies, the system knows what the machine that died was doing and can assign it to another cluster).

  • Both make use of delayed execution / lazy evaluation to allow the system to develop efficient plans for completing a computation efficiently.

  • Both can be run on your own computer, or on a cluster of lots of computers.

The huge difference, though, is that dask lets you write code with the pandas syntax you already know. Seriously. There are lots of little “under the hood” things, but from the perspective of an applied Data Scientist, that’s the big one: it’s just a version of pandas.

Moreover, as we’ll see in later lessons, dask is also insanely easy to setup on a distributed cluster, making it not only easier to use than Spark for a pandas user, but generally also much easier to get up and running (at least in my experience).

Spark, by contrast, is a stand-alone system. It’s built to run on Java virtual machines, and Spark itself is written in a language called Scala. It is not a tool for pandas users per se, and so it has its own syntax for manipulating datasets that is distinct from that of numpy and pandas.

A Note on Koalas: in the last year or so, there have been inroads in implementing the pandas API on top of spark—check out koalas project if you’re at a place that uses spark!

As for which is more popular, as is so often the case with software, it depends on where you’re working. In this class, I’ve decided to teach dask because you don’t have to learn a new syntax, so you can instead just focus on learning how distributed computing works. But if you get a job someday that requires you to work with Spark, don’t panic – you’ll find that all the concepts you’ve learned for using dask also apply to Spark—you’ll just have to learn some new syntax.

And as for performance, it probably depends on the workload, but I’ve yet to see anything that suggests dask compute times are slower than Spark compute times. Case studies are always tricky since performance depends on the exact work being done, but here’s one case study comparison of performance that puts dask just a little ahead. And I’ve heard reports of dask beating Spark by 40x in another project. So personally, I think dask is a no-brainer if you aren’t working at a company that it is already using spark: it will take much less of your time setup and use, and it should at least run about even with Spark.

The only exceptions are some specific use cases, like network analysis, where Spark has some libraries that dask does not. For more on these types of issues, check out this conceptual comparison to Spark.

What else can dask do?

At this point, we’ve mostly emphasized what dask can do in terms of the data wrangling of dataframes. However, dask has a number of additional functionalities to be aware of:

  • Working with dask arrays: dask has a parallelized version of numpy arrays

  • Parallelizing arbitrary functions: you can write your own parallelized functions with delayed

  • Distributed machine learning: dask has parallelized SOME machine learning methods in dask-ml

  • dask can be used with different tools for parallelization other than distributed (for example, it can do some parallelism through multi-threading). However… it seems like everyone seems to agree at this point you should just use distributed all the time.

What can’t dask do?

Because dask is basically a library full of little recipes for parallelizing common python, numpy, and pandas functions, you will occassionally find that there are some things that the authors of dask just haven’t implemented (usually because some operations are really hard to parallelize). Here are guides to what you can expect to work and what is unlikely to work with dask:

If you really want to get into dask…

Then after doing the exercise below (which I think is actually the most accessible to those taking this class), here are some extensions and next steps:

  • dask-ml: As a reminder, if you now want to do some machine learning, you can use dask-ml on this system, which does the same thing for scikit-learn that regular dask does for pandas.

  • Check out dask best practices here.

  • Here’s a great blog post on the history of dask by one of its creaters.

  • Interested in using dask in your company and want help? There’s a great new company created by the founders of dask to provide enterprise support for dask called coiled (No, I have no affiliation with them, I just think these companies that try to offer paid support services to businesses to help them move from closed source software to open source are a great way to help make open source software better). You can also hear a fun interview with the founders about both dask and coiled here.

  • The folks from coiled have also compiled a great collection of videos and tutorials about dask and Python at scale here

  • Curious how dask compares to other tools for distributed computing? Here’s a conceptual comparison to Spark, and here’s a case study comparison of performance. Comparisons will usually depend a lot on the specifics of the work being done, but at least in this case, dask was a little faster than Spark.

  • Working with GPUs? There’s a project to offer the kind of CPU parallelization we get from dask for GPUs called dask-cudf (part of the RAPIDS project. The project is young but growing quickly. My guess, though, is that those libraries will become the infrastructure for updates to tools like dask-ml rather than something most applied people need to play with. But putting it here as an FYI!

Exercises

Exercises can be found here

If you want more, you can find tutorials written by the dask team here.

(Note: all these tutorials are great, but as the focus of this class is on real world tabular data, we’re gonna focus on those exercises).

When you’re done, you can find a dask cheatsheet here for future reference!