# Xarray MemoryError: with groupby workloads

**URL:** <https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273>\
**Category:** Uncategorized\
**Created:** [June 11, 2024, 9:07am UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273 "2024-06-11T09:07:11Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 11, 2024, 9:07am UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/1 "2024-06-11T09:07:11Z")

</div>

Hi,

I am working with piControl data from CMIP6 and handling 2000 years of daily data. While performing some analysis, I encountered memory error and am unable to write the result to a NetCDF file. The error message I received is as follows:

“MemoryError: Unable to allocate 176. GiB for an array with shape (730485, 180, 360) and data type float32”

To clarify, after the final calculation, there is only one value per year. Therefore, the final output shape would be (2000, 180, 360).

Any assistance or suggestions to resolve this issue would be greatly appreciated.

Thank you.

---

<div class="post-metadata">

**Author:** ![keewis](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/keewis/32/1106_2.png) [@keewis](https://discourse.pangeo.io/u/keewis)\
**Post date:** [June 11, 2024, 9:40am UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/2 "2024-06-11T09:40:55Z")

</div>

I suspect that’s because at some point during your calculations you accidentally load the entire data into memory.

To verify, try computing a single variable of the output shape (something like `result["variable"].compute()`). If this succeeds, you know that something goes wrong when writing to disk. However, if it fails (as I suspect), then that means that the issue is with the way you implemented your computation.

Either way, it would be great if you could post a (trimmed down) version of the code, as otherwise all we can do is guess.

---

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 11, 2024, 10:27am UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/3 "2024-06-11T10:27:16Z")

</div>

![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/5/5515fa94cd8136d1e4b1c6c0c79e5cb634162a06.png)

Please find the snippet of the code I used

---

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 11, 2024, 10:30am UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/4 "2024-06-11T10:30:34Z")

</div>

The calculation completes in 30 seconds until the `yearly_r95ptot` variable is calculated. The memory error occurs when I try to write the variable to a NetCDF file.

---

<div class="post-metadata">

**Author:** ![rabernat](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/rabernat/32/22_2.png) [@rabernat](https://discourse.pangeo.io/u/rabernat)\
**Post date:** [June 11, 2024, 1:17pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/5 "2024-06-11T13:17:46Z")

</div>

How much memory does your computer have?

---

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 11, 2024, 2:11pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/6 "2024-06-11T14:11:33Z")

</div>

The server has a total memory of around 251 GB.

---

<div class="post-metadata">

**Author:** ![jbusecke](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/jbusecke/32/118_2.png) [@jbusecke](https://discourse.pangeo.io/u/jbusecke)\
**Post date:** [June 11, 2024, 6:27pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/7 "2024-06-11T18:27:54Z")

</div>

I think you need to calculate `pn=...` inside the lambda (along the lines of

```auto
... lambda group: group.where(group > group.quantile(...)).sum(...)

```

Right now it seems like you generate very large arrays due to broadcasting in the `group > pn` call?  
I recommend inspecting each group manually, and I bet that `group.where(group > pn)` has the shape of the original array. In that case you would be trying to load `size(wet_days) * n_years` into memory.

---

<div class="post-metadata">

**Author:** ![jbusecke](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/jbusecke/32/118_2.png) [@jbusecke](https://discourse.pangeo.io/u/jbusecke)\
**Post date:** [June 11, 2024, 6:35pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/8 "2024-06-11T18:35:15Z")

</div>

@chaithra could you provide the particular model, grid, and other facets from the CMIP output your are working with? This would help us to look for the same data in the cloud and test this.

Perhaps you could just print the datasets attributes from your `file` datasets object here?

---

<div class="post-metadata">

**Author:** ![dcherian](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/dcherian/32/2235_2.png) [@dcherian](https://discourse.pangeo.io/u/dcherian)\
**Post date:** [June 11, 2024, 9:42pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/9 "2024-06-11T21:42:41Z")

</div>

Julius makes a key observation. If the quantile is indeed calculated on a per year basis, then this is a much simpler problem.

### First construct a dummy dataset

I’ve assumed that a month of daily data is in a single netCDF file:

```python
import dask.array
import numpy as np
import xarray as xr

ds = xr.Dataset(
    {
        "pr": (
            ("time", "lat", "lon"),
            dask.array.random.random(
                (730487, 180, 360),
                chunks=(30, -1, -1), # assuming one month per file
            ),
        )
    },
    coords={"time": xr.date_range("0001-01-01", "2000-12-31", freq="D")},
)
ds

```

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/2/20af816652116f38b51c0d5d4fde944c4ff81aad.png)

### Now rechunk to a yearly frequency

This is the key observation. Since you’re operating on a year of data at a time, you don’t need to rechunk to `time=-1` instead you can rechunk so that a year of data is in a single chunk. This rechunking is **required** for computing the quantile.

```python
# rechunk to yearly frequency
from xarray.groupers import TimeResampler

ds = ds.chunk({"time": TimeResampler(freq="AS")})
ds

```

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/c/c32399b76485231be341bdbb12d9330970bfd1d3.png)

^ EDIT: Use rechunking with a TimeResampler object.

### Now do your groupby.apply

```python
ds = ds.where(ds >= 1)
result = ds.groupby("time.year").apply(
    lambda group: group.where(group > group.quantile(q=0.95)).sum("time")
)
result

```

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/5/5ade2068299ff52c05c15e6f940925677b6f8027.png)

### This works quite well!

```python
result.compute()

```

![dask](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/e/ee1455d29dfbabd86124e52a97d979a8289fb4e8.gif)

---

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 12, 2024, 5:16am UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/10 "2024-06-12T05:16:18Z")

</div>

Model details: IPSL-CM6A-LR, piControl, r1i1p1f1.  
I have regridded the original grid into a 1x1 grid.

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/a/ad72d61f284907aec2801d7c821803c915901bb0.png)

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/7/77d0fe14bdf73b530f33279364b4d39940bdd86c.png)

---

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 12, 2024, 7:01am UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/11 "2024-06-12T07:01:44Z")

</div>

It’s working. Thank you! @dcherian  
The detailed explanation has been immensely helpful for my learning process.

---

<div class="post-metadata">

**Author:** ![rabernat](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/rabernat/32/22_2.png) [@rabernat](https://discourse.pangeo.io/u/rabernat)\
**Post date:** [June 12, 2024, 12:30pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/12 "2024-06-12T12:30:55Z")

</div>

Amazing answer Deepak!

I think it’s worth asking–what could we do at the API level to make things “just work” more automatically? What @chaithra wants to do is pretty standard. Yet the tricks required to make it succeed are obscure and only obvious to experts.

---

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 12, 2024, 1:00pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/13 "2024-06-12T13:00:36Z")

</div>

Hi,

I would like to get your suggestions on improving the performance of my calculations.

To my understanding, your code uses yearly 95th percentile values as a threshold. I want to compute the climatological 95p values instead of the yearly values. Please see the attached snapshot. Unfortunately, the process is significantly slower than expected.

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/6/67fd6433260a89baaf631f1906600d3fba8b9a31.png)

Could you suggest any methods to speed up this process? I would greatly appreciate any guidance or suggestions you could provide.

Thank you very much for your time and assistance.

---

<div class="post-metadata">

**Author:** ![dcherian](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/dcherian/32/2235_2.png) [@dcherian](https://discourse.pangeo.io/u/dcherian)\
**Post date:** [June 12, 2024, 2:45pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/14 "2024-06-12T14:45:04Z")

</div>

> [@chaithra](#):
>
> the process is significantly slower than expected.

What is “expected” here?

Your screenshot with `chunksize=(182621,180, 360)` is concerning. That’s only 4 chunks in the whole array, which limits the amount of parallelism you can use (with dask at least). Where is this chunksize coming from? How many days or months or years data are stored in a single netCDF file?

---

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 12, 2024, 3:22pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/15 "2024-06-12T15:22:35Z")

</div>

That screenshot was taken before applying chunks. Just to clarify, my chunk size is (365, 180, 360) as in your example.

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/e/ef98a65d22fe4f681204719f9aec4143bf6b90f3.png)

A single NetCDF file from this model contains 500 years of daily data.

---

<div class="post-metadata">

**Author:** ![dcherian](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/dcherian/32/2235_2.png) [@dcherian](https://discourse.pangeo.io/u/dcherian)\
**Post date:** [June 12, 2024, 3:47pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/16 "2024-06-12T15:47:03Z")

</div>

> A single NetCDF file from this model contains 500 years of daily data.

Right. This is probably the issue. Specify `chunks={"time": 365}` in `open_mfdataset`. You should see increased parallelism after that.

---

<div class="post-metadata">

**Author:** ![chaithra](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/chaithra/32/2890_2.png) [@chaithra](https://discourse.pangeo.io/u/chaithra)\
**Post date:** [June 12, 2024, 5:54pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/17 "2024-06-12T17:54:03Z")

</div>

Yes, it made the code work really fast. Thanks!

 ![image](https://canada1.discourse-cdn.com/flex030/uploads/pangeo/original/2X/8/8a67b519c6a618b492dccb5910ea81a07c8c8379.png)

However, writing the result to netcdf seems a bit slow.

---

<div class="post-metadata">

**Author:** ![rabernat](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/rabernat/32/22_2.png) [@rabernat](https://discourse.pangeo.io/u/rabernat)\
**Post date:** [June 13, 2024, 1:28pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/18 "2024-06-13T13:28:26Z")

</div>

Try writing to Zarr instead!

---

<div class="post-metadata">

**Author:** ![dcherian](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/dcherian/32/2235_2.png) [@dcherian](https://discourse.pangeo.io/u/dcherian)\
**Post date:** [August 23, 2024, 4:48pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/19 "2024-08-23T16:48:51Z")

</div>

With latest Xarray you can now [rechunk to a frequency](https://docs.xarray.dev/en/stable/user-guide/dask.html#chunking-and-performance) quite easily

```auto
from xarray.groupers import TimeResampler

ds = ds.chunk(time=TimeResampler(freq="AS"))

```

---

<div class="post-metadata">

**Author:** ![Michael\_Sumner](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/michael_sumner/32/1608_2.png) [@Michael\_Sumner](https://discourse.pangeo.io/u/Michael_Sumner)\
**Post date:** [August 24, 2024, 11:33pm UTC](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273/20 "2024-08-24T23:33:59Z")

</div>

when does setting chunks get materialized? It confuses me that this gets set at read time or as a property of an object (I can’t find out how to do this properly for a multi-file input that I want different chunk sizes for in a Zarr I create). I expect it to be a property at _write time_, and that doesn’t seem to be the case. Is this described somewhere in examples? (I’m struggling with the documentation about what’s the right thing to do. Thanks!).

[Next page](https://discourse.pangeo.io/t/xarray-memoryerror-with-groupby-workloads/4273.md?page=2)
