Skip to content

quantiles for repartitioning - #1261

Merged
mrocklin merged 20 commits into
dask:masterfrom
eriknw:repartition_quantiles
Jun 21, 2016
Merged

mrocklin merged 20 commits into
dask:masterfrom
eriknw:repartition_quantiles

Conversation

@eriknw

@eriknw eriknw commented Jun 9, 2016

Copy link
Copy Markdown
Member

See #1225

This calculates fewer quantiles than before, which will reduce the time required to merge the quantiles together. This is based on some hand-wavy heuristics, and we introduce some random percentiles to try to avoid certain types of pathologies. Give it a try!

This does not do a tree reduction to do merge-sorted, so there is still more gain to be had.

…tiles for repartitioning.

This calculates fewer quantiles than before, which will reduce the time required
to merge the quantiles together.  This is based on some hand-wavy heuristics, and
we introduce some random percentiles to try to avoid certain types of pathologies.
Give it a try!
@mrocklin

mrocklin commented Jun 9, 2016

Copy link
Copy Markdown
Member

Can you give some more intuition about the choices made here, ideally in a docstring rather than a github comment? Why is this faster? How do you choose to use fewer quantiles. Why the random percentiles Perhaps add tests for pathological cases? How does this differ from the current implementation? Does it handle all Pandas dtypes?

This requires us to calculate the len of series before we create percentiles.

Also, slightly reduce the number of random samples.
@eriknw

eriknw commented Jun 9, 2016

Copy link
Copy Markdown
Member Author

Certainly. In time.

@eriknw

eriknw commented Jun 9, 2016

Copy link
Copy Markdown
Member Author

Docstring added. Feedback (and testing) welcome.

@eriknw

eriknw commented Jun 9, 2016

Copy link
Copy Markdown
Member Author

btw, I won't have time today to investigate the test failure, test_set_partition_tasks_names.

I hope to change merge_percentiles to a reduction this weekend.

Should we introduce a user-facing knob, such as ddf.set_index(..., upsample=1.0), to allow a user to increase the total number of percentiles in case they're not content with the default behavior? Such a knob would probably be applicable for any approach we may come up with.

Comment thread dask/dataframe/core.py Outdated
len_dsk = dict(((name1, i), (len, key)) for i, key in enumerate(df._keys()))

total_name = 're-quantiles-len-' + token
total_dsk = {total_name: (sum, sorted(len_dsk))}

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.

So, this computation of the length will probably cause a lot of the intermediate results to stick around in RAM between computing the length and computing the percentiles. Keeping this stuff around hurts streamability a bit. How important is knowing the full length?

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.

Are there common cases that would not be handled well by assuming uniform partition length?

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.

Knowing the length is only important if there is high variance in the lengths of partitions (more specifically, if most of the values are in a very small percentage of partitions). We can assume approximately-uniform partition length if you prefer to avoid a full block.

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.

Assuming approximate-uniformity sounds very good to me

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.

Can we use the chunk length of a single partition? This is useful if num_percentiles > chunk_length.

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.

Dask.dataframe doesn't keep track of the lengths of partitions. We only know these once we're computing. Dask.dataframe differs from dask.array in this way.

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.

I know. In quantiles, we calculate the lengths of each partition and pass these to merge_percentiles. I would now like to use these lengths earlier in the calculation if it's cheap to do. I suppose I don't need to. I could push the check to a later function.

Are you saying you would like to avoid calculating the lengths separately? Do you want only a single function to operate on each dataframe, which would mean a function would return both the calculated percentile values and the length of a chunk?

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.

Calculating the total length has been removed. We still calculate lengths.

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.

Right, sorry, I thought you knew that and so was a bit confused by the question.

As written now we compute the lengths as we compute the percentiles and then pass both into a final reduction step. It's easy to do this in a single pass. The difference here is that we now compute all of the lengths, reduce over them, and then use this value to compute all of the percentiles. it looks a bit like this

df -- len --\             /  -- percentile
df -- len --\             /  -- percentile
              --- len  ---
df -- len --/             \  -- percentile
df -- len --/             \  -- percentile

We compute the partition, compute the lengths, but can't release the partitions because they'll be needed again in a bit to compute the percentile. We can't compute the percentiles until we've computed all of the lengths.

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.

No worries :)

Your concerns are valid. We were blocking in order to calculate the total length, which requires all the data to be loaded. The loaded data needs to persist, because it's used later by percentile.

I removed taking the total length (I was going to ask you about that anyway before you brought it up), so now we can load a single partition at a time and calculate its percentiles to completion before the next partition is loaded.

@mrocklin

mrocklin commented Jun 9, 2016

Copy link
Copy Markdown
Member

OK, just so I understand I think that the logic here is as follows:

  1. We want to reduce the number of quantiles computed on each partition so that the final merge operation (where we end up throwing away a lot of this anyway) is cheaper
  2. This causes bad behavior in the limit of large number of partitions because you may only have a few quantiles in each partition
  3. So we add in random quantiles to compensate and fuzz things out a bit in case all of the data is already pretty well aligned

As mentioned in the inline comment I'd like to avoid pre-computing length if possible. It changes this operation from single-pass to dual-pass.

My hope is that a tree reduction will significantly reduce costs here. I suspect that it'll change an O(n_k) operation to an O(log(n)_k) operation.

@eriknw

eriknw commented Jun 9, 2016

Copy link
Copy Markdown
Member Author

You understand correctly. Good summary.

Yes, a tree reduction should significantly reduce costs here. The first tasks to compute will probably be very fast (<1ms). Should I do a binary reduction for simplicity, which may result in more scheduler overhead, or should I allow it to be an N-ary tree?

@mrocklin

mrocklin commented Jun 9, 2016

Copy link
Copy Markdown
Member

I expect the optimal value of N to be greater than two but I'm actually not sure. Keeping this configurable might be interesting. N-ary reduction trees can be fun to build as well. toolz.partition_all and a while loop help a bit.

@eriknw

eriknw commented Jun 11, 2016

Copy link
Copy Markdown
Member Author

Merging percentiles for repartitioning is now a reduction. Dask is fun!

I'd say this PR is now in a state where others can experiment with it and give critical feedback. For example, I've given virtually no thought for where to put code or the tidiness and readability of the code--my first target was to get things working.

@mrocklin, the random percentiles is causing a test to fail, test_set_partition_tasks_names. set(ddf.set_index('x').dask) == set(ddf.set_index('x').dask) is no longer guaranteed, because the divisions will probably be different. How should we rectify this?

eriknw added 3 commits June 11, 2016 14:44
These were very linear and inter-dependent anyway, so we might as well make
the graph simpler and reduce the number of tasks.
@coveralls

Copy link
Copy Markdown

Coverage Status

Changes Unknown when pulling f0441b0 on eriknw:repartition_quantiles into * on dask:master*.

Comment thread dask/dataframe/core.py Outdated
prev_width = width
prev_keys = iter(keys)
level += 1
return rv

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.

Nice.

@mrocklin

Copy link
Copy Markdown
Member

OK, I think that next step is for me to try this out on a real cluster (probably sometime tomorrow.)

There is enough code here that I think it should probably live in a separate file so as not to muddy up core. After going through it once I still don't have a clear idea of exactly what's going on, which raises concerns of maintainability. Some combination of a strong module-level docstring or many more function-level docstrings are probably in order. I should probably test performance though before you make that time-investment.

@eriknw

eriknw commented Jun 12, 2016

Copy link
Copy Markdown
Member Author

Thanks for taking a look. I'm very interested how it'll perform on a cluster (both accuracy and speed). Don't be afraid to experiment with the upscale keyword (should this be user-facing?).

I'll create a new module. Sorry for still missing some docstrings. The approach should become very clear and intuitive with a little more documentation.

Unlike for merge_percentile in dask.array.percentile, I don't have special handling for categorical types yet. Also, the work in this PR is largely separate from the previous quantiles calculations and functions in dask.array.percentile, so Series.quantile can be scrapped if desired.

@coveralls

Copy link
Copy Markdown

Coverage Status

Changes Unknown when pulling bdc2899 on eriknw:repartition_quantiles into * on dask:master*.

Comment thread dask/dataframe/core.py Outdated
qs = np.linspace(0, 1, npartitions + 1)
# currently, only Series has quantile method
# Index.quantile(list-like) must be pd.Series, not pd.Index
merge_type = lambda v: pd.Series(v, index=qs, name=df.name)

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.

This fails in a distributed setting because df, a dask.dataframe, is closed over inside of a method being sent over a wire

@mrocklin

Copy link
Copy Markdown
Member

After making a fix to avoid closing over df.name this works quite well. I've attached a profile of the computation on a 10-node cluster of 80 cores. Red is data transfer.

image

@eriknw

eriknw commented Jun 15, 2016 •

Copy link
Copy Markdown
Member Author

TODO:

  • Fix closing over df.name
  • Move code to a new module
  • Add more documentation
  • Handle categoricals intelligently
  • Avoid creating empty partitions

@mrocklin, is there anything else you would like from this PR? Should I do anything with quantiles or the tests for quantiles? Should I make it easier for you to experiment with different tree strategies?

@mrocklin

Copy link
Copy Markdown
Member

Nothing else comes to mind. Because it's an internal function documentation can probably be just in-source documentation (docstrings, perhaps a module-level docstring) rather than external docs (though those would be cool too.)

@eriknw

eriknw commented Jun 15, 2016

Copy link
Copy Markdown
Member Author

Great. I may have time this evening to do this; if not, I'll have this wrapped up within a couple of days.

eriknw added 3 commits June 19, 2016 15:44
…r more efficient serialization.

Serialization with `cloudpickle` should now be 10-20x faster than before, but it is
still the dominant factor.  `cloudpickle` remains about 50x slower than `cPickle`.
@eriknw

eriknw commented Jun 19, 2016

Copy link
Copy Markdown
Member Author

@mrocklin (or maybe @jcrist), in the profile diagram above, where is the time spent doing serialization and deserialization: red, yellow, or empty space?

A couple days ago, @jcrist told me that cloudpickle is much slower than cPickle (in Python 2 parlance) when serializing native Python objects such as lists. I made a couple small tweaks in the last commit, so serialization should now be 10-20x faster than before, but cloudpickle is still up to 50x slower than cPickle. toolz performs merge_sorted faster than numpy, but performance is currently dominated by serialization. I wonder how a single reduction step that does rv = np.concatenate(results) ; rv.sort(axis=0) would perform. Another option would be to call cPickle.dumps manually if we know the dtype can be pickled safely. Optimizing further may be a moot point, though, since this should now be 10-20x faster.

@mrocklin

Copy link
Copy Markdown
Member

Serialization isn't shown in the profile plot (though we do keep track of those numbers. Usually it isn't that big of a deal.

The current policy is to try pickle before falling back on cloudpickle so we're already handling this decently. If you wanted things to be faster one next step might be to move things around as numpy arrays. However I'm not that concerned here:

In [1]: import pickle

In [2]: %time len(pickle.dumps(list(range(10000))))
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 1.78 ms
Out[2]: 29770

This is not non-trivial given the timescale, but it's also decently well spread across the cluster.

I think you're right that performance-wise we're doing pretty well here. We should verify that things are clean and nicely isolated and then probably merge.

@eriknw

eriknw commented Jun 19, 2016

Copy link
Copy Markdown
Member Author

Okay, great. The recent enhancements should still improve performance by 5-10x or so when using pickle, and I couldn't find a way to make things faster by using numpy arrays. I'll stop worrying about performance for now.

I'll clean and document today, and hopefully merge tomorrow.

@eriknw

eriknw commented Jun 19, 2016

Copy link
Copy Markdown
Member Author

Serialization isn't shown in the profile plot

Does that mean it's in the empty space? I'm not asking for serialization to be distinguished from calculations and data transfer; I'm wondering where it gets included.

@mrocklin

Copy link
Copy Markdown
Member

At the moment I believe that deserialization is in empty space and that serialization is likely part of the transfer time

rv = rv.astype(dtype)
# Should we try to fudge the result to avoid duplicates? After all,
# two smaller partitions is probably better than having an empty one.
return rv

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.

So, do you think we should fudge the final results to avoid duplicates and empty new partitions? I don't have a sense of how significant or common this may be, but we can certainly take steps in this function to avoid empty partitions.

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, avoiding non-empty partitions is good.

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.

Er, avoiding empty partitions...

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.

Done.

Comment thread dask/dataframe/partitionquantiles.py Outdated
)
duplicated_vals = vals[duplicated_index]
rv = np.concatenate([vals, duplicated_vals])
rv.sort()

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.

If we have too few samples to work with, is there an easy way for us to create the dask.dataframe with fewer partitions instead of knowingly creating empty partitions? Hmm, and I suppose we can use interpolation for number dtypes to estimate additional partition divisions.

@eriknw eriknw changed the title WIP: quantiles for repartitioning quantiles for repartitioning Jun 21, 2016
@eriknw

eriknw commented Jun 21, 2016

Copy link
Copy Markdown
Member Author

imho, I think this PR is ready for final review and merging. If non-critical changes are requested, I can make a new PR.

I can attest the existing tests are actually pretty good and were helpful during development. I plan to add a test to exercise these lines:
https://coveralls.io/builds/6688910/source?filename=dask%2Fdataframe%2Fpartitionquantiles.py#L330

@mrocklin

Copy link
Copy Markdown
Member

Reading now. After starting the intro module-level docstring I'm really looking forward to this.

grabs popcorn

@mrocklin

Copy link
Copy Markdown
Member

OK, to the extent that I'm able to verify in short time, this looks great to me. I have to admit though that I haven't given this the full consideration that it deserves. I plan to merge in the near future if there are no further comments.

At some point @eriknw you might write something up and put it out there for general community review. This might be novel work.

if str(data.dtype) == 'category':
data = data.codes
interpolation = 'nearest'
vals = _percentile(data, qs, interpolation=interpolation)

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.

A lingering thought: should we always use interpolation='nearest', which may behave more nicely with our simple compression step that combines equal values? Doing linear interpolation pretty much makes our compression step useless.

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.

No strong opinion from me. I don't think I have the experience here to make a good judgment.

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.

Aye, for floating point data, linear interpolation is probably fine. Using nearest with integer and datetime dtypes would probably compress much better. I'm fine keeping things as is for now.

@eriknw

eriknw commented Jun 21, 2016

Copy link
Copy Markdown
Member Author

Great!

I'm not sure how novel it is; then again, I don't think our particular scenario (which is sufficiently different from calculating approximate percentiles) comes up all that often. Given that we can compute percentiles cheaply, I just try to do the "obvious" thing combined with a large degree of paranoia that may or may not be justified, and then handle edge cases. Still, this could indeed be fun to write up, and I would welcome critical feedback and improvements.

@mrocklin

Copy link
Copy Markdown
Member

I would expect our need to quickly compute rough approximate percentiles to be shared by other computational systems. I think that the thought process that you went through and your solutions to real-world pathological cases may be of value to others doing similar things.

@mrocklin

Copy link
Copy Markdown
Member

Merging

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.

4 participants