Repository navigation
PERF Speed-up _weighted_percentiles when n_percentiles > 1 - #35079
jeremiedbb wants to merge 4 commits into
Conversation
cakedev0
left a comment
There was a problem hiding this comment.
Thanks!
That's a nice viz!! I'll remember it.
Note that this PR also fixes a bug: on main, average=True fails with array_api_strict as soon as a column has a zero weight "plus one":
X = xp.asarray([[1.], [2.], [3.]]); w = xp.asarray([[1.], [0.], [1.]])
_weighted_percentile(X, w, 50, average=True)
# main: IndexError: Integer index arrays are only allowed with integer indices; got (Array(0, dtype=array_api_strict.int64), Ellipsis).It'd be nice to cover this in the tests: test_weighted_percentile_array_api_consistency never uses average=True, and test_weighted_percentile_ignores_zero_weight only uses scalar percentiles (the new vectorized zero-weight branch with e.g. percentile_rank=[0, 50, 100] isn't tested).
| zero_weight_cols = [ | ||
| col_idx for col_idx in range(n_features) if has_zero_weight[col_idx] | ||
| ] |
There was a problem hiding this comment.
has_zero_weight[col_idx] triggers a device -> host sync for each feature, so on GPU this list comprehension costs n_features round trips on every call with average=True, even when no column has a zero weight "plus one". I'd do the masking on device and copy the selected indices to the host once:
| zero_weight_cols = [ | |
| col_idx for col_idx in range(n_features) if has_zero_weight[col_idx] | |
| ] | |
| zero_weight_cols = move_to( | |
| xp.arange(n_features, device=device)[has_zero_weight], xp=np, device="cpu" | |
| ).tolist() |
(needs move_to imported from sklearn.utils._array_api)
On torch XPU (Intel Arc iGPU, float32, average=True, positive weights, 1000 samples), this gives:
- 100 features: 21.3 ms -> 6.5 ms
- 1000 features: 179 ms -> 33 ms
Note: iterating directly over the device array (like main does) would loop over 0-d arrays and bring back main's array_api_strict failure (Integer index arrays are only allowed with integer indices, because of the ...), hence the .tolist().
There was a problem hiding this comment.
I was sure I was messing something up related to array api :)
thx for the improvement.
It'd be nice to cover this in the tests: test_weighted_percentile_array_api_consistency never uses average=True, and test_weighted_percentile_ignores_zero_weight only uses scalar percentiles (the new vectorized zero-weight branch with e.g. percentile_rank=[0, 50, 100] isn't tested).
I added more parametrizations in the existing tests to cover all use cases.
|
Could you also habe a look how it compares to In the long run I would really like to remove our own implementation and rely on upstream scipy. |
On my 14-cores laptop, with the script of @jeremiedbb adapted to run Also we'll need to wait for our minimum supported version of scipy of be 1.17 (current is 1.10) before we can use it instead of our custom implementation. So I think this PR is very much worth the effort 👍 |
If we contribute such an improvement to scipy, many more would profit. |
|
I'll look if scipy quantile can get faster by using a similar implementation than ours, but not sure: theirs is more generic and it's quite complex (I know it a bit already, because I had started to implement quantile in array-api-extra)... But I'll look into it for sure! Still in the meantime, let's merge this one. |
There was a problem hiding this comment.
Thanks for the PR @jeremiedbb, LGMT !
- I was thinking an efficiency changelog (for user facing estimators like QuantileTransformer which benefit from this PR) could be nice. But on the other hand it only concerns a specific case (I think sample_weight + no subsampling) so maybe a changelog is not necessary here.
- The suggestions by @cakedev0 above sound good and easy to add. So +1 to implement these if possible.
Anyway, +1 to merge as is or with the aforementioned suggestions.
I added an entry, but not about QuantileTransformer because sample weight support is not released yet. |
cakedev0
left a comment
There was a problem hiding this comment.
Minor test fix, but otherwise LGTM
Co-authored-by: Arthur Lacote <[email protected]>
Co-authored-by: Arthur Lacote <[email protected]>
|
I've added 1.10 milestone to this PR because it's a fairly important speed-up for some cases I think, and it's ready to merge, maybe @lorentzenchr you can merge it? Btw, I looked into porting that to scipy and I couldn't find a nice way to do it while still supporting all the scipy constraints. Though I have a small numpy-only improvement almost ready. |
| n_dim_percentile = percentile_rank.ndim | ||
| if n_dim_percentile == 0: | ||
| percentile_rank = xp.reshape(percentile_rank, (1,)) |
There was a problem hiding this comment.
| if percentile_rank.ndim == 0: | |
| percentile_rank = xp.reshape(percentile_rank, (1,)) |
Then I have less to remember later.
There was a problem hiding this comment.
The if n_dim_percentile == 1 branches are there to avoid the (n_features, 1) broadcast when there is a single percentile, which is the most common case.
But I measured it (NumPy, troch cuda, torch xpu) and it's not really useful.
So I'd be +1 to always work with shape (n_features, n_percentiles) and squeeze at the end, like main does:
adjusted_percentile_rank = percentile_rank / 100 * weight_cdf[..., -1:]
...
col_indices = xp.reshape(xp.arange(n_features, device=device), (-1, 1))
...
has_zero_weight = xp.any(zero_weight_mask, axis=1)
...
if n_dim_percentile == 0:
result = result[..., 0]
return result[0, ...] if n_dim == 1 else result| else: | ||
| # special case for scalar percentile to avoid broadcasting | ||
| adjusted_percentile_rank = percentile_rank[0] / 100 * weight_cdf[..., -1] |
There was a problem hiding this comment.
Wasn't this taken care of above by percentile_rank = xp.reshape(percentile_rank, (1,))?
There was a problem hiding this comment.
Same as above: I don't think it's needed.
| np.array([0, 1, 1, 1, 1, 0], dtype=np.int32), | ||
| [25, 75], | ||
| ), | ||
| # Zero weight on the `average=True` plus-one index. Only column 0 needs |
There was a problem hiding this comment.
What is the "average=True plus-one index"?
There was a problem hiding this comment.
It's the "plus one" of stats.py: the next sample in sorted order, the one average=True averages with. Here column 0 has weights [1, 0, 1], so for the percentile 50 this next sample has a zero weight and the correction loop has to skip it.
Maybe clearer:
| # Zero weight on the `average=True` plus-one index. Only column 0 needs | |
| # Zero weight on the "plus one" sample (the next one in sorted order, | |
| # that `average=True` averages with). Only column 0 needs |
_weighted_percentileloops over percentiles while every following operations can be vectorized.I just had to special case here and there the n_percentile = 1 case to avoid an unnecessary broadcast
(n_features, 1)which would decrease the perfs for 1 percentile which is a very common use case of this function.Here's the benchmark script that I used:
and the results for n_samples = 100 / 1000 / 10000 and various values for n_features and n_percentiles
note that n_percentile = 1000 is the default for QuantileTransformer.