Skip to content

PERF Speed-up _weighted_percentiles when n_percentiles > 1 - #35079

Open
jeremiedbb wants to merge 4 commits into
scikit-learn:mainfrom
jeremiedbb:eff-weighted-percentile
Open

jeremiedbb wants to merge 4 commits into
scikit-learn:mainfrom
jeremiedbb:eff-weighted-percentile

Conversation

@jeremiedbb

@jeremiedbb jeremiedbb commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

_weighted_percentile loops 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:
import csv
import time

import numpy as np

from sklearn.utils.stats import _weighted_percentile

N_SAMPLES = 10000
REPEATS = 100


def _make_data(n_features):
    rng = np.random.RandomState(0)
    shape = (N_SAMPLES, n_features)
    array = rng.normal(size=shape)
    weight = rng.uniform(0.1, 2.0, size=shape)
    return array, weight


def _benchmark_case(array, weight, percentiles):
    for _ in range(5):
        _weighted_percentile(array, weight, percentiles, average=True)
    times = np.empty(REPEATS)
    for i in range(REPEATS):
        start = time.perf_counter()
        _weighted_percentile(array, weight, percentiles, average=True)
        times[i] = time.perf_counter() - start
    times = np.sort(times)[10:-10]  # Drop the 10 fastest and 10 slowest.
    return np.median(times)


def _write_grid_results(rows):
    path = f"bench_weighted_percentile_{N_SAMPLES}.csv"
    with open(path, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)


def benchmark_grid():
    grid_n_features = (1, 2, 3, 5, 10, 20, 50, 100, 200, 500, 1000)
    grid_n_percentiles = (1, 2, 3, 5, 10, 20, 50, 100, 200, 500, 1000)

    rows = []
    for n_features in grid_n_features:
        array, weight = _make_data(n_features)
        for n_percentiles in grid_n_percentiles:
            percentiles = (
                np.linspace(0, 100, n_percentiles) if n_percentiles > 1 else 0.5
            )
            rows.append(
                {
                    "n_features": n_features,
                    "n_percentiles": n_percentiles,
                    "time": _benchmark_case(array, weight, percentiles),
                }
            )
            print(f"done {n_features=} | {n_percentiles=}")

    _write_grid_results(rows)

and the results for n_samples = 100 / 1000 / 10000 and various values for n_features and n_percentiles

bench_weighted_percentile_speedup_100_0 0_0 0 bench_weighted_percentile_speedup_1000_0 0_0 0 bench_weighted_percentile_speedup_10000_0 0_0 0

note that n_percentile = 1000 is the default for QuantileTransformer.

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

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).

Comment thread sklearn/utils/stats.py Outdated
Comment on lines +223 to +225
zero_weight_cols = [
col_idx for col_idx in range(n_features) if has_zero_weight[col_idx]
]

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.

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:

Suggested change
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().

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

@lorentzenchr

Copy link
Copy Markdown
Member

Could you also habe a look how it compares to scipy.stats. quantile.

In the long run I would really like to remove our own implementation and rely on upstream scipy.

@cakedev0

cakedev0 commented Oct 8, 2026

Copy link
Copy Markdown
Member

Could you also habe a look how it compares to scipy.stats.quantile

On my 14-cores laptop, with the script of @jeremiedbb adapted to run scipy.stats.quantile too, this PR is ~2.5-5x faster with few features and ~1.5x faster with many features.

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 👍

@lorentzenchr

Copy link
Copy Markdown
Member

So I think this PR is very much worth the effort

If we contribute such an improvement to scipy, many more would profit.

@cakedev0

cakedev0 commented Oct 9, 2026

Copy link
Copy Markdown
Member

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.

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

Thanks for the PR @jeremiedbb, LGMT !

  1. 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.
  2. 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.

@antoinebaker antoinebaker moved this from PR waiting for reviews to PR in progress in Labs Nov 2, 2026
@github-actions github-actions Bot added the size/M label Nov 5, 2026
@jeremiedbb

Copy link
Copy Markdown
Member Author

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.

I added an entry, but not about QuantileTransformer because sample weight support is not released yet.

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

Minor test fix, but otherwise LGTM

Comment thread sklearn/utils/tests/test_stats.py Resolved
Comment thread sklearn/utils/tests/test_stats.py Resolved
@cakedev0 cakedev0 added this to the 1.10 milestone Nov 6, 2026
@cakedev0

cakedev0 commented Nov 6, 2026

Copy link
Copy Markdown
Member

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.

Comment thread sklearn/utils/stats.py
Comment on lines 144 to 146
n_dim_percentile = percentile_rank.ndim
if n_dim_percentile == 0:
percentile_rank = xp.reshape(percentile_rank, (1,))

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.

Suggested change
if percentile_rank.ndim == 0:
percentile_rank = xp.reshape(percentile_rank, (1,))

Then I have less to remember later.

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 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

Comment thread sklearn/utils/stats.py
Comment on lines +174 to +176
else:
# special case for scalar percentile to avoid broadcasting
adjusted_percentile_rank = percentile_rank[0] / 100 * weight_cdf[..., -1]

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.

Wasn't this taken care of above by percentile_rank = xp.reshape(percentile_rank, (1,))?

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.

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

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.

What is the "average=True plus-one index"?

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.

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:

Suggested change
# 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

This branch has not been deployed

No deployments
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