Repository navigation
Conversation
🔗 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 FailuresAs of commit ac3ce4f with merge base 12a9ea2 ( 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. |
|
@pytorchbot label "release notes: cpu" "topic: performance" |
|
Didn't find following labels among repository labels: release notes: cpu |
|
❌ 🤖 pytorchbot command failed: |
|
@pytorchbot label "release notes: python_frontend" |
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.
There was a problem hiding this comment.
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_elementpasses over an index permutation, falling back to sort for other devices/subclass-like tensors/large rank sets. - Refactor
quantile_computeto 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. |
|
@claude review this PR |
|
Claude finished @Skylion007's task in 9m 20s —— View job PR Review: #188394SummaryReplaces the full Full review detailsCorrectness (verified, no issues)
Minor notes (non-blocking)
Prior review threadsAll of Skylion007's earlier comments (mutable_data_ptr / raw write removed, accessors instead of RecommendationApprove — no correctness, BC, thread-safety, or test-coverage blockers. The two minor notes are optional polish. |
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 1 mandatory check(s) failed. The first few are: Dig deeper by viewing the failures on hud |
|
@pytorchbot merge -i |
Merge startedYour 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 |
Merge failedReason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable) Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot merge -i |
Merge startedYour 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 |
Merge failedReason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m1-14) Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 6 checks: pull / linux-jammy-aarch64-py3.10 / build-osdc, trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m2-15), trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m1-14), trunk / macos-py3-arm64 / test (default, 2, 3, macos-m1-stable), trunk / linux-jammy-cuda13.0-py3.10-gcc11 / test-osdc (default, 4, 5, mt-l-x86aavx2-29-113-l4), trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 8, 8, linux.rocm.gpu.gfx950.1) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
) ## 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
) ## 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
) ## 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
Summary
Closes #64947.
(Part 2/2)
(float32 size-limit fix landed in #187574.)
torch.quantile/torch.nanquantilefully 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/flattenednanquantile) 2-8x faster and ~60% lighter, bit-identical to the sort.Root cause
For a few quantiles,
quantile_computeruns a fullself.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:
std::nth_elementpasses over an index permutation (recursing into the lower/upper rank subsets), NaN ordered last to matchsort. Cost is ~O(n log K), not O(n log n).gatherreads 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).quantile, flattenednanquantile, and ragged batchednanquantileshare 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, base12a9ea264bf+ this commit. Median wall time;sortis the pre-change sort+gather+lerp path.Peak RSS (16.7M, 3 quantiles): 147 MB vs 385 MB. Past the cap the selection falls back to the sort with no regression;
nanquantileand batched inputs see the same win.Verification
python test/test_reductions.py -k quantile(built CPU+MPS on Apple M5, all pass):test_quantile_partial_selection_autogradpins forward and gradient equal to an explicit sort/gather/lerp reference across all five interpolation modes forquantileandnanquantile, plusgradcheck/gradgradcheck.test_quantile_partial_selection(device-generic): many-quantile recursion, adversarial layouts, ragged-NaN batches, single-valid rows, sort fallback.cc @ngimel @Skylion007