Skip to content

Large memory increase and processing slowness during graph creation #7851

Closed

Description

@chrisroat

What happened:

When creating a graph consisting of delayed dataframes created from 20k image blocks, the memory climbs into 10+ gigabytes and it takes several minutes to create. No execution of graph is done. I experimented with fewer blocks, and the performance is quite non-linear. The processing time and memory taken up (measured via GKE jupyterhub pod memory usage) by number of blocks:

1000  =>   3s
2000  =>   9s
4000  =>  28s, 0.6GB
8000  =>  93s, 2.4GB
16000 => 324s, 9.1GB

What you expected to happen:

I expected 20k blocks this to fit under a minute and under a gigabyte. I also expected linear performance with number of blocks, as the blocks are independent (as can be verified by .visualize(..) on a single dataframe)

Minimal Complete Verifiable Example:

Scaled down example with 8k blocks, which is enough to demonstrate the memory growth. My actual dataset has 20k blocks, roughly 3TB divided into 150MB blocks -- but the problem seems to be purely a function of block count, not datasize.

import dask
import dask.array as da
import dask.dataframe as dd
import numpy as np

image = da.zeros(8000, dtype=np.uint16, chunks=1)
block_iter = zip(np.ndindex(*image.numblocks), image.to_delayed().flatten())

ddf_all = np.empty(image.numblocks, dtype=object)
for idx_chunk, chunk in block_iter:
    ddf_delayed = dask.delayed(lambda x: None)(chunk)
    ddf_all[idx_chunk] = dd.from_delayed(ddf_delayed, meta=[("z", np.float32)]) 

Environment:

  • Dask version: 2021.06.2
  • Python version: 3.8.10
  • Operating System: Ubuntu 18.04
  • Install method (conda, pip, source): conda

Activity

  1. rikturr commented on Jul 2, 2021

    @rikturr

    I think this is the same thing happening in #7860

  2. chrisroat commented on Jul 2, 2021

    @chrisroat
    ContributorAuthor

    @rikturr Thanks for pointing out the issue. In my case there is no scheduler involved -- I was running into OOM Kills on my client job during graph construction. I now give my client jobs 45GB of memory per core!

  3. chrisroat commented on Aug 13, 2021

    @chrisroat
    ContributorAuthor

    I verified this is still true in 2021.7.2.

    There are an enormous number of calls to highlevelgraph getitem, and I suspect it may be falling back to the O(n) branch. From prun:

             339976721 function calls (339640711 primitive calls) in 94.208 seconds
    
       Ordered by: internal time
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     64008000   39.405    0.000   49.203    0.000 highlevelgraph.py:738(__getitem__)
    40004/24004   19.524    0.000   78.100    0.003 {method 'update' of 'dict' objects}
    128016000   12.791    0.000   12.791    0.000 highlevelgraph.py:559(__getitem__)
        80000    4.022    0.000    4.022    0.000 flags.py:47(__init__)
     64040002    3.475    0.000    3.508    0.000 _collections_abc.py:719(__iter__)
     64024008    2.791    0.000    2.791    0.000 {method 'values' of 'dict' objects}
    ...
    

    And from pyinstrument.

    Program: slow_graph.py
    
    91.950 <module>  <string>:1
    └─ 91.950 run_path  runpy.py:242
       └─ 91.950 _run_module_code  runpy.py:90
          └─ 91.950 _run_code  runpy.py:64
             └─ 91.950 <module>  slow_graph.py:1
                └─ 90.279 from_delayed  dask/dataframe/io/io.py:554
                   ├─ 76.491 merge  toolz/dicttoolz.py:18
                   │  ├─ 47.944 __getitem__  dask/highlevelgraph.py:738
                   │  │  ├─ 37.249 [self]  
                   │  │  ├─ 7.293 __getitem__  dask/highlevelgraph.py:559
                   │  │  └─ 3.401 dict.values  <built-in>:0
                   │  ├─ 19.977 keys  dask/highlevelgraph.py:779
                   │  │  └─ 19.973 to_dict  dask/highlevelgraph.py:771
                   │  │     └─ 19.949 ensure_dict  dask/utils.py:1096
                   │  │        ├─ 10.008 [self]  
                   │  │        ├─ 6.162 __getitem__  dask/highlevelgraph.py:559
                   │  │        └─ 3.675 __iter__  _collections_abc.py:719
                   │  │           └─ 3.668 [self]  
                   │  └─ 8.407 [self]  
                   ├─ 11.074 make_meta  dask/dataframe/dispatch.py:88
                   │  └─ 10.956 make_meta_object  dask/dataframe/backends.py:87
                   │     └─ 10.015 __init__  pandas/core/frame.py:573
                   │        └─ 9.908 dict_to_mgr  pandas/core/internals/construction.py:396
                   │           ├─ 5.320 __getitem__  pandas/core/series.py:928
                   │           │  └─ 5.053 _get_values  pandas/core/series.py:1024
                   │           │     └─ 4.840 __init__  pandas/core/series.py:315
                   │           │        └─ 4.803 __init__  pandas/core/generic.py:230
                   │           │           └─ 4.795 [self]  
                   │           ├─ 1.665 __init__  pandas/core/series.py:315
                   │           │  └─ 1.041 _init_dict  pandas/core/series.py:451
                   │           └─ 1.494 arrays_to_mgr  pandas/core/internals/construction.py:100
                   │              └─ 0.945 create_block_manager_from_arrays  pandas/core/internals/managers.py:1756
                   └─ 2.501 new_dd_object  dask/dataframe/core.py:6862
                      └─ 2.468 __init__  dask/dataframe/core.py:3869
                         └─ 1.885 __init__  dask/dataframe/core.py:319
                            └─ 1.228 is_dataframe_like  dask/dataframe/utils.py:323
                               └─ 1.218 is_dataframe_like  dask/utils.py:1219
                                  └─ 1.166 <genexpr>  dask/utils.py:1224
                                     └─ 1.146 dtypes  pandas/core/generic.py:5621
    
  4. chrisroat commented on Aug 14, 2021

    @chrisroat
    ContributorAuthor

    @GenevieveBuckley Given your expertise in HighLevelGraphs and your interest in alternatives when creating non-arrays from chunked arrays, I thought this would be of interest. Do you have any tips in how we might avoid this behavior when returning delayed dataframes?

    Similar code that returns delayed arrays does not have this problem. I suspect something can be done in dd.from_delayed with the merge, but I'm not familiar with what is happening here.

  5. GenevieveBuckley commented on Aug 16, 2021

    @GenevieveBuckley
    Contributor

    My first suggestion was going to be to remove the delayed within a delayed, since that's something recommended against in the docs (you have image.to_delayed() passed into another delayed function later on). But when I change that in a notebook I still see an exponential increase in time taken to construct the graph, so that can't be the whole story.

    I don't see the same memory climb as you do (I'm running Ubuntu 20.04). Watching the system monitor, the memory and swap history stays pretty consistent, although during graph creation I do see a single CPU thread max itself out for a bit, then drop back to zero while another CPU thread maxes out for a bit, etc.

    It's definitely the from_delayed part that's causing the trouble. I'd try moving that out of the loop.

  6. GenevieveBuckley commented on Aug 16, 2021

    @GenevieveBuckley
    Contributor

    @chrisroat take a look at the way I've structured https://github.com/dask/dask-image/pull/240/files and see if that helps you here (less pleasantly, perhaps you can tell us if we'll run into problems with large numbers of chunks with that PR too)

        if label_image.dtype.char not in np.typecodes['AllInteger']:
            raise ValueError("find_objects only accepts integer dtype arrays")
    
        block_iter = zip(
            np.ndindex(*label_image.numblocks),
            map(functools.partial(operator.getitem, label_image),
                da.core.slices_from_chunks(label_image.chunks))
        )
    
        arrays = []
        for block_id, block in block_iter:
            array_location = _array_chunk_location(block_id, label_image.chunks)
            arrays.append(delayed(_find_bounding_boxes)(block, array_location))
    
        bag = db.from_sequence(arrays)
        result = bag.fold(functools.partial(_find_objects, label_image.ndim), split_every=2).to_delayed()
        meta = dd.utils.make_meta([(i, object) for i in range(label_image.ndim)])
        result = delayed(compute)(result)[0]  # avoid the user having to call compute twice on result
        result = dd.from_delayed(result, meta=meta, prefix="find-objects-", verify_meta=False)
  7. GenevieveBuckley commented on Aug 16, 2021

    @GenevieveBuckley
    Contributor

    When I do this the memory leak is observable. If the chunk size is changed to 1000 instead of 1 it runs (there are many fewer chunks overall in that scenario)

    import operator
    import functools
    import dask
    import dask.array as da
    import dask.bag as db
    import dask.dataframe as dd
    import numpy as np
    import pandas as pd
    
    image = da.zeros(8000, dtype=np.uint16, chunks=1)
    
    block_iter = zip(
        np.ndindex(*image.numblocks),
        map(functools.partial(operator.getitem, image),
            da.core.slices_from_chunks(image.chunks))
    )
    
    ddf_all = np.empty(image.numblocks, dtype=object)
    
    for idx_chunk, chunk in block_iter:
        ddf_delayed = dask.delayed(lambda x: pd.DataFrame(np.random.random(5)))(chunk)
        ddf_all[idx_chunk] = ddf_delayed
    
    bag = db.from_sequence(ddf_all)
    result = bag.map(dd.from_delayed, meta=[(0, np.float64)])
    # things seem ok until now...
    
    # memory leak observable
    for i in result:
        print(i)
  8. chrisroat commented on Aug 16, 2021

    @chrisroat
    ContributorAuthor

    Thanks for helping out. I see what you are saying about the recommendation of not using delayed-in-delayed, though I'm not sure if the problem I'm seeing is related to that recommendation (though it may be).

    I have this pattern (of creating dataframes from chunks) several places in my codebase, and most times I do defer the from_delayed until outside the loop. In those cases, I want the dataframes concatenated. But in this case I do actually need each dataframe separate and stored in the array structure, as each one is rejoined later to chunks laid out in the same pattern. (It's actually more complex that than -- the array is 5 dimensional, and the frames along one dimension of the array are concatenated before the rejoin)

    The final graph here is very simple (it is separable by chunk, and each chunk's subgraph is just a few tasks), so I believe this is something that should be possible without so much time/memory. My understanding of the code is that there is a quadratic effect where each chunk carries information about all other chunks -- and the HLG merging seems to be doing a double loop while looking up keys.

    If it's not obvious what the problem may be, I can look and see if my code can be restructured. The restructuring would be unfortunate, as it may make the APIs a bit messy, but it would be worth it for performance. I just don't know if that restructuring might have similar performance issues.

  9. GenevieveBuckley commented on Aug 16, 2021

    @GenevieveBuckley
    Contributor

    Maintainers, do we know who our experts are on dask delayed? (I don't think there's a project team list I can ping here)

  10. jsignell commented on Aug 19, 2021

    @jsignell
    Member

    Hmm, not sure if there is a specific expert, but there have been some roughly related issues. Specifically #7922 and #8042

  11. chrisroat commented on Aug 20, 2021

    @chrisroat
    ContributorAuthor

    Thanks for pointing out those issues, @jsignell . It looks like #7922 is related to arrays iterating via blocks, which is similar to this, but here the iterate is via delayed (or in following @GenevieveBuckley , using numpy slicing). And #8042 is requesting some sort of new functionality in computation, while this issue is around graph construction only -- not computation.

    My investigation has led me to realize that a block of an array seems to have a pointer back to the high-level-graph of the original array, which has all the keys for all the chunks. When the dd.from_delayed happens on a chunk, it is trying to merge the HLGs. This leads to a loop over all those underlying keys. Because this is done for each chunk, this leads to an N^2 behavior -- hence you see some functions being called 10s or 100s of millions of times in the profiles.

    The HLG getitem is falling down to the O(n) lookup because the keys have a "delayed-" prefix, whereas the layer keys do not have this -- it has to go into the values themselves to find the "delayed-" prefixed items.

    I think this requires someone with knowledge of delayed (in particular, dataframes) and HLGs, and how they should be interacting.

  12. chrisroat commented on Sep 27, 2021

    @chrisroat
    ContributorAuthor

    The fix by #8174 by @gjoseph92 fixed this issue. In my testing, the 8000 block reproducer finished in <8s with minimal memory usage.

  13. gjoseph92 commented on Sep 27, 2021

    @gjoseph92
    Collaborator

    Ah that makes sense, every from_delayed probably had to materialize and merge the full un-culled graph of the array. Nice! I had no idea I was fixing this.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions