Skip to content

dask dataframe from delayeds of dask dataframes #8042

Closed

Description

@NativeVex

tl;dr Can we please add (or could someone explain how this is already possible) creating dask dataframes from a function that returns a list of delayed(dd.DataFrame) without evaluating all the delayed(dd.DataFrame)s in the list? I'm okay with passing metadata up the chain.

I've been using dask to interact with sqlalchemy queries and to distribute larger-than-memory outputs with the pd.from_sql function with the chunksize argument, like the following:
sub_df = dd.from_delayed([ client.scatter(x) for x in pd.read_sql(compiled_str_qry, engine, chunksize=chunksize)])
This works well, and distributes my pandas dataframes over a k8s cluster without overloading any single worker's memory.

When I try to request only a part of the SQL query, I rely on sqlalchemy's limit and offset. This doesn't have ideal performance characteristics, but when working on a CTE I expect it to outperform loading the entire dataset in some cases. I've been hoping to use something of a mixed-methods approach to load the entire database as a dask dataframe, but it's proving to be difficult namely due to the fact that you can't get a dask dataframe from a list of delayed(dd.DataFrames).

It's desirable in my use case for the ability to have a set of sqlalchemy queries that partition the resultant query CTE into chunks based on the limit/offset, and then to stitch the output of those functions (a dask dataframe, to allow for greater than memory queries) into a representative dataframe that contains all of them together. This would allow for lazy-loading of chunks of SQL, as the scheduler finds it appropriate. It would also allow for dropping whole tasks without having to re-request all the data at once. I believe this'd be good for resilience, whereas for the alternative of just loading the entire SQL query in one go, the scheduler would need to re-run that singular task, without the ability to discern which part failed.

Please let me know what you think! I'm personally not fluent enough in dask to make this happen, but there are a couple reasons I think this could be done: given I'm using a limit in SQL, I know the upper limit of the size that the dataframe will occupy (I know the exact size of all but the last dataframe), and that there's the to_delayed and from_delayed interface. If there is a function that operates on delayeds, it should stand to reason it'd be possible to splice a set of delayeds into that list in place (to replace?) one of them on evaluation.

Activity

  1. jsignell commented on Aug 17, 2021

    @jsignell
    Member

    Hi @NativeVex thanks for opening this issue. It would definitely help to have an example of the type of workflow that you have tried. I am imagining something like:

    import dask
    import dask.dataframe as dd
    
    ddfs = [dask.datasets.timeseries(start=f"2021-{m}-01", end=f"2021-{m+1}-01", freq="1H") for m in range(1, 12)]
    ddf = dd.concat(ddfs)

    Is that similar to what you have? In that case you can use dd.concat or dd.merge depending on how your data are divided up.

  2. added
    needs info
    on Aug 17, 2021
  3. NativeVex commented on Aug 18, 2021

    @NativeVex
    Author

    I wrote up a more generalizable demo of my use case, substituting communicating with sqlalchemy with selecting ranges from dask.datasets.timeseries.

    import dask
    import dask.dataframe as dd
    import pandas as pd
    from dask.distributed import Client, LocalCluster
    from dask import delayed
    from typing import List
    
    cluster = LocalCluster(n_workers=2, threads_per_worker=1, memory_limit="4GB")
    client0 = Client(cluster)
    
    
    def sql_limit_to_larger_than_memory(y: int) -> dd.DataFrame:
        # In my use case this talks to sql, but here we can just as easily talk to
        # dask.datasets
        from dask.distributed import get_client  # type: ignore
        from distributed.client import Future
    
        set_of_futures: List[Future] = []
        client = get_client()
        for m in range(1, 12):  # here I'd loop over pd.read_sql(qry, engine, chunksize)
            small_packet: pd.DataFrame = dask.datasets.timeseries(
                start=f"{y}-{m}-01", end=f"{y}-{m+1}-01", freq="1H"
            ).compute()[:500]
            # I know exactly the size of each item here, without evaluating every iteration
            # In my case this is due to the offset-limit slicing of sql I do
            set_of_futures.append(client.scatter(small_packet))
        df: dd.DataFrame = dd.from_delayed(set_of_futures)
        # Creating this list of futures allows me to distribute the 'small_packet'
        # chunks of data over many workers. Here I pretend that a month of
        # timeseries data is a significant amount of data that a worker can hold,
        # and that it would be impractical for a single worker to hold a whole year
        # of data at once.
        return df
    
    
    set_of_dataframes = [
        delayed(sql_limit_to_larger_than_memory)(y) for y in range(2000, 2021)
    ]
    # Here I construct a list of functions that could be called to retrieve
    # specific ranges from my sql database. I'd trust the dask scheduler to make
    # the appropriate decisions on if my operation should call them or not.
    # Presumably if I just want to use a .sample, it could avoid certain
    # partitions.
    
    # problem area: (desired functionality)
    overarching_df = dd.from_delayed(set_of_dataframes) # runs ok
    overarching_df.head() # does not run ok
    
    # proving that the approach makes sense
    sql_limit_to_larger_than_memory(2001).head()
    # This would be analogous to asking just for the year 2001 to be loaded into
    # dask's memory, and distributed among the workers in a reasonable manner. This
    # is much kinder on my network and on the computer hosting the workers than
    # loading the whole dataset at once.

    I'm hoping to avoid dd.concat and dd.merge, as in this case it would require the list of delayeds to be computed one by one, and that would defeat the purpose of delaying the function. Unfortunately, the for loop within sql_limit_to_larger_than_memory must exist within that function, as pd.read_sql, when called with chunksize returns an iterator. I do not believe it is currently possible to delay individual partitions of the output of an iterator, and so this would be my only option.

    The reason I mention metadata is because I know that dask stores metrics regarding the dataframes it constructs by sampling each function. If I as the user know the metadata, I'd be glad to offer it to dask instead of having it call every single one of my delayed functions. Equivalently, I'd be okay with setting constraints on my function sql_limit_to_larger_than_memory to force it to have a pre-defined number of rows/columns matching all the other data. This could be similar to passing additional information in dd.read_csv's 'dtypes' argument.

    I also know that dataframes can be made to and from lists of delayeds, and I think it'd be neat if those could be nested. This use case is just recursively nesting delayeds in dataframe constructs. I figured this would be better as it preserves more metadata. If dataframes can equivalently be expressed as a list of delayeds + metadata, it should be possible to modify the dd.from_delayed function to accept delayed(functions) that return a list or dataframe (both consisting of delayed items) and have them splice those in as needed, similar to the following code:

    # input previously generated 'overarching_df'
    def splice_dereferenced_delayed_item(
        df: dd.DataFrame, index_to_deref: int
    ) -> dd.DataFrame:
        # it would make sense for this to undo .from_delayed
        x: List[Delayed] = dd.to_delayed()
    
        # pretend that it does, and substitute set_of_dataframes from the previous code
        # x = set_of_dataframes # uncomment me to get the code to run
    
        # hit the actual db here
        dereferenced_data: dd.DataFrame = x[index_to_deref].compute()
    
        # presumably refers to the small partitions on each worker
        list_of_delayeds_to_splice: List[Delayed] = dereferenced_data.to_delayed()
    
        new_list_of_delayeds = (
            x[:index_to_deref] + list_of_delayeds_to_splice + x[1 + index_to_deref :]
        )
    
        # We're replaced the delayed(of a function that returns delayeds) with the
        # constituent delayeds the function returns, effectively splicing the
        # result in.
        return dd.from_delayed(new_list_of_delayeds)

    I have no idea if this is possible given the current implementation, but if nothing else am eager to see where my understanding falls short.

    Thanks for taking the time to look at my issue!

  4. jsignell commented on Aug 18, 2021

    @jsignell
    Member

    Thanks for the extra details that is really helpful! I was going to suggest that you do this hackish thing with map_partitions where you set up an empty dataframe with exactly the partitions that you want and then you fill it in using map_partitions. Something like this:

    import dask
    import dask.dataframe as dd
    import pandas as pd
    from dask.distributed import Client, LocalCluster
    from dask import delayed
    from typing import List
    
    cluster = LocalCluster(n_workers=2, threads_per_worker=1, memory_limit="4GB")
    client0 = Client(cluster)
    
    def sql_limit_to_larger_than_memory(df) -> dd.DataFrame:
        # In my use case this talks to sql, but here we can just as easily talk to
        # dask.datasets
        from dask.distributed import get_client  # type: ignore
        from distributed.client import Future
    
        y = df.index.item()
        set_of_futures: List[Future] = []
        client = get_client()
        for m in range(1, 12):  # here I'd loop over pd.read_sql(qry, engine, chunksize)
            small_packet: pd.DataFrame = dask.datasets.timeseries(
                start=f"{y}-{m}-01", end=f"{y}-{m+1}-01", freq="1H"
            ).compute()[:500]
            # I know exactly the size of each item here, without evaluating every iteration
            # In my case this is due to the offset-limit slicing of sql I do
            set_of_futures.append(client.scatter(small_packet))
        return dd.from_delayed(set_of_futures)
    
    # get just a little bit of data to give dask a hint about what this thing looks like 
    y, m = 2000, 1
    meta = dask.datasets.timeseries(start=f"{y}-{m}-01", end=f"{y}-{m+1}-01", freq="1H").compute()[:5]
    
    # construct an empty dataframe
    empty_df = pd.DataFrame(index=range(2000, 2021))
    empty_ddf = dd.from_pandas(empty_df, npartitions=len(empty_df))
    
    # use make partitions to directly set the data on each partition using the output of the function. 
    ddf = empty_ddf.map_partitions(sql_limit_to_larger_than_memory, meta=meta, enforce_metadata=False)
    ddf.head()

    But then I saw that what you want is a dataframe that contains dask dataframes in each of its partitions. I am not quite sure what the value of that is, dask is not set up to understand that kind of nesting.

    The more I thought about this the more I want to recommend that you look at https://github.com/intake/fsspec-reference-maker . Here's a quick description.

    Sorry for the incomplete response. Just wanted to let you know what I am thinking :)

  5. NativeVex commented on Aug 21, 2021

    @NativeVex
    Author

    Very cool! I've understood the link to mean I should be offloading my data to a bucket, and that's worked very well for the limited trial run I've done. Also I believe the documentation might be out of date here- https://docs.dask.org/en/latest/remote-data-services.html claims that you can use 'gcs.session.credentials,' but gcs.credentials.credentials is the only thing that's worked for me as of right now.

    Please keep me in the loop as things develop- I'd be eager to make more advanced usage of dask's delayed interface, and I think it'll likely be the main pipeline people use for data ingress.

    Thanks for the pointers!

  6. ncclementi commented on Oct 14, 2021

    @ncclementi
    Member

    @NativeVex it seems this issue is resolved by the recommendation of offloading data to a bucket. Thanks for pointing out the documentation issue, but that one seems unrelated to this issue. I will close this issue (if you think this is not resolved, feel free to re-open), but would you mind opening a separate issue explaining what you experience with 'gcs.session.credentials,'.

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

    dataframeneeds info

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions