Skip to content

map_partitions or map_blocks with large objects eats up scheduler memory #7860

Open

Description

@rikturr

Opening this report from investigation in dask/dask-ml#842 and dask/dask-ml#843

When passing some large objects as arguments to map_blocks / map_partitions, the scheduler memory can quickly be overwhelmed. Large objects should be wrapped in delayed to add them to graph and avoid this issue (see here) , but the way the object sizes are determined miss some large objects. In the cases I've encountered, it does not correctly compute the size of scikit-learn estimators.

This is because sys.getsizeof does not properly traverse object references to compute the "real" size of an object. This is a notoriously difficult thing to do in Python, so not sure what the best course of action here should be.

Minimal Complete Verifiable Example:

Running on machine with 2 cores and 16 GB of RAM

from dask_ml.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import pickle
import sys
import dask
from dask.distributed import Client

client = Client()

X, y = make_classification(
    n_samples=50000,
    chunks=1000,
    random_state=42,
)

rf = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
_ = rf.fit(X, y)


def dask_predict(part, model):
    return model.predict(part)

preds = X.map_blocks(
    dask_predict,
    model=rf,
    dtype="int",
    drop_axis=1,
)
preds.compute()

Scheduler memory ballons up to this:

image

And ends up with this error:

KilledWorker: ("('normal-dask_predict-4b858b85224825aeb2d45678c4c91d39', 27)", <WorkerState 'tcp://127.0.0.1:33369', name: 0, memory: 0, processing: 50>)

If we explictly delayed the rf object,

rf_delayed = dask.delayed(rf)
preds = X.map_blocks(
    dask_predict,
    model=rf_delayed,
    dtype="int",
    drop_axis=1,
    meta=np.array([1]),
)
preds.compute()

the memory use looks like this:

Screen Shot 2021-07-02 at 4 00 52 PM

Environment:

  • Dask version: 2021.5.1
  • Python version: 3.7
  • Operating System: ubuntu
  • Install method (conda, pip, source): conda

Activity

  1. jrbourbeau commented on Jul 2, 2021

    @jrbourbeau
    Member

    Thanks for the clear writeup @rikturr! Indeed it looks like we're underestimating the size of the RandomForestClassifier model in your example:

    In [1]: from sklearn.ensemble import RandomForestClassifier
    
    In [2]: rf = RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
    
    In [3]: from dask.sizeof import sizeof
    
    In [4]: sizeof(rf)
    Out[4]: 48

    One way to improve the situation is to register a custom sizeof implementation in dask/sizeof.py for scikit-learn estimators which more accurately captures the memory footprint of an estimator.

    One thing that comes to mind is to include information from estimator.get_params()

    In [5]: rf.get_params()
    Out[5]:
    {'bootstrap': True,
     'ccp_alpha': 0.0,
     'class_weight': None,
     'criterion': 'gini',
     'max_depth': None,
     'max_features': 'auto',
     'max_leaf_nodes': None,
     'max_samples': None,
     'min_impurity_decrease': 0.0,
     'min_impurity_split': None,
     'min_samples_leaf': 1,
     'min_samples_split': 2,
     'min_weight_fraction_leaf': 0.0,
     'n_estimators': 100,
     'n_jobs': -1,
     'oob_score': False,
     'random_state': 42,
     'verbose': 0,
     'warm_start': False}
    
    In [6]: sizeof(rf.get_params())
    Out[6]: 2604

    though there may be other attributes which are stored on the class, but not captured by get_params.

    cc @thomasjpfan as you might find this interesting

  2. rikturr commented on Jul 2, 2021

    @rikturr
    Author

    That would be great! I think there is more than in get_params, if you train the model then pickle the object and check that size it is much larger:

    In [2]: sys.getsizeof(rf), sys.getsizeof(pickle.dumps(rf))
    Out[2]: (64, 115509472)

    Another place this comes up is with xgboost and lightgbm, so would want to consider models from those libraries also

    Speaking of pickle, one idea might be to check the size of pickle.dumps(obj)

  3. stsievert commented on Jul 2, 2021

    @stsievert
    Member

    I think scikit-learn/scikit-learn#8642 tracks this issue for Scikit-Learn.

  4. thomasjpfan commented on Jul 2, 2021

    @thomasjpfan
    Contributor

    get_params only shows the parameters in __init__ which does not contain the fitted attributes in an estimator.

    I see a possible way forward to resolve this issue:

    1. Ensure all C/C++ objects in scikit-learn defines a __sizeof__. For this specific issue, define it for scikit-learn's tree data structure.
    2. Option 2a: Add a special case for BaseEstimator in https://github.com/dask/dask/blob/main/dask/sizeof.py with a register_lazy that calls sizeof on vars(estimator).
    3. Extra: The booster objects in xgboost and lightgbm would also need to define a __sizeof__. Since both libraries have a soft dependency on scikit-learn, they will get the benefit from Option 2a only when scikit-learn is installed.

    Option 2b: To support xgboost/lightgbm better, a more generic solution would be to ducktype the estimator:

    @sizeof.register(object)
    def sizeof_default(o):
        if hasattr(o, "get_params") and callable(o.get_params):
            # "estimator-like"
            return sizeof(vars(o))
        return getsizeof(o)

    (Would have been a little easier with Protocol but that requires Python>=3.8)

    What does everyone think of either Option 2a or 2b?

  5. jsignell commented on Jul 19, 2021

    @jsignell
    Member

    I prefer Option 2b. It seems like a good idea to do as well as we can with the sizeof estimation.

  6. added
    needs attention
    on Oct 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs attentionscheduler

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions