Skip to content

Speed up CPU quantile/nanquantile with partial selection - #188394

Closed
qflen wants to merge 1 commit into
pytorch:mainfrom
qflen:quantile-perf
Closed

qflen wants to merge 1 commit into
pytorch:mainfrom
qflen:quantile-perf

Conversation

@qflen

@qflen qflen commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #64947.
(Part 2/2)
(float32 size-limit fix landed in #187574.)

torch.quantile / torch.nanquantile fully sort the reduced dimension just to read back a few order statistics. This replaces the sort with a CPU partial selection, making the common cases (median, quartiles, a handful of quantiles, batched/flattened nanquantile) 2-8x faster and ~60% lighter, bit-identical to the sort.

Root cause

For a few quantiles, quantile_compute runs a full self.sort() (O(n log n)) plus an n-element index tensor it immediately discards, then gathers a few ranks. The sort dominates the cost.

Approach

On CPU, in eager mode, with no tensor subclasses and few requested ranks, select the order statistics instead of sorting:

  • A helper resolves all requested ranks of a row in shared std::nth_element passes over an index permutation (recursing into the lower/upper rank subsets), NaN ordered last to match sort. Cost is ~O(n log K), not O(n log n).
  • It returns the original indices; the existing gather reads the values. So there is no new operator and no new autograd formula, and the forward output is bit-identical to the sort. The gradient matches too for distinct values; at tied values the subgradient is inherently non-unique (it already varies across non-stable CPU sort runs and vs CUDA).
  • Per-row ranks let quantile, flattened nanquantile, and ragged batched nanquantile share one helper with no special cases.

Everything else keeps the sort path: CUDA/MPS (device sorts already win), compile/export and vmap (gated behind !areAnyTensorSubclassLike), and large rank sets (num_ranks <= 100 && num_ranks^2 <= L). NaN semantics, the #187574 size cap, interpolation, and output shapes are untouched.

Before / after

Apple M5 (4 perf cores), torch.float64, base 12a9ea264bf + this commit. Median wall time; sort is the pre-change sort+gather+lerp path.

n num_q sort quantile speedup
10M 1 1308 ms 170 ms 7.7x
10M 3 1309 ms 313 ms 4.2x
10M 10 1305 ms 581 ms 2.3x
16.7M 1 2254 ms 278 ms 8.1x
16.7M 3 2257 ms 594 ms 3.8x
16.7M 10 2252 ms 1011 ms 2.2x

Peak RSS (16.7M, 3 quantiles): 147 MB vs 385 MB. Past the cap the selection falls back to the sort with no regression; nanquantile and batched inputs see the same win.

Verification

python test/test_reductions.py -k quantile (built CPU+MPS on Apple M5, all pass):

  • Bit-identical to the sort. test_quantile_partial_selection_autograd pins forward and gradient equal to an explicit sort/gather/lerp reference across all five interpolation modes for quantile and nanquantile, plus gradcheck/gradgradcheck.
  • Forward coverage. test_quantile_partial_selection (device-generic): many-quantile recursion, adversarial layouts, ragged-NaN batches, single-valid rows, sort fallback.
  • The fast path is gated off for subclass-like inputs, so compile/export/vmap and CUDA/MPS are unchanged; the device-generic tests also run on CUDA in CI.

cc @ngimel @Skylion007

@qflen
qflen requested a review from mruberry as a code owner June 29, 2026 06:56
@pytorch-bot

pytorch-bot Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/188394

Note: Links to docs will display an error until the docs builds have been completed.

❌ 4 New Failures, 5 Unrelated Failures

As of commit ac3ce4f with merge base 12a9ea2 (image):

NEW FAILURES - The following jobs have failed:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@qflen

qflen commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: cpu" "topic: performance"

@pytorch-bot

pytorch-bot Bot commented Jun 29, 2026

Copy link
Copy Markdown

Didn't find following labels among repository labels: release notes: cpu

@pytorch-bot pytorch-bot Bot added the topic: performance topic category label Jun 29, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 29, 2026

Copy link
Copy Markdown

❌ 🤖 pytorchbot command failed:

Got EOF while in a quoted string```
Try `@pytorchbot --help` for more info.

@qflen

qflen commented Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: python_frontend"

@pytorch-bot pytorch-bot Bot added the release notes: python_frontend python frontend release notes category label Jun 29, 2026
Comment thread aten/src/ATen/native/Sorting.cpp Resolved
Comment thread aten/src/ATen/native/Sorting.cpp Resolved
Comment thread aten/src/ATen/native/Sorting.cpp Resolved
Comment thread aten/src/ATen/native/Sorting.cpp Resolved
@soulitzer
soulitzer requested a review from ngimel June 29, 2026 21:13
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 29, 2026
@qflen
qflen requested a review from Skylion007 June 30, 2026 15:46
Comment thread test/test_reductions.py Resolved
quantile/nanquantile sort the entire reduced dimension to read back a few
order statistics (O(n log n) plus a discarded index tensor). On CPU eager
inputs with no tensor subclasses and few ranks, select just those order
statistics with std::nth_element over an index permutation and gather the
resulting indices instead of sorting.

Gathering indices rather than adding a values-only kernel keeps autograd
working with no new operator: the forward output is bit-identical to the
sort, and the gradient matches for distinct values (the subgradient is
non-unique at ties regardless). The fast path is gated on device and on
whether inputs are tensor subclasses, not on the symbolic size, so
compile/export/vmap, CUDA, and MPS keep the sort; a guard (num_ranks <= 100
and num_ranks^2 <= L) keeps large requests on the sort too.

Test Plan:
  python test/test_reductions.py -k quantile
  PYTORCH_TEST_WITH_DYNAMO=1 python test/test_reductions.py -k test_quantile_partial_selection

Adds test_quantile_partial_selection and
test_quantile_partial_selection_autograd (forward + gradient vs a
sort/gather/lerp reference, gradcheck/gradgradcheck); the autograd test is
skipped under dynamo_wrapped, where gradcheck's undefined-grad probe is
unsupported under compiled autograd. On Apple M5 (float64) ~2-8x faster and
~60% lighter for a handful of quantiles.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR accelerates CPU torch.quantile / torch.nanquantile by avoiding a full sort when only a small set of order statistics is needed, using a partial-selection (std::nth_element) approach while preserving existing semantics and autograd behavior.

Changes:

  • Add a CPU-only fast path that selects needed ranks via recursive nth_element passes over an index permutation, falling back to sort for other devices/subclass-like tensors/large rank sets.
  • Refactor quantile_compute to operate on an unsorted “reduced” view and share rank/weight computation between fast/slow value acquisition paths.
  • Add device-generic forward-accuracy tests and eager-only autograd (gradcheck/gradgradcheck) coverage for the new selection path.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
aten/src/ATen/native/Sorting.cpp Implements CPU partial-selection fast path for quantile/nanquantile and integrates it into quantile_compute with sort fallback.
test/test_reductions.py Adds forward and autograd tests validating correctness/equivalence across modes, shapes, NaN patterns, and devices.

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 9m 20s —— View job


PR Review: #188394

Summary

Replaces the full sort() in CPU quantile/nanquantile with a shared-pass std::nth_element order-statistic selection (2-8x faster), gated to CPU non-subclass tensors with small rank sets and falling back to the sort otherwise. I traced the shape/rank/autograd/NaN logic end-to-end and found no correctness or BC issues; the change is well-tested and I concur with the existing approval. Only minor, non-blocking notes below.

Full review details

Correctness (verified, no issues)

  • Recursion invariants (quantile_select_recurse, Sorting.cpp:195-217): the middle-rank pivot at r = ranks[umid] guarantees lo <= r < hi because sorted_ranks is sorted/unique within [0, L) and the recursion partitions ranks in lockstep with columns ([lo,r)/ranks[ulo,umid) and [r+1,hi)/ranks[umid+1,uhi)). Correct multi-order-statistic quickselect.
  • NaN ordering: the comparator !_isnan(x) && (_isnan(y) || x < y) is a strict-weak-order placing NaN last, matching sort(). All-NaN nanquantile rows (rank forced to 0) gather a NaN, same as the sort path.
  • Tie behavior: nth_element places the true r-th element at idx[r]; duplicate/interpolation ranks are resolved via idx[rkrow[m]], so the forward value is bit-identical to the sort even at ties (only the subgradient index can differ, which is inherently non-unique — correctly documented).
  • Shape consistency: reduced drops the leading q dim (in_shape = out_shape[1:]), while ranks broadcasts to [reduced_batch..., Q]; batch dims match, so R = reduced.numel()/L and the {R, M} reshape / gather(-1) are valid — identical contract to the pre-change sorted.gather(-1, ...).
  • Autograd: indices are computed in a non-differentiable helper (like argsort); the graph flows self -> reshape -> contiguous -> gather -> lerp, matching the sort path for distinct values. gradcheck/gradgradcheck cover it.
  • Overflow: num_ranks <= 100 bounds num_ranks*num_ranks well under int limits; r * L is int64_t throughout.
  • Fast-path gate: !areAnyTensorSubclassLike({self, q}) (which also returns true under dispatch_mode_enabled) correctly excludes fake tensors (compile/export), functorch (vmap/grad), and non-CPU backends, so the concrete reduced.size(-1) reads at Sorting.cpp:454-456 are safe.
  • Thread safety: parallel_for writes disjoint outp[r] rows; idx/sorted_ranks scratch is per-chunk. Fine.

Minor notes (non-blocking)

  • Sorting.cpp:456 — the num_ranks <= 100 && num_ranks^2 <= L threshold is a bare heuristic. The comment explains the intent but not why 100 specifically; a one-line note that it's an empirical crossover (not a correctness bound) would help future readers, since past the gate you silently fall back to the sort.
  • Sorting.cpp:442 — ranks.ceil_() mutates ranks in place. It's safe because ranks/weights/ranks_below are all read before this line, but it's a foot-gun if code is later inserted between; the original had the same pattern, so no change required.
  • Test test_quantile_partial_selection relies on numpy's method= kwarg (numpy >= 1.22) — fine for current CI.

Prior review threads

All of Skylion007's earlier comments (mutable_data_ptr / raw write removed, accessors instead of contiguous, dtypesIfMPS instead of skipIfMPS on the forward test, sub dtype arg) have been addressed in the current diff.

Recommendation

Approve — no correctness, BC, thread-safety, or test-coverage blockers. The two minor notes are optional polish.
· branch quantile-perf

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 24, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: pull / linux-jammy-aarch64-py3.10 / build-osdc

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable)

Details for Dev Infra team Raised by workflow job

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 2 checks: pull / linux-jammy-aarch64-py3.10 / build-osdc, trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m1-14)

Details for Dev Infra team Raised by workflow job

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Harsha0Sree pushed a commit to Harsha0Sree/pytorch that referenced this pull request Jul 25, 2026
)

## Summary

Closes pytorch#64947.
**(Part 2/2)**
(float32 size-limit fix landed in pytorch#187574.)

`torch.quantile` / `torch.nanquantile` fully sort the reduced dimension just to read back a few order statistics. This replaces the sort with a CPU partial selection, making the common cases (median, quartiles, a handful of quantiles, batched/flattened `nanquantile`) **2-8x faster and ~60% lighter**, bit-identical to the sort.

## Root cause

For a few quantiles, `quantile_compute` runs a full `self.sort()` (O(n log n)) plus an n-element index tensor it immediately discards, then gathers a few ranks. The sort dominates the cost.

## Approach

On CPU, in eager mode, with no tensor subclasses and few requested ranks, select the order statistics instead of sorting:

- A helper resolves all requested ranks of a row in shared `std::nth_element` passes over an index permutation (recursing into the lower/upper rank subsets), NaN ordered last to match `sort`. Cost is ~O(n log K), not O(n log n).
- It returns the original indices; the existing `gather` reads the values. So there is no new operator and no new autograd formula, and the forward output is bit-identical to the sort. The gradient matches too for distinct values; at tied values the subgradient is inherently non-unique (it already varies across non-stable CPU sort runs and vs CUDA).
- Per-row ranks let `quantile`, flattened `nanquantile`, and ragged batched `nanquantile` share one helper with no special cases.

Everything else keeps the sort path: CUDA/MPS (device sorts already win), compile/export and vmap (gated behind `!areAnyTensorSubclassLike`), and large rank sets (`num_ranks <= 100 && num_ranks^2 <= L`). NaN semantics, the pytorch#187574 size cap, interpolation, and output shapes are untouched.

## Before / after

Apple M5 (4 perf cores), `torch.float64`, base `12a9ea264bf` + this commit. Median wall time; `sort` is the pre-change sort+gather+lerp path.

| n | num_q | sort | quantile | speedup |
|---|---|---|---|---|
| 10M | 1 | 1308 ms | 170 ms | 7.7x |
| 10M | 3 | 1309 ms | 313 ms | 4.2x |
| 10M | 10 | 1305 ms | 581 ms | 2.3x |
| 16.7M | 1 | 2254 ms | 278 ms | 8.1x |
| 16.7M | 3 | 2257 ms | 594 ms | 3.8x |
| 16.7M | 10 | 2252 ms | 1011 ms | 2.2x |

Peak RSS (16.7M, 3 quantiles): **147 MB vs 385 MB**. Past the cap the selection falls back to the sort with no regression; `nanquantile` and batched inputs see the same win.

## Verification

`python test/test_reductions.py -k quantile` (built CPU+MPS on Apple M5, all pass):

- **Bit-identical to the sort.** `test_quantile_partial_selection_autograd` pins forward and gradient equal to an explicit sort/gather/lerp reference across all five interpolation modes for `quantile` and `nanquantile`, plus `gradcheck`/`gradgradcheck`.
- **Forward coverage.** `test_quantile_partial_selection` (device-generic): many-quantile recursion, adversarial layouts, ragged-NaN batches, single-valid rows, sort fallback.
- The fast path is gated off for subclass-like inputs, so compile/export/vmap and CUDA/MPS are unchanged; the device-generic tests also run on CUDA in CI.

Pull Request resolved: pytorch#188394
Approved by: https://github.com/Skylion007
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
)

## Summary

Closes pytorch#64947.
**(Part 2/2)**
(float32 size-limit fix landed in pytorch#187574.)

`torch.quantile` / `torch.nanquantile` fully sort the reduced dimension just to read back a few order statistics. This replaces the sort with a CPU partial selection, making the common cases (median, quartiles, a handful of quantiles, batched/flattened `nanquantile`) **2-8x faster and ~60% lighter**, bit-identical to the sort.

## Root cause

For a few quantiles, `quantile_compute` runs a full `self.sort()` (O(n log n)) plus an n-element index tensor it immediately discards, then gathers a few ranks. The sort dominates the cost.

## Approach

On CPU, in eager mode, with no tensor subclasses and few requested ranks, select the order statistics instead of sorting:

- A helper resolves all requested ranks of a row in shared `std::nth_element` passes over an index permutation (recursing into the lower/upper rank subsets), NaN ordered last to match `sort`. Cost is ~O(n log K), not O(n log n).
- It returns the original indices; the existing `gather` reads the values. So there is no new operator and no new autograd formula, and the forward output is bit-identical to the sort. The gradient matches too for distinct values; at tied values the subgradient is inherently non-unique (it already varies across non-stable CPU sort runs and vs CUDA).
- Per-row ranks let `quantile`, flattened `nanquantile`, and ragged batched `nanquantile` share one helper with no special cases.

Everything else keeps the sort path: CUDA/MPS (device sorts already win), compile/export and vmap (gated behind `!areAnyTensorSubclassLike`), and large rank sets (`num_ranks <= 100 && num_ranks^2 <= L`). NaN semantics, the pytorch#187574 size cap, interpolation, and output shapes are untouched.

## Before / after

Apple M5 (4 perf cores), `torch.float64`, base `12a9ea264bf` + this commit. Median wall time; `sort` is the pre-change sort+gather+lerp path.

| n | num_q | sort | quantile | speedup |
|---|---|---|---|---|
| 10M | 1 | 1308 ms | 170 ms | 7.7x |
| 10M | 3 | 1309 ms | 313 ms | 4.2x |
| 10M | 10 | 1305 ms | 581 ms | 2.3x |
| 16.7M | 1 | 2254 ms | 278 ms | 8.1x |
| 16.7M | 3 | 2257 ms | 594 ms | 3.8x |
| 16.7M | 10 | 2252 ms | 1011 ms | 2.2x |

Peak RSS (16.7M, 3 quantiles): **147 MB vs 385 MB**. Past the cap the selection falls back to the sort with no regression; `nanquantile` and batched inputs see the same win.

## Verification

`python test/test_reductions.py -k quantile` (built CPU+MPS on Apple M5, all pass):

- **Bit-identical to the sort.** `test_quantile_partial_selection_autograd` pins forward and gradient equal to an explicit sort/gather/lerp reference across all five interpolation modes for `quantile` and `nanquantile`, plus `gradcheck`/`gradgradcheck`.
- **Forward coverage.** `test_quantile_partial_selection` (device-generic): many-quantile recursion, adversarial layouts, ragged-NaN batches, single-valid rows, sort fallback.
- The fast path is gated off for subclass-like inputs, so compile/export/vmap and CUDA/MPS are unchanged; the device-generic tests also run on CUDA in CI.

Pull Request resolved: pytorch#188394
Approved by: https://github.com/Skylion007
MelindaTan pushed a commit to MelindaTan/pytorch that referenced this pull request Jul 31, 2026
)

## Summary

Closes pytorch#64947.
**(Part 2/2)**
(float32 size-limit fix landed in pytorch#187574.)

`torch.quantile` / `torch.nanquantile` fully sort the reduced dimension just to read back a few order statistics. This replaces the sort with a CPU partial selection, making the common cases (median, quartiles, a handful of quantiles, batched/flattened `nanquantile`) **2-8x faster and ~60% lighter**, bit-identical to the sort.

## Root cause

For a few quantiles, `quantile_compute` runs a full `self.sort()` (O(n log n)) plus an n-element index tensor it immediately discards, then gathers a few ranks. The sort dominates the cost.

## Approach

On CPU, in eager mode, with no tensor subclasses and few requested ranks, select the order statistics instead of sorting:

- A helper resolves all requested ranks of a row in shared `std::nth_element` passes over an index permutation (recursing into the lower/upper rank subsets), NaN ordered last to match `sort`. Cost is ~O(n log K), not O(n log n).
- It returns the original indices; the existing `gather` reads the values. So there is no new operator and no new autograd formula, and the forward output is bit-identical to the sort. The gradient matches too for distinct values; at tied values the subgradient is inherently non-unique (it already varies across non-stable CPU sort runs and vs CUDA).
- Per-row ranks let `quantile`, flattened `nanquantile`, and ragged batched `nanquantile` share one helper with no special cases.

Everything else keeps the sort path: CUDA/MPS (device sorts already win), compile/export and vmap (gated behind `!areAnyTensorSubclassLike`), and large rank sets (`num_ranks <= 100 && num_ranks^2 <= L`). NaN semantics, the pytorch#187574 size cap, interpolation, and output shapes are untouched.

## Before / after

Apple M5 (4 perf cores), `torch.float64`, base `12a9ea264bf` + this commit. Median wall time; `sort` is the pre-change sort+gather+lerp path.

| n | num_q | sort | quantile | speedup |
|---|---|---|---|---|
| 10M | 1 | 1308 ms | 170 ms | 7.7x |
| 10M | 3 | 1309 ms | 313 ms | 4.2x |
| 10M | 10 | 1305 ms | 581 ms | 2.3x |
| 16.7M | 1 | 2254 ms | 278 ms | 8.1x |
| 16.7M | 3 | 2257 ms | 594 ms | 3.8x |
| 16.7M | 10 | 2252 ms | 1011 ms | 2.2x |

Peak RSS (16.7M, 3 quantiles): **147 MB vs 385 MB**. Past the cap the selection falls back to the sort with no regression; `nanquantile` and batched inputs see the same win.

## Verification

`python test/test_reductions.py -k quantile` (built CPU+MPS on Apple M5, all pass):

- **Bit-identical to the sort.** `test_quantile_partial_selection_autograd` pins forward and gradient equal to an explicit sort/gather/lerp reference across all five interpolation modes for `quantile` and `nanquantile`, plus `gradcheck`/`gradgradcheck`.
- **Forward coverage.** `test_quantile_partial_selection` (device-generic): many-quantile recursion, adversarial layouts, ragged-NaN batches, single-valid rows, sort fallback.
- The fast path is gated off for subclass-like inputs, so compile/export/vmap and CUDA/MPS are unchanged; the device-generic tests also run on CUDA in CI.

Pull Request resolved: pytorch#188394
Approved by: https://github.com/Skylion007
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: python_frontend python frontend release notes category topic: performance topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Quantile is limited to 16 million elements and have poor performance.

6 participants