Skip to content

Commit 1b261ab

Browse files
committed
Add blogpost on flox heuristics
1 parent 4b0e4ec commit 1b261ab

File tree

1 file changed

+159
-0
lines changed

1 file changed

+159
-0
lines changed

src/posts/flox-smart/index.md

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
---
2+
title: flox: GroupBy, now with smarts!'
3+
date: '2024-05-31'
4+
authors:
5+
- name: Deepak Cherian
6+
github: dcherian
7+
8+
summary: 'flox adds heuristics for automatically choosing an appropriate strategy with dask arrays!'
9+
---
10+
11+
## What is flox?
12+
13+
[`flox` implements](https://flox.readthedocs.io/) grouped reductions for chunked array types like cubed and dask using a tree reduction approach.
14+
Tree reduction ([example](https://people.csail.mit.edu/xchen/gpu-programming/Lecture11-reduction.pdf)) are a parallel-friendly way of computing common reduction operations like `sum`, `mean` etc.
15+
Without flox, Xarray shuffles or sorts the data to extract all values in a single group, and then runs the reduction group-by-group.
16+
Depending on data layout ("chunking"), this shuffle can be quite expensive.
17+
With flox installed, Xarray instead uses the parallel-friendly tree reduction approach for the same calculation.
18+
In many cases, this is a massive improvement.
19+
See our [previous blog post](https://xarray.dev/blog/flox) for more.
20+
21+
Two key realizations influenced the development of flox:
22+
23+
1. Array workloads frequently group by a relatively small in-memory array. Quite frequently those arrays have patterns to their values e.g. `"time.month"` is exactly periodic, `"time.dayofyear"` is approximately periodic (depending on calendar), `"time.year"` is commonly a monotonic increasing array.
24+
2. An important difference between arrays and dataframes is that chunk sizes (or "partition sizes") for arrays can be quite small along the core-dimension of an operation.
25+
26+
These two properties are particularly relevant for climatology calculations --- a common Xarray workload.
27+
28+
## Tree reductions can be catastrophically bad
29+
30+
For a catastrophic example, consider `ds.groupby("time.year").mean()`, or the equivalent `ds.resample(time="Y").mean()` for a 100 year long dataset of monthly averages with chunk size of **1** (or **4**) along the time dimension.
31+
This is a fairly common format for climate model output.
32+
The small chunk size along time is offset by much larger chunk sizes along the other dimensions --- commonly horizontal space (`x, y` or `latitude, longitude`).
33+
34+
A naive tree reduction would accumulate all averaged values into a single output chunk of size 100.
35+
Depending on the chunking of the input dataset, this may overload the worker memory and fail catastrophically.
36+
More importantly, there is a lot of wasteful communication --- computing on the last year of data is completely independent of computing on the first year of the data, and there is no reason the two values need to reside in the same output chunk.
37+
38+
## Avoiding catastrophe
39+
40+
Thus `flox` quickly grew two new modes of computing the groupby reduction:
41+
First, `method="blockwise"` which applies the grouped-reduction in a blockwise fashion.
42+
This is great for `resample(time="Y").mean()` where we group by `"time.year"`, which is a monotonic increasing array.
43+
With an appropriate (and usually quite cheap) rechunking, the problem is embarassingly parallel.
44+
45+
Second, `method="cohorts"` which is a bit more subtle.
46+
Consider `groupby("time.month")` for the monthly mean dataset i.e. grouping by an exactly periodic array.
47+
When the chunk size along the core dimension "time" is a divisor of the period; so either 1, 2, 3, 4, or 6 in this case; groups tend to occur in cohorts ("groups of groups").
48+
For example, with a chunk size of 4, monthly mean input data for Jan, Feb, Mar, and April ("one cohort") are _always_ in the same chunk, and totally separate from any of the other months.
49+
This means that we can run the tree reduction for each cohort (three cohorts in total: `JFMA | MJJA | SOND`) independently and expose more parallelism.
50+
Doing so can significantly reduce compute times and in particular memory required for the computation.
51+
52+
Importantly if there isn't much separation of groups into cohorts; example, the groups are randomly distributed, then we'd like the standard `method="map-reduce"` for low overhead.
53+
54+
## Choosing a strategy is hard, and hard to teach.
55+
56+
These strategies are great, but the downside is some sophistication is required to apply them.
57+
Worse, they are hard to explain conceptually! I've tried! ([example 1](https://discourse.pangeo.io/t/optimizing-climatology-calculation-with-xarray-and-dask/2453/20?u=dcherian), [example 2](https://discourse.pangeo.io/t/understanding-optimal-zarr-chunking-scheme-for-a-climatology/2335)).
58+
59+
What we need is to choose the appropriate strategy automatically.
60+
And guess what, `flox>=0.9` will now choose an appropriate method automatically!
61+
62+
## Problem statement
63+
64+
Fundamentally, we know:
65+
66+
1. the data layout or chunking.
67+
2. the array we are grouping by, and can detect possible patterns in that array.
68+
69+
We want to find all sets of groups that occupy similar sets of chunks.
70+
For groups `A,B,C,D` that occupy the following chunks (chunk 0 is the first chunk along the core-dimension or the axis of reduction)
71+
72+
```
73+
A: [0, 1, 2]
74+
B: [1, 2, 3]
75+
D: [5, 6, 7, 8]
76+
E: [8]
77+
X: [0, 3]
78+
```
79+
80+
We want to detect the cohorts `{A,B,X}` and `{C, D}` with the following chunks.
81+
82+
```
83+
[A, B, X]: [0, 1, 2, 3]
84+
[C, D]: [5, 6, 7, 8]
85+
```
86+
87+
Importantly, we do _not_ want to be dependent on detecting exact patterns, and prefer approximate solutions and heuristics.
88+
89+
## The solution
90+
91+
After a fun exploration involving such fun ideas as [locality-sensitive hashing](http://ekzhu.com/datasketch/lshensemble.html), and [all-pair set similarity search](https://www.cse.unsw.edu.au/~lxue/WWW08.pdf), I settled on the following algorithm.
92+
93+
I use set _containment_, or a "normalized intersection", to determine the similarity the sets of chunks occupied by two different groups (`Q` and `X`).
94+
95+
```
96+
C = |Q ∩ X| / |Q| ≤ 1
97+
```
98+
99+
Unlike Jaccard similarity, _containment_ [isn't skewed](http://ekzhu.com/datasketch/lshensemble.html) when one of the sets is much larger than the other.
100+
101+
The steps are as follows:
102+
103+
1. First determine which labels are present in each chunk. The distribution of labels across chunks
104+
is represented internally as a 2D boolean sparse array `S[chunks, labels]`. `S[i, j] = 1` when
105+
label `j` is present in chunk `i`.
106+
107+
1. Now we can quickly determine a number of special cases:
108+
109+
1. Use `"blockwise"` when every group is contained to one block each.
110+
1. Use `"cohorts"` when every chunk only has a single group, but that group might extend across multiple chunks
111+
1. [and more](https://github.com/xarray-contrib/flox/blob/e6159a657c55fa4aeb31bcbcecb341a4849da9fe/flox/core.py#L408-L426)
112+
Here is an example:
113+
![bitmask-patterns](/../diagrams/bitmask-patterns-perfect.png)
114+
115+
- On the left, is a monthly grouping for a monthly time series with chunk size 4. There are 3 non-overlapping cohorts so
116+
`method="cohorts"` is perfect.
117+
- On the right, is a resampling problem of a daily time series with chunk size 10 to 5-daily frequency. Two 5-day periods
118+
are exactly contained in one chunk, so `method="blockwise"` is perfect.
119+
120+
1. At this point, we want to merge groups in to cohorts when they occupy _approximately_ the same chunks. For each group `i` we can quickly compute containment against
121+
all other groups `j` as `C = S.T @ S / number_chunks_per_group`. Here is `C` for a range of chunk sizes from 1 to 12, for computing
122+
the monthly mean of a monthly time series problem, \[the title on each image is `(chunk size, sparsity)`\].
123+
124+
```python
125+
chunks = np.arange(1, 13)
126+
labels = np.tile(np.arange(1, 13), 30)
127+
```
128+
129+
![cohorts-schematic](/../diagrams/containment.png)
130+
131+
1. To choose between `"map-reduce"` and `"cohorts"`, we need a summary measure of the degree to which the labels overlap with
132+
each other. We can use _sparsity_ --- the number of non-zero elements in `C` divided by the number of elements in `C`, `C.nnz/C.size`.
133+
We use _sparsity_ --- the number of non-zero elements in `C` divided by the number of elements in `C`, `C.nnz/C.size`. When sparsity is relatively high, we use `"map-reduce"`, otherwise we use `"cohorts"`.
134+
135+
Cool, isn't it?!
136+
137+
## What's next?
138+
139+
flox' ability to do cool inferences entirely relies on the input chunking, which is a major user-tunable knob.
140+
Perfect optimization still requires some user-tuned chunking.
141+
Recent Xarray feature makes that a lot easier for time grouping:
142+
143+
```
144+
from xarray.groupers import TimeResampler
145+
146+
rechunked = ds.chunk(time=TimeResampler("YE"))
147+
```
148+
149+
will rechunk so that a year of data is in a single chunk.
150+
151+
Even so, it would be nice to automatically rechunk to minimize number of cohorts detected, or to a perfectly blockwise application.
152+
A key limitation is that we have lost context.
153+
The string `"time.month"` tells me that I am grouping a perfectly periodic array with period 12; similarly
154+
the _string_ `"time.dayofyear"` tells me that I am grouping by a (quasi-)\_periodic array with period 365, and that group `366` may occur occasionally (depending on calendar).
155+
This context is hard to infer from integer group labels `[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]`.
156+
157+
One way to preserve context may be to use Xarray's new Grouper objects, and let them report ["preferred chunks"](https://github.com/pydata/xarray/blob/main/design_notes/grouper_objects.md#the-preferred_chunks-method-) for a particular grouping.
158+
This would allow a downstream system like `flox` or `dask-expr` to take this in to account later (or even earlier!) in the pipeline.
159+
That is an experiment for another day.

0 commit comments

Comments
 (0)