Skip to content

Support large float32 tensors in quantile by computing ranks in float64 - #187574

Closed
qflen wants to merge 1 commit into
pytorch:mainfrom
qflen:fix-quantile-float64-cap-64947
Closed

qflen wants to merge 1 commit into
pytorch:mainfrom
qflen:fix-quantile-float64-cap-64947

Conversation

@qflen

@qflen qflen commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

(1/2) DONE
Performance fix pending.

Addresses the size limitation in #64947.

EDIT: (2/2) landed at #188394.

Lifts the ~16M element limit in torch.quantile / torch.nanquantile for float32 (and float64): large inputs now compute correctly instead of raising quantile() input tensor is too large.

Root cause

quantile maps q to a rank q * (size - 1), rounds it to an int64 gather index, and interpolates the sorted values. The rank was computed in the input dtype, so for float32 a rank above 2^24 is not exactly representable: distinct ranks alias to one index and interpolation weights quantize. The size cap rejected such inputs to avoid silently wrong results.

Fix

Compute the ranks in float64 wherever it exists. The sorted values stay float32; only the rank arithmetic and the int64 gather indices change, and those are exact in float64 out to 2^53. The interpolation weight is cast back to the value dtype so the float32 output is not upcast.

MPS has no float64, so float32 there keeps float32 ranks and the original 2^24 cap; the cap is now dtype- and device-aware.

The branch is on dtype and device, not on the (symbolic) size, so it stays compile- and export-safe. It shifts existing float32 results by at most one ulp, toward the float64 value numpy returns; float64 and MPS are unchanged. The change is cost-neutral: ranks and weights are output-sized, so quantile stays sort-bound (on 16M float32 the added arithmetic is microseconds against a ~1s sort).

Verification

Base 083e2617b8ee. Built CPU+MPS on an Apple M5 and validated CUDA on an NVIDIA A40. quantile is a device-agnostic composite, so the same sort/gather/lerp kernels run the fix's exact numerics on every device.

Case Before After
float32 17M, q=[0.1, 0.5] RuntimeError "too large" matches numpy float64 oracle; output float32
float32/float64 sweep (2^24-1 .. 2^25, 5 modes, quantile + nanquantile, scalar/1D q, dim None/last/middle, keepdim) n/a (capped) 470/470 match numpy (CPU)
MPS small float32 vs CPU; >2^24 unchanged matches CPU; cap still raises
CUDA float32+float64 17M, all modes + nan path RuntimeError 20/20 match numpy
python test/test_reductions.py -k quantile -v   # 9 passed, 5 MPS-skipped

New test_quantile_large_input (float32 and float64 at 17M vs numpy, all interpolation modes + nanquantile) and test_quantile_size_limit (device-aware boundary) are device-generic, so CI also runs them on CUDA.

Not in this PR

#64947 also asks for a faster, lower-memory implementation. This keeps the full O(n log n) sort; a partial-selection (kthvalue) rewrite is a separate follow-up (it is device-specific: faster on CPU, but the radix sort already wins on CUDA).

@qflen
qflen requested a review from mruberry as a code owner June 17, 2026 14:44
@pytorch-bot

pytorch-bot Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure

As of commit f66303f with merge base 083e261 (image):

NEW FAILURE - The following job has failed:

  • pull / linux-jammy-aarch64-py3.10 / build-osdc (gh)
    Executing the custom container implementation failed. Please contact your self hosted runner administrator.

    AI verdict:

    The failure is a GitHub Actions self-hosted runner infrastructure error ("Executing the custom container implementation failed") unrelated to the code change. The commit only modifies quantile computation logic in Sorting.cpp and a test file.

    Full reasoning on HUD →

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

@qflen
qflen force-pushed the fix-quantile-float64-cap-64947 branch from a1c2dba to 3ac08fd Compare June 17, 2026 14:50
@qflen

qflen commented Jun 17, 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 17, 2026
@liangel-02
liangel-02 requested a review from ngimel June 18, 2026 00:38
@liangel-02 liangel-02 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 18, 2026
Comment thread aten/src/ATen/native/Sorting.cpp Resolved
@datadog-pytorch-via-lf

Copy link
Copy Markdown

Pipelines

⚠️ Warnings

🚦 1 Pipeline job failed

pull | linux-jammy-aarch64-py3.10 / build-osdc   View in Datadog   GitHub Actions

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 3ac08fd | Docs | Give us feedback!

@ngimel

ngimel commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator

This doesn't fully fix #64947, as the ask was to support quantile for larger fp32 tensors, but it's an improvement over status quo.

@qflen

qflen commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

Trying a full fix and some final edits to make this more complete.

quantile rounds q * (size - 1) to gather indices in the input dtype, so for
float32 a rank past 2^24 is not exactly representable and distinct ranks
alias to one index; a size cap rejected such inputs (the 16M limit in
pytorchgh-64947). Compute the ranks in float64 where it exists, keep the sorted
values float32, and cast the interpolation weight back to the value dtype.
The branch is on dtype and device, not a symbolic size gate, so it stays
compile- and export-safe; it shifts existing float32 results by at most one
ulp, toward the float64 value numpy returns. MPS has no float64, so float32
there keeps float32 ranks and the 2^24 cap.

Lifts the size limit only; the perf ask in pytorchgh-64947 is a separate follow-up.
@qflen
qflen force-pushed the fix-quantile-float64-cap-64947 branch from 3ac08fd to f66303f Compare June 18, 2026 20:00
@qflen qflen changed the title Make quantile size cap dtype-aware to lift the 16M limit for float64 Support large float32 tensors in quantile by computing ranks in float64 Jun 18, 2026
@qflen

qflen commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

Pushed, but the performance half of the issue still open. I'll make a separate follow-up to try to replace the full sort with a partial selection (kthvalue / introselect), including benchmarks / repro in the PR.

TORCH_INTERNAL_ASSERT(
self.scalar_type() == kFloat || self.scalar_type() == kDouble,
"quantile() rank computation assumes a float or double input");
const bool double_ranks =

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

you are now using double_ranks even for cases that can be handled with float

@qflen qflen Jun 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I looked into using float for the smaller cases, but gating it on the reduction size means branching on a symbolic size, which isn't safe for compilation or exporting. Instead, making the choice based on dtype and device keeps things static. This means we just default to double for ranks wherever the hardware supports it.

Performance-wise, this shouldn't cost us anything. Because the ranks and weights are output-sized, the overhead of using double arithmetic is just microseconds compared to the actual sorting step. As a bonus, it pushes the float32 result at most 1 ULP closer to NumPy's reference output.

We could branch on the static size to keep float for the small cases, but that would cause the eager and compiled modes to diverge by that same 1 ULP. Honestly, I don't think it's worth maintaining a second code path for that. What do you think?

@qflen

qflen commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Note on performance follow-up (2/2):

Already implemented and validated locally.

CPU introselect path is ~5-10x faster, 25-45% lighter, and bit-identical (37k-config sweep and gradchecks passing).

I'll push it as soon as this one merges to not stack quantile_compute refactors.

@qflen
qflen requested a review from Skylion007 June 19, 2026 02:06
@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 Jun 20, 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

gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…64 (pytorch#187574)

## Summary

_**(1/2)** DONE_
Performance fix pending.

Addresses the size limitation in pytorch#64947.

Lifts the ~16M element limit in `torch.quantile` / `torch.nanquantile` for `float32` (and `float64`): large inputs now compute correctly instead of raising `quantile() input tensor is too large`.

## Root cause

quantile maps `q` to a rank `q * (size - 1)`, rounds it to an int64 gather index, and interpolates the sorted values. The rank was computed in the input dtype, so for `float32` a rank above `2^24` is not exactly representable: distinct ranks alias to one index and interpolation weights quantize. The size cap rejected such inputs to avoid silently wrong results.

## Fix

Compute the ranks in `float64` wherever it exists. The sorted values stay `float32`; only the rank arithmetic and the int64 gather indices change, and those are exact in `float64` out to `2^53`. The interpolation weight is cast back to the value dtype so the `float32` output is not upcast.

`MPS` has no `float64`, so `float32` there keeps `float32` ranks and the original `2^24` cap; the cap is now dtype- and device-aware.

The branch is on dtype and device, not on the (symbolic) size, so it stays compile- and export-safe. It shifts existing `float32` results by at most one ulp, toward the `float64` value numpy returns; `float64` and `MPS` are unchanged. The change is cost-neutral: ranks and weights are output-sized, so quantile stays sort-bound (on 16M `float32` the added arithmetic is microseconds against a ~1s sort).

## Verification

Base [`083e2617b8ee`](pytorch@083e261). Built CPU+MPS on an Apple M5 and validated CUDA on an NVIDIA A40. quantile is a device-agnostic composite, so the same sort/gather/lerp kernels run the fix's exact numerics on every device.

| Case | Before | After |
|---|---|---|
| `float32` 17M, q=[0.1, 0.5] | RuntimeError "too large" | matches numpy float64 oracle; output `float32` |
| `float32`/`float64` sweep (2^24-1 .. 2^25, 5 modes, quantile + nanquantile, scalar/1D q, dim None/last/middle, keepdim) | n/a (capped) | 470/470 match numpy (CPU) |
| MPS small `float32` vs CPU; >2^24 | unchanged | matches CPU; cap still raises |
| CUDA `float32`+`float64` 17M, all modes + nan path | RuntimeError | 20/20 match numpy |

```
python test/test_reductions.py -k quantile -v   # 9 passed, 5 MPS-skipped
```

New `test_quantile_large_input` (`float32` and `float64` at 17M vs numpy, all interpolation modes + nanquantile) and `test_quantile_size_limit` (device-aware boundary) are device-generic, so CI also runs them on CUDA.

## Not in this PR

pytorch#64947 also asks for a faster, lower-memory implementation. This keeps the full `O(n log n)` sort; a partial-selection (`kthvalue`) rewrite is a separate follow-up (it is device-specific: faster on CPU, but the radix sort already wins on CUDA).

Pull Request resolved: pytorch#187574
Approved by: https://github.com/ngimel, https://github.com/Skylion007
vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
…64 (pytorch#187574)

## Summary

_**(1/2)** DONE_
Performance fix pending.

Addresses the size limitation in pytorch#64947.

Lifts the ~16M element limit in `torch.quantile` / `torch.nanquantile` for `float32` (and `float64`): large inputs now compute correctly instead of raising `quantile() input tensor is too large`.

## Root cause

quantile maps `q` to a rank `q * (size - 1)`, rounds it to an int64 gather index, and interpolates the sorted values. The rank was computed in the input dtype, so for `float32` a rank above `2^24` is not exactly representable: distinct ranks alias to one index and interpolation weights quantize. The size cap rejected such inputs to avoid silently wrong results.

## Fix

Compute the ranks in `float64` wherever it exists. The sorted values stay `float32`; only the rank arithmetic and the int64 gather indices change, and those are exact in `float64` out to `2^53`. The interpolation weight is cast back to the value dtype so the `float32` output is not upcast.

`MPS` has no `float64`, so `float32` there keeps `float32` ranks and the original `2^24` cap; the cap is now dtype- and device-aware.

The branch is on dtype and device, not on the (symbolic) size, so it stays compile- and export-safe. It shifts existing `float32` results by at most one ulp, toward the `float64` value numpy returns; `float64` and `MPS` are unchanged. The change is cost-neutral: ranks and weights are output-sized, so quantile stays sort-bound (on 16M `float32` the added arithmetic is microseconds against a ~1s sort).

## Verification

Base [`083e2617b8ee`](pytorch@083e261). Built CPU+MPS on an Apple M5 and validated CUDA on an NVIDIA A40. quantile is a device-agnostic composite, so the same sort/gather/lerp kernels run the fix's exact numerics on every device.

| Case | Before | After |
|---|---|---|
| `float32` 17M, q=[0.1, 0.5] | RuntimeError "too large" | matches numpy float64 oracle; output `float32` |
| `float32`/`float64` sweep (2^24-1 .. 2^25, 5 modes, quantile + nanquantile, scalar/1D q, dim None/last/middle, keepdim) | n/a (capped) | 470/470 match numpy (CPU) |
| MPS small `float32` vs CPU; >2^24 | unchanged | matches CPU; cap still raises |
| CUDA `float32`+`float64` 17M, all modes + nan path | RuntimeError | 20/20 match numpy |

```
python test/test_reductions.py -k quantile -v   # 9 passed, 5 MPS-skipped
```

New `test_quantile_large_input` (`float32` and `float64` at 17M vs numpy, all interpolation modes + nanquantile) and `test_quantile_size_limit` (device-aware boundary) are device-generic, so CI also runs them on CUDA.

## Not in this PR

pytorch#64947 also asks for a faster, lower-memory implementation. This keeps the full `O(n log n)` sort; a partial-selection (`kthvalue`) rewrite is a separate follow-up (it is device-specific: faster on CPU, but the radix sort already wins on CUDA).

Pull Request resolved: pytorch#187574
Approved by: https://github.com/ngimel, https://github.com/Skylion007
pytorchmergebot pushed a commit that referenced this pull request Jul 25, 2026
## 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.

Pull Request resolved: #188394
Approved by: https://github.com/Skylion007
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
…64 (pytorch#187574)

## Summary

_**(1/2)** DONE_
Performance fix pending.

Addresses the size limitation in pytorch#64947.

Lifts the ~16M element limit in `torch.quantile` / `torch.nanquantile` for `float32` (and `float64`): large inputs now compute correctly instead of raising `quantile() input tensor is too large`.

## Root cause

quantile maps `q` to a rank `q * (size - 1)`, rounds it to an int64 gather index, and interpolates the sorted values. The rank was computed in the input dtype, so for `float32` a rank above `2^24` is not exactly representable: distinct ranks alias to one index and interpolation weights quantize. The size cap rejected such inputs to avoid silently wrong results.

## Fix

Compute the ranks in `float64` wherever it exists. The sorted values stay `float32`; only the rank arithmetic and the int64 gather indices change, and those are exact in `float64` out to `2^53`. The interpolation weight is cast back to the value dtype so the `float32` output is not upcast.

`MPS` has no `float64`, so `float32` there keeps `float32` ranks and the original `2^24` cap; the cap is now dtype- and device-aware.

The branch is on dtype and device, not on the (symbolic) size, so it stays compile- and export-safe. It shifts existing `float32` results by at most one ulp, toward the `float64` value numpy returns; `float64` and `MPS` are unchanged. The change is cost-neutral: ranks and weights are output-sized, so quantile stays sort-bound (on 16M `float32` the added arithmetic is microseconds against a ~1s sort).

## Verification

Base [`083e2617b8ee`](pytorch@083e261). Built CPU+MPS on an Apple M5 and validated CUDA on an NVIDIA A40. quantile is a device-agnostic composite, so the same sort/gather/lerp kernels run the fix's exact numerics on every device.

| Case | Before | After |
|---|---|---|
| `float32` 17M, q=[0.1, 0.5] | RuntimeError "too large" | matches numpy float64 oracle; output `float32` |
| `float32`/`float64` sweep (2^24-1 .. 2^25, 5 modes, quantile + nanquantile, scalar/1D q, dim None/last/middle, keepdim) | n/a (capped) | 470/470 match numpy (CPU) |
| MPS small `float32` vs CPU; >2^24 | unchanged | matches CPU; cap still raises |
| CUDA `float32`+`float64` 17M, all modes + nan path | RuntimeError | 20/20 match numpy |

```
python test/test_reductions.py -k quantile -v   # 9 passed, 5 MPS-skipped
```

New `test_quantile_large_input` (`float32` and `float64` at 17M vs numpy, all interpolation modes + nanquantile) and `test_quantile_size_limit` (device-aware boundary) are device-generic, so CI also runs them on CUDA.

## Not in this PR

pytorch#64947 also asks for a faster, lower-memory implementation. This keeps the full `O(n log n)` sort; a partial-selection (`kthvalue`) rewrite is a separate follow-up (it is device-specific: faster on CPU, but the radix sort already wins on CUDA).

Pull Request resolved: pytorch#187574
Approved by: https://github.com/ngimel, 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 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.

6 participants