Skip to content

dataframe.read_parquet() cannot cope with more than 2^16-valued categories  #5112

Closed

Description

@maowerner

I want to use dask to read parquet files with categorical data from disk. Below is a minimal complete verifyable example.

The issue as far as I understand it is that with engine='fastparquet' no data types larger than int16 are used for encoding categories (?). The same code works completely fine with a smaller number of categorical values.

Using the 'pyarrow' engine will just convert the data back to non-categorical. Furthermore, I did not manage to make it work with pandas' datetime[ns].

There are workarounds. I can obviously just not use category when writing the parquet file and call `dd.dataframe.categorize() afterwards, but I would really like to save the factor 2-3 in disk space.

Is that actually an issue in dask or do I need to ask the people over at pandas / fastparquet?
fastparquets typemap includes uint64, so I don't see why this should not work.

import numpy as np

numbers = np.random.randint(0, 80000, size=1000000)
import pandas as pd

df = pd.DataFrame(numbers.T, columns=['name'])
df.name = df.name.astype('category')
df.to_parquet('parquet_int16.parq', engine='fastparquet', compression='uncompressed')
import dask.dataframe as dd

ddf = dd.read_parquet('parquet_int16.parq', engine='fastparquet')
ddf.compute()
---------------------------------------------------------------------------

RuntimeError                              Traceback (most recent call last)

<ipython-input-41-1abf416ad30b> in <module>
      2 
      3 ddf = dd.read_parquet('parquet_int16.parq', engine='fastparquet')
----> 4 ddf.compute()


~/anaconda3/lib/python3.7/site-packages/dask/base.py in compute(self, **kwargs)
    154         dask.base.compute
    155         """
--> 156         (result,) = compute(self, traverse=False, **kwargs)
    157         return result
    158 


~/anaconda3/lib/python3.7/site-packages/dask/base.py in compute(*args, **kwargs)
    396     keys = [x.__dask_keys__() for x in collections]
    397     postcomputes = [x.__dask_postcompute__() for x in collections]
--> 398     results = schedule(dsk, keys, **kwargs)
    399     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    400 


~/anaconda3/lib/python3.7/site-packages/dask/threaded.py in get(dsk, result, cache, num_workers, pool, **kwargs)
     74     results = get_async(pool.apply_async, len(pool._pool), dsk, result,
     75                         cache=cache, get_id=_thread_get_id,
---> 76                         pack_exception=pack_exception, **kwargs)
     77 
     78     # Cleanup pools associated to dead threads


~/anaconda3/lib/python3.7/site-packages/dask/local.py in get_async(apply_async, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, **kwargs)
    460                         _execute_task(task, data)  # Re-execute locally
    461                     else:
--> 462                         raise_exception(exc, tb)
    463                 res, worker_id = loads(res_info)
    464                 state['cache'][key] = res


~/anaconda3/lib/python3.7/site-packages/dask/compatibility.py in reraise(exc, tb)
    110         if exc.__traceback__ is not tb:
    111             raise exc.with_traceback(tb)
--> 112         raise exc
    113 
    114     import pickle as cPickle


~/anaconda3/lib/python3.7/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)
    228     try:
    229         task, data = loads(task_info)
--> 230         result = _execute_task(task, data)
    231         id = get_id()
    232         result = dumps((result, id))


~/anaconda3/lib/python3.7/site-packages/dask/core.py in _execute_task(arg, cache, dsk)
    117         func, args = arg[0], arg[1:]
    118         args2 = [_execute_task(a, cache) for a in args]
--> 119         return func(*args2)
    120     elif not ishashable(arg):
    121         return arg


~/anaconda3/lib/python3.7/site-packages/dask/dataframe/io/parquet.py in _read_parquet_row_group(fs, fn, index, columns, rg, series, categories, schema, cs, dt, scheme, storage_name_mapping, *args)
    504     df, views = _pre_allocate(rg.num_rows, columns, categories, index, cs, dt)
    505     read_row_group_file(fn, rg, columns, categories, schema, cs,
--> 506                         open=fs.open, assign=views, scheme=scheme)
    507 
    508     if df.index.nlevels == 1:


~/anaconda3/lib/python3.7/site-packages/fastparquet/core.py in read_row_group_file(fn, rg, columns, categories, schema_helper, cats, open, selfmade, index, assign, scheme)
    303         return read_row_group(f, rg, columns, categories, schema_helper, cats,
    304                               selfmade=selfmade, index=index, assign=assign,
--> 305                               scheme=scheme)
    306 
    307 


~/anaconda3/lib/python3.7/site-packages/fastparquet/core.py in read_row_group(file, rg, columns, categories, schema_helper, cats, selfmade, index, assign, scheme)
    352         raise RuntimeError('Going with pre-allocation!')
    353     read_row_group_arrays(file, rg, columns, categories, schema_helper,
--> 354                           cats, selfmade, assign=assign)
    355 
    356     for cat in cats:


~/anaconda3/lib/python3.7/site-packages/fastparquet/core.py in read_row_group_arrays(file, rg, columns, categories, schema_helper, cats, selfmade, assign)
    329         read_col(column, schema_helper, file, use_cat=name+'-catdef' in out,
    330                  selfmade=selfmade, assign=out[name],
--> 331                  catdef=out.get(name+'-catdef', None))
    332 
    333         if _is_map_like(schema_helper, column):


~/anaconda3/lib/python3.7/site-packages/fastparquet/core.py in read_col(column, schema_helper, infile, use_cat, grab_dict, selfmade, assign, catdef)
    209             raise RuntimeError('Assigned array dtype (%s) cannot accommodate '
    210                                'number of category labels (%i)' %
--> 211                                (assign.dtype, len(dic)))
    212 
    213     rows = cmd.num_values


RuntimeError: Assigned array dtype (int16) cannot accommodate number of category labels (80000)

Activity

  1. jrbourbeau commented on Jul 18, 2019

    @jrbourbeau
    Member

    Thanks for raising this issue @maowerner, I'm able to reproduce the RuntimeError with your example

    cc @martindurant @TomAugspurger

  2. martindurant commented on Jul 18, 2019

    @martindurant
    Member

    This is a deliberate optimisation in fastparquet, restricting the dtype and memory usage of category labels, which perhaps is no longer necessary. The parameter categories can be used to work around it (seen in a number of methods and functions):

        categories: list, dict or `None`
    
            If a column is encoded using dictionary encoding in every row-group
            and its name is also in this list, it will generate a Pandas
            Category-type column, potentially saving memory and time. If a
            dict {col: int}, the value indicates the number of categories,
            so that the optimal data-dtype can be allocated. If ``None``,
            will automatically set *if* the data was written from pandas.
    

    So if you specify the column with the large number of labels with an appropriately large number (e.g., 2**31), you should be able to fit them.

    Note that the parquet reader infrastructure is changing, so please check back with us shortly to see exactly how you would phrase the extra argument in the new framework (@rjzamora ).

  3. maowerner commented on Jul 18, 2019

    @maowerner
    Author

    Thank you very much for the fast reply!

    Indeed

    ddf = dd.read_parquet('parquet_int16.parq', engine='fastparquet', categories={'name':80000})
    

    works out of the box.

    Note that the parquet reader infrastructure is changing, so please check back with us shortly to see exactly how you would phrase the extra argument in the new framework (@rjzamora ).

    I will stay tuned

  4. rjzamora commented on Jul 18, 2019

    @rjzamora
    Member

    @maowerner - Thanks for raising this! You should get the same behavior after PR#4995 goes through (I just added something lsimilar to your example as a test).

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions