Repository navigation
Conversation
🔗 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 FailureAs of commit f66303f with merge base 083e261 ( NEW FAILURE - The following job has failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
a1c2dba to
3ac08fd
Compare
|
@pytorchbot label "release notes: python_frontend" |
|
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. |
|
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.
3ac08fd to
f66303f
Compare
|
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 ( |
| TORCH_INTERNAL_ASSERT( | ||
| self.scalar_type() == kFloat || self.scalar_type() == kDouble, | ||
| "quantile() rank computation assumes a float or double input"); | ||
| const bool double_ranks = |
There was a problem hiding this comment.
you are now using double_ranks even for cases that can be handled with float
There was a problem hiding this comment.
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?
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 |
|
@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 |
…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
…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
## 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
) ## 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
…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
) ## 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
(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.nanquantileforfloat32(andfloat64): large inputs now compute correctly instead of raisingquantile() input tensor is too large.Root cause
quantile maps
qto a rankq * (size - 1), rounds it to an int64 gather index, and interpolates the sorted values. The rank was computed in the input dtype, so forfloat32a rank above2^24is 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
float64wherever it exists. The sorted values stayfloat32; only the rank arithmetic and the int64 gather indices change, and those are exact infloat64out to2^53. The interpolation weight is cast back to the value dtype so thefloat32output is not upcast.MPShas nofloat64, sofloat32there keepsfloat32ranks and the original2^24cap; 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
float32results by at most one ulp, toward thefloat64value numpy returns;float64andMPSare unchanged. The change is cost-neutral: ranks and weights are output-sized, so quantile stays sort-bound (on 16Mfloat32the 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.float3217M, q=[0.1, 0.5]float32float32/float64sweep (2^24-1 .. 2^25, 5 modes, quantile + nanquantile, scalar/1D q, dim None/last/middle, keepdim)float32vs CPU; >2^24float32+float6417M, all modes + nan pathNew
test_quantile_large_input(float32andfloat64at 17M vs numpy, all interpolation modes + nanquantile) andtest_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).