{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Dask array provides a parallel, larger-than-memory, n-dimensional array using blocked algorithms. Simply put: distributed Numpy.\n", "\n", "* **Parallel**: Uses all of the cores on your computer\n", "* **Larger-than-memory**: Lets you work on datasets that are larger than your available memory by breaking up your array into many small pieces, operating on those pieces in an order that minimizes the memory footprint of your computation, and effectively streaming data from disk.\n", "* **Blocked Algorithms**: Perform large computations by performing many smaller computations\n", "\n", "In this notebook, we'll build some understanding by implementing some blocked algorithms from scratch.\n", "We'll then use Dask Array to analyze large datasets, in parallel, using a familiar NumPy-like API.\n", "\n", "**Related Documentation**\n", "\n", "* [Array documentation](https://docs.dask.org/en/latest/array.html)\n", "* [Array screencast](https://youtu.be/9h_61hXCDuI)\n", "* [Array API](https://docs.dask.org/en/latest/array-api.html)\n", "* [Array examples](https://examples.dask.org/array.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%run prep.py -d random" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from dask.distributed import Client\n", "\n", "client = Client(n_workers=4, processes=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Blocked Algorithms" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A *blocked algorithm* executes on a large dataset by breaking it up into many small blocks.\n", "\n", "For example, consider taking the sum of a billion numbers. We might instead break up the array into 1,000 chunks, each of size 1,000,000, take the sum of each chunk, and then take the sum of the intermediate sums.\n", "\n", "We achieve the intended result (one sum on one billion numbers) by performing many smaller results (one thousand sums on one million numbers each, followed by another sum of a thousand numbers.)\n", "\n", "We do exactly this with Python and NumPy in the following example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Load data with h5py\n", "# this creates a pointer to the data, but does not actually load\n", "import h5py\n", "import os\n", "f = h5py.File(os.path.join('data', 'random.hdf5'), mode='r')\n", "dset = f['/x']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Compute sum using blocked algorithm**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before using dask, lets consider the concept of blocked algorithms. We can compute the sum of a large number of elements by loading them chunk-by-chunk, and keeping a running total.\n", "\n", "Here we compute the sum of this large array on disk by \n", "\n", "1. Computing the sum of each 1,000,000 sized chunk of the array\n", "2. Computing the sum of the 1,000 intermediate sums\n", "\n", "Note that this is a sequential process in the notebook kernel, both the loading and summing." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute sum of large array, one million numbers at a time\n", "sums = []\n", "for i in range(0, 1000000000, 1000000):\n", " chunk = dset[i: i + 1000000] # pull out numpy array\n", " sums.append(chunk.sum())\n", "\n", "total = sum(sums)\n", "print(total)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: Compute the mean using a blocked algorithm" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we've seen the simple example above try doing a slightly more complicated problem, compute the mean of the array, assuming for a moment that we don't happen to already know how many elements are in the data. You can do this by changing the code above with the following alterations:\n", "\n", "1. Compute the sum of each block\n", "2. Compute the length of each block\n", "3. Compute the sum of the 1,000 intermediate sums and the sum of the 1,000 intermediate lengths and divide one by the other\n", "\n", "This approach is overkill for our case but does nicely generalize if we don't know the size of the array or individual blocks beforehand." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Compute the mean of the array" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "sums = []\n", "lengths = []\n", "for i in range(0, 1000000000, 1000000):\n", " chunk = dset[i: i + 1000000] # pull out numpy array\n", " sums.append(chunk.sum())\n", " lengths.append(len(chunk))\n", "\n", "total = sum(sums)\n", "length = sum(lengths)\n", "print(total / length)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`dask.array` contains these algorithms\n", "--------------------------------------------\n", "\n", "Dask.array is a NumPy-like library that does these kinds of tricks to operate on large datasets that don't fit into memory. It extends beyond the linear problems discussed above to full N-Dimensional algorithms and a decent subset of the NumPy interface." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Create `dask.array` object**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can create a `dask.array` `Array` object with the `da.from_array` function. This function accepts\n", "\n", "1. `data`: Any object that supports NumPy slicing, like `dset`\n", "2. `chunks`: A chunk size to tell us how to block up our array, like `(1000000,)`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import dask.array as da\n", "x = da.from_array(dset, chunks=(1000000,))\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Manipulate `dask.array` object as you would a numpy array**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have an `Array` we perform standard numpy-style computations like arithmetic, mathematics, slicing, reductions, etc..\n", "\n", "The interface is familiar, but the actual work is different. dask_array.sum() does not do the same thing as numpy_array.sum()." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**What's the difference?**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`dask_array.sum()` builds an expression of the computation. It does not do the computation yet. `numpy_array.sum()` computes the sum immediately." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Why the difference?*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dask arrays are split into chunks. Each chunk must have computations run on that chunk explicitly. If the desired answer comes from a small slice of the entire dataset, running the computation over all data would be wasteful of CPU and memory." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "result = x.sum()\n", "result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Compute result**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dask.array objects are lazily evaluated. Operations like `.sum` build up a graph of blocked tasks to execute. \n", "\n", "We ask for the final result with a call to `.compute()`. This triggers the actual computation." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "result.compute()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: Compute the mean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And the variance, std, etc.. This should be a small change to the example above.\n", "\n", "Look at what other operations you can do with the Jupyter notebook's tab-completion." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Does this match your result from before?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Performance and Parallelism\n", "-------------------------------\n", "\n", "\n", "\n", "In our first examples we used `for` loops to walk through the array one block at a time. For simple operations like `sum` this is optimal. However for complex operations we may want to traverse through the array differently. In particular we may want the following:\n", "\n", "1. Use multiple cores in parallel\n", "2. Chain operations on a single blocks before moving on to the next one\n", "\n", "Dask.array translates your array operations into a graph of inter-related tasks with data dependencies between them. Dask then executes this graph in parallel with multiple threads. We'll discuss more about this in the next section.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Construct a 20000x20000 array of normally distributed random values broken up into 1000x1000 sized chunks\n", "2. Take the mean along one axis\n", "3. Take every 100th element" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import dask.array as da\n", "\n", "x = da.random.normal(10, 0.1, size=(20000, 20000), # 400 million element array \n", " chunks=(1000, 1000)) # Cut into 1000x1000 sized chunks\n", "y = x.mean(axis=0)[::100] # Perform NumPy-style operations" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x.nbytes / 1e9 # Gigabytes of the input processed lazily" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "y.compute() # Time to compute the result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Performance comparision\n", "---------------------------\n", "\n", "The following experiment was performed on a heavy personal laptop. Your performance may vary. If you attempt the NumPy version then please ensure that you have more than 4GB of main memory." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**NumPy: 19s, Needs gigabytes of memory**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "import numpy as np\n", "\n", "%%time \n", "x = np.random.normal(10, 0.1, size=(20000, 20000)) \n", "y = x.mean(axis=0)[::100] \n", "y\n", "\n", "CPU times: user 19.6 s, sys: 160 ms, total: 19.8 s\n", "Wall time: 19.7 s\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Dask Array: 4s, Needs megabytes of memory**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "import dask.array as da\n", "\n", "%%time\n", "x = da.random.normal(10, 0.1, size=(20000, 20000), chunks=(1000, 1000))\n", "y = x.mean(axis=0)[::100] \n", "y.compute() \n", "\n", "CPU times: user 29.4 s, sys: 1.07 s, total: 30.5 s\n", "Wall time: 4.01 s\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Discussion**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the Dask array computation ran in 4 seconds, but used 29.4 seconds of user CPU time. The numpy computation ran in 19.7 seconds and used 19.6 seconds of user CPU time.\n", "\n", "Dask finished faster, but used more total CPU time because Dask was able to transparently parallelize the computation because of the chunk size." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Questions*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* What happens if the dask chunks=(20000,20000)?\n", " * Will the computation run in 4 seconds?\n", " * How much memory will be used?\n", "* What happens if the dask chunks=(25,25)?\n", " * What happens to CPU and memory?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: Meteorological data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is 2GB of somewhat artifical weather data in HDF5 files in `data/weather-big/*.hdf5`. We'll use the `h5py` library to interact with this data and `dask.array` to compute on it.\n", "\n", "Our goal is to visualize the average temperature on the surface of the Earth for this month. This will require a mean over all of this data. We'll do this in the following steps\n", "\n", "1. Create `h5py.Dataset` objects for each of the days of data on disk (`dsets`)\n", "2. Wrap these with `da.from_array` calls \n", "3. Stack these datasets along time with a call to `da.stack`\n", "4. Compute the mean along the newly stacked time axis with the `.mean()` method\n", "5. Visualize the result with `matplotlib.pyplot.imshow`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%run prep.py -d weather" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import h5py\n", "from glob import glob\n", "import os\n", "\n", "filenames = sorted(glob(os.path.join('data', 'weather-big', '*.hdf5')))\n", "dsets = [h5py.File(filename, mode='r')['/t2m'] for filename in filenames]\n", "dsets[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dsets[0][:5, :5] # Slicing into h5py.Dataset object gives a numpy array" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "\n", "fig = plt.figure(figsize=(16, 8))\n", "plt.imshow(dsets[0][::4, ::4], cmap='RdBu_r');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Integrate with `dask.array`**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Make a list of `dask.array` objects out of your list of `h5py.Dataset` objects using the `da.from_array` function with a chunk size of `(500, 500)`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arrays = [da.from_array(dset, chunks=(500, 500)) for dset in dsets]\n", "arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Stack this list of `dask.array` objects into a single `dask.array` object with `da.stack`**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Stack these along the first axis so that the shape of the resulting array is `(31, 5760, 11520)`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = da.stack(arrays, axis=0)\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Plot the mean of this array along the time (`0th`) axis**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "raises-exception" ] }, "outputs": [], "source": [ "# complete the following:\n", "fig = plt.figure(figsize=(16, 8))\n", "plt.imshow(..., cmap='RdBu_r')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "result = x.mean(axis=0)\n", "fig = plt.figure(figsize=(16, 8))\n", "plt.imshow(result, cmap='RdBu_r');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Plot the difference of the first day from the mean**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "result = x[0] - x.mean(axis=0)\n", "fig = plt.figure(figsize=(16, 8))\n", "plt.imshow(result, cmap='RdBu_r');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: Subsample and store" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above exercise the result of our computation is small, so we can call `compute` safely. Sometimes our result is still too large to fit into memory and we want to save it to disk. In these cases you can use one of the following two functions\n", "\n", "1. `da.store`: Store dask.array into any object that supports numpy setitem syntax, e.g.\n", "\n", " f = h5py.File('myfile.hdf5')\n", " output = f.create_dataset(shape=..., dtype=...)\n", " \n", " da.store(my_dask_array, output)\n", " \n", "2. `da.to_hdf5`: A specialized function that creates and stores a `dask.array` object into an `HDF5` file.\n", "\n", " da.to_hdf5('data/myfile.hdf5', '/output', my_dask_array)\n", " \n", "The task in this exercise is to **use numpy step slicing to subsample the full dataset by a factor of two in both the latitude and longitude direction and then store this result to disk** using one of the functions listed above.\n", "\n", "As a reminder, Python slicing takes three elements\n", "\n", " start:stop:step\n", "\n", " >>> L = [1, 2, 3, 4, 5, 6, 7]\n", " >>> L[::3]\n", " [1, 4, 7]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "import h5py\n", "from glob import glob\n", "import os\n", "import dask.array as da\n", "\n", "filenames = sorted(glob(os.path.join('data', 'weather-big', '*.hdf5')))\n", "dsets = [h5py.File(filename, mode='r')['/t2m'] for filename in filenames]\n", "\n", "arrays = [da.from_array(dset, chunks=(500, 500)) for dset in dsets]\n", "\n", "x = da.stack(arrays, axis=0)\n", "\n", "result = x[:, ::2, ::2]\n", "\n", "da.to_zarr(result, os.path.join('data', 'myfile.zarr'), overwrite=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example: Lennard-Jones potential" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The [Lennard-Jones](https://en.wikipedia.org/wiki/Lennard-Jones_potential) is used in partical simuluations in physics, chemistry and engineering. It is highly parallelizable.\n", "\n", "First, we'll run and profile the Numpy version on 7,000 particles." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "# make a random collection of particles\n", "def make_cluster(natoms, radius=40, seed=1981):\n", " np.random.seed(seed)\n", " cluster = np.random.normal(0, radius, (natoms,3))-0.5\n", " return cluster\n", "\n", "def lj(r2):\n", " sr6 = (1./r2)**3\n", " pot = 4.*(sr6*sr6 - sr6)\n", " return pot\n", "\n", "# build the matrix of distances\n", "def distances(cluster):\n", " diff = cluster[:, np.newaxis, :] - cluster[np.newaxis, :, :]\n", " mat = (diff*diff).sum(-1)\n", " return mat\n", "\n", "# the lj function is evaluated over the upper traingle\n", "# after removing distances near zero\n", "def potential(cluster):\n", " d2 = distances(cluster)\n", " dtri = np.triu(d2)\n", " energy = lj(dtri[dtri > 1e-6]).sum()\n", " return energy" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cluster = make_cluster(int(7e3), radius=500)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%time potential(cluster)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the most time consuming function is `distances`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# this would open in another browser tab\n", "# %load_ext snakeviz\n", "# %snakeviz potential(cluster)\n", "\n", "# alternative simple version given text results in this tab\n", "%prun -s tottime potential(cluster)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dask version" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's the Dask version. Only the `potential` function needs to be rewritten to best utilize Dask.\n", "\n", "Note that `da.nansum` has been used over the full $NxN$ distance matrix to improve parallel efficiency.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import dask.array as da\n", "\n", "# compute the potential on the entire\n", "# matrix of distances and ignore division by zero\n", "def potential_dask(cluster):\n", " d2 = distances(cluster)\n", " energy = da.nansum(lj(d2))/2.\n", " return energy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's convert the NumPy array to a Dask array. Since the entire NumPy array fits in memory it is more computationally efficient to chunk the array by number of CPU cores." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from os import cpu_count\n", "\n", "dcluster = da.from_array(cluster, chunks=cluster.shape[0]//cpu_count())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This step should scale quite well with number of cores. The warnings are complaining about dividing by zero, which is why we used `da.nansum` in `potential_dask`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "e = potential_dask(dcluster)\n", "%time e.compute()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Limitations\n", "-----------\n", "\n", "Dask Array does not implement the entire numpy interface. Users expecting this\n", "will be disappointed. Notably Dask Array has the following failings:\n", "\n", "1. Dask does not implement all of ``np.linalg``. This has been done by a\n", " number of excellent BLAS/LAPACK implementations and is the focus of\n", " numerous ongoing academic research projects.\n", "2. Dask Array does not support some operations where the resulting shape\n", " depends on the values of the array. For those that it does support\n", " (for example, masking one Dask Array with another boolean mask),\n", " the chunk sizes will be unknown, which may cause issues with other\n", " operations that need to know the chunk sizes.\n", "3. Dask Array does not attempt operations like ``sort`` which are notoriously\n", " difficult to do in parallel and are of somewhat diminished value on very\n", " large data (you rarely actually need a full sort).\n", " Often we include parallel-friendly alternatives like ``topk``.\n", "4. Dask development is driven by immediate need, and so many lesser used\n", " functions, like ``np.sometrue`` have not been implemented purely out of\n", " laziness. These would make excellent community contributions.\n", " \n", "* [Array documentation](https://docs.dask.org/en/latest/array.html)\n", "* [Array screencast](https://youtu.be/9h_61hXCDuI)\n", "* [Array API](https://docs.dask.org/en/latest/array-api.html)\n", "* [Array examples](https://examples.dask.org/array.html)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "client.shutdown()" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 4 }