Skip to content

Add aggregate_files argument to enable multi-file partitions in read_parquet - #7557

Merged
jsignell merged 48 commits into
dask:mainfrom
rjzamora:multi-file-partitions
Jul 15, 2021
Merged

jsignell merged 48 commits into
dask:mainfrom
rjzamora:multi-file-partitions

Conversation

@rjzamora

@rjzamora rjzamora commented Apr 13, 2021 •

Copy link
Copy Markdown
Member

This PR adds a new aggregate_files parameter to dask.dataframe.read_parquet. This enables chunksize= to aggregate both row-groups and/or files into each output partition. We also add an optional read_partition_multi class method to the Engine, allowing the backend (i.e. arrow and/or cudf) to perform file/row-group aggregation in a way that is (much) more efficent than concatenating pandas DataFrame objects.

Current aggregate_files docstring:

    aggregate_files : bool or str, default None
        Whether distinct file paths may be aggregated into the same output
        partition. This parameter is only used when `chunksize` is specified.
        A setting of True means that any two file paths may be aggregated into
        the same output partition, while False means that inter-file aggregation
        is prohibited.

        For "hive-partitioned" datasets, a "partition"-column name can also be
        specified. In this case, we allow the aggregation of any two files
        sharing a file path up to, and including, the corresponding directory name.
        For example, if ``aggregate_files`` is set to ``"section"`` for the
        directory structure below, ``03.parquet`` and ``04.parquet`` may be
        aggregated together, but ``01.parquet`` and ``02.parquet`` cannot be.
        If, however, ``aggregate_files`` is set to ``"region"``, ``01.parquet``
        may be aggregated with ``02.parquet``, and ``03.parquet`` may be aggregated
        with ``04.parquet``::

            dataset-path/
            ├── region=1/
            │   ├── section=a/
            │   │   └── 01.parquet
            │   ├── section=b/
            │   └── └── 02.parquet
            └── region=2/
                ├── section=a/
                │   ├── 03.parquet
                └── └── 04.parquet

        Note that the default behavior of ``aggregate_files`` is False.

Note that this PR currently sets the default behavior of aggregate_files to False. However, here is the motivation to aggregate files by default for partitioned datasets:

dask.datasets.timeseries(
    start='2000-01-01',
    end='2000-02-28',
    freq='1s',
    partition_freq='1h',
    seed=42,
).to_parquet(
    path,
    engine="pyarrow",
    partition_on="name",
    write_index=False,
)

# Traditional read of 36k partitions.
# Takes >4.5 minutes on my machine:
dd.read_parquet(path, engine="pyarrow").compute()

# Aggregation into 26 partitions.
# Takes <30 seconds on my machine:
dd.read_parquet(path, engine="pyarrow", chunksize="1G",  aggregate_files="name").compute()

Note: With dask_cudf, since cudf can read multiple files on the same GPU in parallel, this time goes down to 3 seconds.

rapids-bot Bot pushed a commit to NVIDIA/cudf that referenced this pull request May 3, 2021
This PR loosens some fragile assumptions in dask_cudf's `test_parquet.py::test_chunksize`.

**More context**: This change is in preparation for [dask#7557](dask/dask#7557), which will change the behavior of the `chunksize` argument in `dask.dataframe.read_parquet`.  Further changes will be required in dask_cudf to enable (optimal) multi-file partition aggregation, but this PR should avoid any temporary CI failures.

Authors:
  - Richard (Rick) Zamora (https://github.com/rjzamora)

Approvers:
  - Keith Kraus (https://github.com/kkraus14)

URL: #8108
@MrPowers

Copy link
Copy Markdown
Contributor

@rjzamora - those sound like some juicy performance gains 🚀

Any way I can help with this PR? Want me to pull down this branch and see if I can reproduce those performance gains on my machine?

@rjzamora

Copy link
Copy Markdown
Member Author

Any way I can help with this PR? Want me to pull down this branch and see if I can reproduce those performance gains on my machine?

It would be great to have you try it out :)

I actually had this PR on the top of my priority list for next week. I think the only sticking point is the question of how to set the maximum granularity of aggregation. For example, users may only want to aggregate within files, or they may want to aggregate within a directory, or maybe within a specific group of directories. I am wondering if there is a clean way to expose a simple knob for the user to turn.

@rjzamora
rjzamora marked this pull request as ready for review May 27, 2021 14:35
@randerzander

Copy link
Copy Markdown

Any way I can help with this PR? Want me to pull down this branch and see if I can reproduce those performance gains on my machine?

It would be great to have you try it out :)

I actually had this PR on the top of my priority list for next week. I think the only sticking point is the question of how to set the maximum granularity of aggregation. For example, users may only want to aggregate within files, or they may want to aggregate within a directory, or maybe within a specific group of directories. I am wondering if there is a clean way to expose a simple knob for the user to turn.

I could see two patterns being of immediate use:

  1. dd.read_parquet([['/sub1/fn1', '/sub1/fn2'], ['/sub2/fn1'], ['/sub3/*']])

A list of lists of all files/path expressions which should be read. When users have skewed file sizes, they sometimes write custom logic to concatenate specific files to approximate either evenly sized partitions, or logically distinct partitions.

  1. Allow Dask to coalesce files in specified subdir level:

Dir structure:

2021-05-27/
├── 01
│   ├── 01.parquet
│   └── 02.parquet
└── 02
    ├── 03.parquet
    └── 04.parquet

dd.read_parquet('2021-05-27/*/*', coalesce_depth=1)

In the above example, with coalesce_depth=1, it'd be fair game for you to merge 01.parquet and 02.parquet into one partition, and 03.parquet and 04.parquet into another partition.

This would be basically in line with reading a partitioned dataset but where you specify what "level" of partition beneath which you want to allow Dask to merge files.

Comment thread dask/dataframe/io/parquet/core.py Resolved
@rjzamora

Copy link
Copy Markdown
Member Author

Thank you for the suggestions and feedback @randerzander - I'm sorry our efforts to design a reasonable API overlapped a bit!

I definitley started with an approach that was very similar to the coalesce_depth idea. However, I shifted to the chunksize=(<size>, <range>) approach after finding that something like that would require a lot more changes throughout the read_parquet code base than I originally anticipated. The current implementation isolates most of the logic within a single shared utility aggregate_row_groups, and doesn't add any new arguments to read_parquet. This makes the current PR relatively simple, but also means that there are obvious limitations. For example, it may be true that the user doesn't care about the output partitions meeting a specific chunksize target. Int that case, it would be nice to be able to perform aggregation/coelescence without parsing/processing any parquet statistics.

@fjetter fjetter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding the API, this feels like the right direction. I left one or two questions which probably result in a no-op but otherwise this looks good to me. I think everything else can be iterated on later.


A very subjective comment I cannot actually back up but the introduced complexity seems to be a lot while there are only a few added unit tests. However, they are parameterised so we might actually cover everything? idk. this might be a time for a coverage report :)
Nothing I've seen seemed very controversial but it is practically impossible to review all for/if conditions without actually diving into the code myself with a debugger, therefore I trust the tests. This is mostly a question of "can you come up with any more weird edge cases we might want to include in the tests?" if the answer is no, that's fine with me until the first bugs come in :)

However, I would also like to expand this PR to enable file aggregation when split_row_groups is set to an integer >1.

May I suggest to hold on with this? The PR is already uncomfortably large. That sounds like something you can put into a follow up PR.

Comment thread dask/dataframe/io/parquet/core.py Resolved
Comment thread dask/dataframe/io/parquet/core.py Resolved
Comment thread dask/dataframe/io/parquet/core.py Resolved
Comment thread dask/dataframe/io/parquet/core.py Resolved
Comment thread dask/dataframe/io/parquet/arrow.py Outdated
# Check/correct order of `categories` using last file_frag
cat_keys = [
o.split(" =")[0]
for o in re.findall("[^(]* =", str(file_frag.partition_expression))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd love to see something like this live in upstream

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is exactly my sentiment. Unfortunately, the exposed API and partitioning information is far from consistent between the three supported engines. This inconsistency is the reason I originally went with the general regex approach for specifying an aggregation range.

At this point, I am sort of throwing up my hands. It seems like we need to do something messy like this to produce a reasonable API. Other ideas are welcome :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, this affects only arrow, doesn't it? I agree that arrow might not want to expose the exact signature we're requiring here but IIUC this function is something like an aggregation of filepath encoded data.

A=1/B=2/data.parquet
A=4/B=2/data.parquet

I am struggling a bit to parse what the expected output would be for that simple example but I expect something like

{
    "A=1/B=2/data.parquet": ["A", "B"],
    "A=4/B=2/data.parquet": ["A", "B"],
}

or

{
    "A=1/B=2/data.parquet": [1, 2],
    "A=4/B=2/data.parquet": [4, 2],
}

Maybe a short example in the doc string would be helpful. imho, nomenclature is not sufficiently aligned and I always get confused when reading about 'categories', 'fragments', 'partitions', etc.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, this affects only arrow, doesn't it?

Yes, thats right - I was conflating this specific change with a larger challenge I was facing :)

I agree that this specific logic should live in pyarrow. There is currently a (private) _get_partition_keys utility to convert the "partition expression" into a list of "keys". However, the result is not ordered in the way we need it to be, hence this custom/ugly logic. @jorisvandenbossche may be able to comment, but I suspect I should just raise a jira/pyarrow issue about it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We still have open https://issues.apache.org/jira/browse/ARROW-8655 to better expose the partitioning information. Concrete suggestions on what information you want to have accessible in which way is always welcome.

However, the result is not ordered in the way we need it to be, hence this custom/ugly logic

Ah, that's useful feedback, that might be an easy change in pyarrow (the implementation in C++ is currently using an unordered map, I notice. I suppose we can change that to something that preserves the order).


About the specific code line this is commenting on: I would suggest to not rely on the repr of the partition expression (that seems rather brittle, and I can't guarantee any stability for the display of an expression). As an alternative short-term work-around, can you do something similar on the file path?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note that this regex does not allow ( in the category names. For "proper" dataset formats I would expect this to not be an issue since the paths are likely encoded, e.g. url encoded, and ( might be forbidden but it could pop up and this regex would return nonsense.

@rjzamora rjzamora Jul 6, 2021 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

About the specific code line this is commenting on: I would suggest to not rely on the repr of the partition expression (that seems rather brittle, and I can't guarantee any stability for the display of an expression). As an alternative short-term work-around, can you do something similar on the file path?

I agree that it is not ideal to depend on the repr. We can use the file path for now, but that is also a bit tricky. Does anyone know if the following would work for both linux and windows?...

        cat_keys = [
            o.split("=")[0]
            for o in re.findall(f"[^{fs.sep}]*=", str(file_frag.path))
        ]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fsspec has a make_posix_path which normalizes / or \, but not sure if that's a public function.

But I also think that file_frag.path will always return normalized paths (using /) even on Windows. So hardcoding "[/]*=" in the regex could also work.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it's public, but "/" is the only variant that gets used in practice. Note that "/" paths always work on any OS (python has some in-built hidden windows stuff to do this, and we can rely on it).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if in doubt, you can also use smth like os.path.split which should resolve properly for win/linux but is likely slower

Comment thread dask/dataframe/io/tests/test_parquet.py Resolved
@jsignell

Copy link
Copy Markdown
Member

In case you are curious @fjetter you can see the coverage changes in https://app.codecov.io/gh/dask/dask/compare/7557

@fjetter

fjetter commented Jun 22, 2021

Copy link
Copy Markdown
Member

Thanks for the coverage link. The diff itself seems to be mostly covered but there are a few big gaps in the overall logic, in particular for arrow / split_row_groups (https://app.codecov.io/gh/dask/dask/compare/7557/changes#D3L292) obviously out of scope for this PR but very informative ;)

@rjzamora

rjzamora commented Jul 1, 2021

Copy link
Copy Markdown
Member Author

@fjetter @dask/io - Let me know if there are any remaining thoughts/concerns here. I think it is good to go. Note that I recently changed the default aggregate_files to be False - This is less efficient for hive-partitioned data, but it avoids changes in down-stream behavior for now (e.g. I found that tests were failing in NVTabular).

@fjetter fjetter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left a final note about the regex but that isn't a blocker. I think the edge case I'm mentioning there is rare enough to justify moving forward, especially since arrow might include a better functionality in the future.

I would suggest that if any bigger things pop up, we should move these changes to a dedicated PR and lock this PR in terms of scope.

If nobody, else has more to say, I'm good.

Thanks @rjzamora for your hard work, I just realised this PR has been open since April! Good job and thanks for completing it!

@jorisvandenbossche

Copy link
Copy Markdown
Member

I would only still change the regex to be based on eg the file path, instead of the repr of the expression, if possible.


In the meantime, related to #7557 (comment), I updated the JIRA https://issues.apache.org/jira/browse/ARROW-8655 with some more concrete thoughts and a draft PR to expose more information: apache/arrow#10661. If I can get some feedback on it, we might be able to get it into pyarrow 5.0.

@rjzamora

rjzamora commented Jul 8, 2021

Copy link
Copy Markdown
Member Author

Okay - Now that the unrelated CI failures are resolved, this PR should be good to go.

@jsignell

Copy link
Copy Markdown
Member

Seems like once the conflict is resolved we can merge :)

@rjzamora

Copy link
Copy Markdown
Member Author

grrr - looks like test_create_metadata_file is a legitimate failure. I'll look into it.

@rjzamora

Copy link
Copy Markdown
Member Author

grrr - looks like test_create_metadata_file is a legitimate failure. I'll look into it.

Yikes - That took a while to track down. It seems that the new approach requires us to reset the row_groups attribute on a fastparquet ParquetFile object, and this can sometimes fail when the _set_attrs() logic is called with multiple threads. Adding a lock seems to fix the problem. @martindurant - Does this sound reasonable?

Side note: In the past, we have already been "resetting" the row-groups. However, we were also explicitly passing in the row-group metadata at IO, so these threading errors haven't caused any problems until now.

@martindurant

Copy link
Copy Markdown
Member

A ParquetFiles certainly does use its row_groups while doing _set_attrs() (perhaps only to get the paths for partition values). It would not surprise me if calling that from multiple threads on the same instance, and also mutating the row_goups , might end up with an inconsistent state.

Instead of using a lock, can we not do a (shallow) copy.copy() of the ParquetFile and/or fmd? In fact, I am surprised that each thread doesn't get an independent copy of the instance anyway.

@rjzamora

Copy link
Copy Markdown
Member Author

@dask/maintenance - I'm hoping this is ready, and I'd like to see it get in early in the release cycle :)

@jsignell

Copy link
Copy Markdown
Member

Sounds good to me. Merging...

@jsignell
jsignell merged commit 7f38c0a into dask:main Jul 15, 2021
rapids-bot Bot pushed a commit to NVIDIA/cudf that referenced this pull request Jul 21, 2021
Depends on [dask#7557](dask/dask#7557)

This PR updates `dask_cudf.read_parquet` to enable multi-file aggregation when the `chunksize` parameter is used.  This change enables dramatic (>50x) improvements when the dataset contains many small files, which is somewhat common for hive/directory-partitioned data.

**Motivating Example**

```python
dask.datasets.timeseries(
    start='2000-01-01',
    end='2000-02-28',
    freq='1s',
    partition_freq='1h',
    seed=42,
).to_parquet(
    path,
    engine="pyarrow",
    partition_on="name",
    write_index=False,
)

####
#### BEFORE THIS PR ####
####

# Without useing `chunksize`, or  when using `chunksize` before this PR
# results in 36,192 partitions
%time df_read = dask_cudf.read_parquet(path)
CPU times: user 1.17 s, sys: 501 ms, total: 1.67 s
Wall time: 1.67 s

# Without useing `chunksize`, or  when using `chunksize` before this PR
# results in a 5+ minute read time
%time df_read.compute()
CPU times: user 5min 34s, sys: 37.1 s, total: 6min 11s
Wall time: 6min 12s

####
#### AFTER THIS PR ####
####

# Using `chunksize` WITH this PR results in 26 partitions
%time df_read = dask_cudf.read_parquet(path, chunksize="1GB", aggregate_files="name")
CPU times: user 1.03 s, sys: 119 ms, total: 1.15 s
Wall time: 1.15 s

# Using `chunksize` WITH this PR results in a ~95x speedup
%time df_read.compute()
CPU times: user 3.18 s, sys: 703 ms, total: 3.88 s
Wall time: 3.92 s
```

Authors:
  - Richard (Rick) Zamora (https://github.com/rjzamora)

Approvers:
  - Devavret Makkar (https://github.com/devavret)
  - Benjamin Zaitlen (https://github.com/quasiben)

URL: #8393
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants