Skip to content

Infer arrow schema in to_parquet (for ArrowEngine) - #6490

Merged
martindurant merged 11 commits into
dask:masterfrom
rjzamora:schema-inference
Aug 17, 2020
Merged

martindurant merged 11 commits into
dask:masterfrom
rjzamora:schema-inference

Conversation

@rjzamora

@rjzamora rjzamora commented Aug 6, 2020 •

Copy link
Copy Markdown
Member

Closes #6243

As of the 1.0 release, pyarrow now (understandably) compains when you try to compose a shared _metadata file from partitions with inconsistent schemas. This PR adds a public schema argument to to_parquet (although it is only used by the ArrowEngine).

By default (if the user does not specify an actual arrow schema), this new argument is set to "sample", which means the client will find the first partition with data, and use the head of this partition to infer the global arrow schema. The user can also pass schema="meta" to use the _meta_nonempty for inference, or schema=None to allow the backend (pyarrow) to infer the schema for each output partition separately.

The advantage of using "sample" over "meta" as the default is that we are much less likely to set an incorrect global schema. For example, using "meta" will not correcly detect the difference between string and binary (they are both "object" types in _meta_nonempty). The obvious disadvantage is the need to sample "real" data (requiring worker-client data transfer in a distributed environment).

Given the competing factors described above: Do we want to infer the schema by default? An alternative to the current solution is to set the default to None, and only perform inference (via sampling) if the user passes schema="infer"

As stated in a comment below, the following approach is now used:

  • The default is now schema=None. However, if/when pyarrow fails to write the _metadata, we "handle" the exception by also recommending that the user try "schema="infer"` (or to pass an explicit schema).
  • The user can now pass in a dict with only a subset of column-types included (similar to "object_encoding")
  • When schema="infer" or when the user passes in a dict, we start with an inital schema based on the _meta_nonempty. For schema="infer", we further sample partitions for non-null data to update the "object" fields. For the dict, we only update the fields specified by the user.
  • Tests added / passed
  • Passes black dask / flake8 dask

@martindurant

Copy link
Copy Markdown
Member

It's rather similar to the "object_encoding=" argument from fastparquet, i.e., specify the parquet encoding type only for specific object-type columns, or for all object columns in general. This still works today, I think

I also think that there is an opportunity for the dataframe meta to carry more information than the basic pandas dtypes. That would be a deeper change, but worth thinking about. On the other hand, the object type may be increasingly superseded by specific extension types that would provide more obvious behaviour.

@rjzamora

rjzamora commented Aug 6, 2020

Copy link
Copy Markdown
Member Author

It's rather similar to the "object_encoding=" argument from fastparquet, i.e., specify the parquet encoding type only for specific object-type columns, or for all object columns in general. This still works today, I think

This comparison makes sense. I just updated the PR to do things a bit differently:

  • The default is now schema=None. However, if/when pyarrow fails to write the _metadata, we "handle" the exception by also recommending that the user try "schema="infer"` (or to pass an explicit schema).
  • The user can now pass in a dict with only a subset of column-types included (similar to "object_encoding")
  • When schema="infer" or when the user passes in a dict, we start with an inital schema based on the _meta_nonempty. For schema="infer", we further sample partitions for non-null data to update the "object" fields. For the dict, we only update the fields specified by the user.

@rjzamora

rjzamora commented Aug 7, 2020 •

Copy link
Copy Markdown
Member Author

cc @jorisvandenbossche and @TomAugspurger (Since you may have thoughts here)

@TomAugspurger TomAugspurger 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.

Makes sense to me, thanks.

@davesque

davesque commented Aug 10, 2020 •

Copy link
Copy Markdown

Just thought I'd pop in here and say that I've personally run into cases where using pa.Schema.from_pandas(_meta_nonempty) doesn't give a good result. In my particular case, it resulted in an object-typed date column being represented by a string in the arrow schema. So I've cooked up a modified workaround for this issue that begins with a schema of entirely null-typed columns. Then, it fills in the column types with non-null types from sequentially evaluated partitions as is done in this PR. Here's a little demonstration of the issue I'm talking about:
Screen Shot 2020-08-10 at 11 17 26 AM

@davesque

davesque commented Aug 10, 2020 •

Copy link
Copy Markdown

And because I sort of left it out, here's my modified workaround for this problem:

import dask.dataframe as dd
import pyarrow as pa

NULL_TYPE = pa.null()

def get_nonnull_schema_for_dataframe(df: dd.DataFrame) -> pa.Schema:
    schema = pa.schema([pa.field(c, NULL_TYPE) for c in df.columns])
    for i in range(df.npartitions):
        part_df = df.get_partition(i)
        if len(part_df):
            _schema = pa.Schema.from_pandas(part_df.compute())
            for name, typ in zip(_schema.names, _schema.types):
                if typ != "null":
                    i = schema.get_field_index(name)
                    j = _schema.get_field_index(name)
                    schema = schema.set(i, _schema.field(j))
        has_null_col = NULL_TYPE in [f.type for f in schema]
        if not has_null_col:
            break
    if has_null_col:
        raise ValueError("cannot infer schema with no null-type columns")
    return schema

@martindurant

Copy link
Copy Markdown
Member

Having to "get" each partition of a dataframe into the client is likely prohibitive for most large datasets. You could do the same work in the workers, but could still means two passes of the data for a write.
I guess it makes sense if we are asserting that columns should not be null type, and we will find out the true type from the first one or two partitions.

@davesque

Copy link
Copy Markdown

Having to "get" each partition of a dataframe into the client is likely prohibitive for most large datasets. You could do the same work in the workers, but could still means two passes of the data for a write.
I guess it makes sense if we are asserting that columns should not be null type, and we will find out the true type from the first one or two partitions.

My assumption is that the reason @rjzamora is looking at doing it this way is because the necessary information to determine the correct arrow type is simply not statically available in the dask dataframe's metadata. Is that correct? If so, it seems like there's no avoiding inspecting the data or at least enough data to determine a concrete type for each column. For most datasets, I would hope that this is possible by only computing a small fraction of the partitions.

@martindurant

Copy link
Copy Markdown
Member

@davesque , yes of course you are right. I wanted to get the caveat in ahead. This kind of thing would need to be user specified, I think.

@rjzamora

Copy link
Copy Markdown
Member Author

@davesque - Are you saying the solution in this PR fails for your example? (sorry - I'm not really at my computer long enough to check)

@martindurant - With this PR, we will only sample partitions for "object" columns if the user specifies schema="infer". Agreed that we don't want sampleing to be the default. Does this sound reasonable?

@martindurant

Copy link
Copy Markdown
Member

@rjzamora yes, I agree with your approach, I was merely sounding out. Your code is mostly the same. I do wonder at this line, is compute on the whole partition necessary, shouldn't we push the from_pandas to the worker?

@rjzamora

Copy link
Copy Markdown
Member Author

@rjzamora yes, I agree with your approach, I was merely sounding out. Your code is mostly the same. I do wonder at this line, is compute on the whole partition necessary, shouldn't we push the from_pandas to the worker?

Ah - Thats a good point.

@davesque

davesque commented Aug 10, 2020 •

Copy link
Copy Markdown

@davesque - Are you saying the solution in this PR fails for your example? (sorry - I'm not really at my computer long enough to check)

Yes, and sorry I didn't include a demonstration of exactly how this was failing for me. This notebook gist contains an error that's being thrown in pyarrow.pandas_compat when the inferred arrow type string can't be reconciled with the datetime.date value in the dataframe: https://gist.github.com/davesque/f1be14bb8fe93fbc83186ec6a84c3b81

@rjzamora

Copy link
Copy Markdown
Member Author

Yes, and sorry I didn't include a demonstration of exactly how this was failing for me. This notebook gist contains an error that's being thrown in pyarrow.pandas_compat when the inferred arrow type string can't be reconciled with the datetime.date value in the dataframe: https://gist.github.com/davesque/f1be14bb8fe93fbc83186ec6a84c3b81

Hmm - In this PR, we will start with the _meta_nonempty-based schema, but will then sample the partitions for "object"-typed columns (and replace those fields). Therefore, I would expect it to work fine for th datetime case (since it will be an "object" type in the metadata).

@davesque

davesque commented Aug 10, 2020 •

Copy link
Copy Markdown

Right but as I pointed out, the dtype in _meta_nonempty for the "date" column ends up being string. So it never gets filled in with the correct date32[day] arrow type and just ends up using the string arrow type. And then that fails because the internals of pyarrow expect a string or bytes object when writing the actual values to disk for a string type column. Maybe there's an issue with the code that produces the _meta_nonempty dataframe?

Update: Actually, I guess I didn't point out the issue with _meta_nonempty explicitly but that's the reason why we end up incorrectly with the string arrow type.

@rjzamora

Copy link
Copy Markdown
Member Author

Right but as I pointed out, the dtype in _meta_nonempty for the "date" column ends up being string

Oops - This shouldn't be the case - there was a bug in my code (the set method does not operate in place, so I we need the explicit assignment).

@davesque

Copy link
Copy Markdown

Right but as I pointed out, the dtype in _meta_nonempty for the "date" column ends up being string

Oops - This shouldn't be the case - there was a bug in my code (the set method does not operate in place, so I we need the explicit assignment).

Ahh, funny. Yeah I remember running into that issue and correcting it in my version. But maybe I didn't realize it was the real root problem.

@davesque

Copy link
Copy Markdown

@rjzamora Although won't it also cause issues that you're checking specifically for "object" type columns? So anything that is marked as "string" in _meta_nonempty will be ignored?

sample = [col for col in df.columns if df[col].dtype == "object"]

@davesque

davesque commented Aug 10, 2020 •

Copy link
Copy Markdown

Actually, I guess it won't technically be ignored since it may appear in a partition that you compute. However, if it does not appear in one of those partitions, it won't get the right data type. This is because the sample object in your code doesn't track "string" type columns so that they would end up getting resolved by a partition-derived schema.

So I think you still need to resolve those columns somehow so the issue with the wrong data type in _meta_nonempty doesn't trickle down to the pyarrow lib. That's why I just went with resolving all column types from evaluated partitions instead of starting with _meta_nonempty which seems to contain weird dtypes.

@jorisvandenbossche jorisvandenbossche 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.

The general approach looks good to me!

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

Copy link
Copy Markdown
Member Author

@rjzamora Although won't it also cause issues that you're checking specifically for "object" type columns? So anything that is marked as "string" in _meta_nonempty will be ignored?

I may be confused here. For me, the arrow schema starts off with a "string" field for the datetime example,because the _meta_nonempty will always have string-like data. However, since the pandas dataframe has an "object" dtype, that column should be included in sample. Are you saying there will be an issue when the pandas dtype is "string"? I don't see how that case relates to the datetime example. (Note that I am not particularly knowledgeable about pandas dtypes, so I'm sorry if I am missing something basic)

@davesque

Copy link
Copy Markdown

@rjzamora Actually, you're totally right! Sorry! I forgot that the date column in my example still has dtype "object" so it will be resolved to a data type in an evaluated partition by your code. Never mind! Yeah, the issue was just that you weren't setting the schema back into the var.

@davesque davesque left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sorry to inject myself again into this discussion :). I just had a thought about the last update I saw so I thought I'd share. Feel free to ignore.

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

Copy link
Copy Markdown
Member Author

@martindurant - Thanks for your help with this. Let me know if you have any other thoughts/concerns

@martindurant
martindurant merged commit d3a179b into dask:master Aug 17, 2020
@jsignell

Copy link
Copy Markdown
Member

It looks like there are failures on master after this merge:

==================================== ERRORS ====================================
___________ ERROR collecting dask/dataframe/io/tests/test_parquet.py ___________
dask/dataframe/io/tests/test_parquet.py:1077: in <module>
    "schema", ["infer", {"index": pa.string(), "amount": pa.int64()}]
E   AttributeError: 'bool' object has no attribute 'string'
___________ ERROR collecting dask/dataframe/io/tests/test_parquet.py ___________
dask/dataframe/io/tests/test_parquet.py:1077: in <module>
    "schema", ["infer", {"index": pa.string(), "amount": pa.int64()}]
E   AttributeError: 'bool' object has no attribute 'string'
___________ ERROR collecting dask/dataframe/io/tests/test_parquet.py ___________
dask/dataframe/io/tests/test_parquet.py:1077: in <module>
    "schema", ["infer", {"index": pa.string(), "amount": pa.int64()}]
E   AttributeError: 'bool' object has no attribute 'string'

From: https://travis-ci.org/github/dask/dask/jobs/718654946

@martindurant

martindurant commented Aug 17, 2020 •

Copy link
Copy Markdown
Member

It looks like this is the arrow-not-installed case. The test ought to have been skipped.

@martindurant

Copy link
Copy Markdown
Member

#6524

kumarprabhu1988 pushed a commit to kumarprabhu1988/dask that referenced this pull request Oct 29, 2020
* infer schema for to_parquet in ArrowEngine

* make sampling more thorough (when necessary)

* handle dict input for schema

* add test coverage for dict input and update docstring

* handle pre-0.15 pyarrow

* missing assignment

* missing assignment

* fix test

* improve docstring

* get schema on worker

* avoid lambda
@rjzamora
rjzamora deleted the schema-inference branch May 21, 2024 00:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

to_parquet failing on pyarrow master when different partitions result in different parquet schema

6 participants