Skip to content

Compute median, quantile, two-argument cov/cor and complex var on the device - #868

Merged
maleadt merged 4 commits into
mainfrom
tb/statistics
Nov 27, 2026
Merged

maleadt merged 4 commits into
mainfrom
tb/statistics

Conversation

@maleadt

@maleadt maleadt commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Several Statistics functions either scalar-index GPU arrays or copy them to the host:

  • median(A; dims) goes through mapslices, and median! of an even number of values reads the two middle elements one at a time.
  • median(A) copies the array to the host and sorts it there.
  • Every form of quantile and quantile! goes through Statistics' sort!(v, lo, hi, PartialQuickSort) and then reads each order statistic separately.
  • cov(X, Y) takes its result type from first(C). cor(x, y) accumulates in a scalar loop, and cor(X, Y) scales with a cov2cor! loop.
  • var(A; dims) of complex arrays falls back to Statistics' loop, because GPUArrays' varm only accepted real arrays.

This PR handles all of them on the device, with the same results as Statistics.

Variance stays two-pass: Statistics computes the mean, then GPUArrays sums abs2(a - m) in a single fused reduction. A one-pass Welford/Chan merge, as in AcceleratedKernels.jl#64, came out less accurate in Float32 (relative error 4e-5 against 1.3e-6) and 2–10× slower in Float64 on an RTX 5080, so it isn't used. varm now accepts any number type and returns Statistics' real floating-point type. The squared deviations are summed in the result type, or in their own type where that is wider, and scaled afterwards. Previously each term was scaled first, which rounded small Float16 deviations to zero. An empty array now gives NaN rather than 0, and the means of nonempty data are checked against the reduced shape.

Covariance and correlation of two arrays: the result type is inferred, cov2cor! becomes one broadcast, and two-vector cor sums its three terms in a single reduction. Statistics' overflow-avoiding scaling is kept.

Median and quantile sort on the device with AK.sort!(...; alg=AK.Auto(stable=false)) and gather only the order statistics they need. Equal values are indistinguishable apart from NaN payloads, so the sort doesn't need to be stable, and an unstable sort is much faster for short slices. The NaN check uses the last element of each sorted slice, because isless sorts NaN last. median(A; dims) accepts any set of dimensions: the reduced ones are combined into one, by reshaping when they lead and by permuting otherwise. Quantiles reuse Statistics' own _quantile arithmetic, run on host stand-ins for the sorted data, so the interpolation is bit-identical for every alpha/beta. Out-of-bounds probabilities and NaN or missing data are reported in Statistics' order. quantile! sorts its input, as its docstring says. quantile leaves its input alone.

The selection goes through an internal _select!(src, ranks; dims), which returns the values at given sorted ranks. Once AcceleratedKernels has a batched radix select (JuliaGPU/AcceleratedKernels.jl#215), _select! can call it without changes to the callers. A prototype makes median another 6–8× faster on large vectors and 4096² matrices, with no gain for 64-element slices.

Where this differs from Statistics:

  • quantile(v, p) with an array p returns an array in p's container: a host array for host p, a GPU array for GPU p. A tuple p gives a tuple.
  • median of data with NaNs returns one of those NaNs, not necessarily the first.
  • median(A; dims) returns an empty array when the result is empty (Statistics' mapslices throws a BoundsError). It returns a Union{Missing,T} array when slices contain missing (mapslices fails to store missing after a slice that had a median).
  • varm(A, M::AbstractArray) without dims throws an ArgumentError (Statistics throws a MethodError).
  • Two-argument cov with no variables returns an empty matrix (Statistics throws a BoundsError from first(C)).
  • median of an integer array along dims is computed in Float64 on the device, as in Statistics, so on devices without Float64 (Metal, some Intel GPUs) it fails to compile. The tests skip these cases there.

Not covered: wrappers such as adjoint, PermutedDims and strided views still scalar-index, because of first(A) in Statistics' _mean. That is being fixed upstream.

Performance

RTX 5080, Float32 data, best of 10, synchronized:

main this PR
median(v), 2^26 elements 113 ms (host copy) 11.5 ms
median(v), 10^6 elements 1.66 ms 0.39 ms
median(A; dims=1), 4096×4096 scalar indexing 2.53 ms
median(A; dims=2), 4096×4096 scalar indexing 3.48 ms
median(B; dims=1), 64×2^20 scalar indexing 2.12 ms
quantile(v, [0.1, 0.5, 0.9]), 2^26 scalar indexing (4.6 s via Array(v)) 11.0 ms
quantile(v, [0.1, 0.5, 0.9]), 10^6 scalar indexing 0.35 ms

Other backends, Float32, a 2^24-element vector and a 4096×4096 matrix, best of 5:

Metal (M1) main Metal PR oneAPI (Arc A770) main oneAPI PR
median(v) 37 ms 74 ms 43 ms 16.5 ms
median(A; dims=1) 3.7 s 124 ms scalar indexing 8.6 ms
quantile(v, [0.1, 0.5, 0.9]) 2.5 s 74 ms scalar indexing 16.5 ms

On Metal, whole-vector median gets slower: main copies to unified memory and runs a CPU quickselect, which beats AK's GPU sort on the M1. A select primitive in AK should change that.

Tests

The statistics testsuite now covers median, quantile, two-argument cov/cor, complex and integer var, mixed-precision and empty inputs, NaN and missing data, and error precedence. Most of the new checks compare exact values, types and error types with Statistics. Cases that need Float64 on the device are skipped when the backend lacks it.

Supersedes the mean/var part of JuliaGPU/AcceleratedKernels.jl#64. Thanks to @yolhan83 for raising it: the conclusion there was that the Statistics front end belongs in GPUArrays, with AK providing the kernels. mean was already handled by #825.

varm on GPU arrays was restricted to real data, so complex arrays fell back
to Statistics' scalar loop. Sum abs2(a - m) for any number type, with the
real floating-point result type that Statistics' varm! uses, and match its
other rules: an empty array gives NaN rather than zero, the means of
nonempty data must have the reduced shape (trailing singleton dimensions
allowed, and not added to the result), and an array of means without dims
is an ArgumentError rather than an UndefKeywordError.

The squared deviations are summed in the result type, or in their own type
where that is wider, and scaled afterwards. Before, each term was scaled
first, which rounded small Float16 deviations to zero.
Statistics' two-argument covzm takes the result type from first(C), its
cov2cor! for two sets of standard deviations loops over the elements, and
its corm of two vectors accumulates in a scalar loop, so cov(X, Y),
cov(x, Y), cor(x, y) and cor(X, Y) all needed scalar indexing. Infer the
type instead, scale by the standard deviations in one broadcast, and sum
the three terms of corm in one reduction, keeping Statistics' scaling of
the result.
median(A) copied GPU arrays to the host and sorted them there,
median(A; dims) went through mapslices, and median! of an even number of
values indexed the two middle elements of the sorted array one by one.
Sort on the device instead, and gather the middle values. The sort may be
unstable, since equal values can only be told apart by their NaN payloads.
The last value of each slice tells whether the slice contains NaN. Reduced
dimensions are combined into one, so dims can be any set of dimensions.

Unlike Statistics, a slice with NaNs gives one of them rather than the
first. An empty result is an empty array, where mapslices throws a
BoundsError, and slices with missing values give missing in a
Union{Missing,T} array, which mapslices fails to store after a slice with
a median.

The sorting and gathering go through _select!, which has the contract of a
selection primitive, so that one can replace them.
Statistics' quantile! partially sorts with sort!(v, lo, hi, ...) and reads
the order statistics it needs one by one, which GPU arrays only support by
scalar indexing, and quantile of a matrix collects it to the host. Gather
all the order statistics for all probabilities at once instead: quantile!
sorts its input on the device, fully where Statistics documents a partial
sort, and quantile selects from a copy through _select!.

The arithmetic is Statistics' own: _quantile runs on a stand-in for the
sorted data that first records the positions it reads, which depend only
on the length, the probabilities, alpha and beta, and then answers with
the gathered values. Probabilities out of bounds and NaN or missing data
are reported in Statistics' order. The result has the container of the
probabilities: a tuple for a tuple, and for an array a GPU array if the
array is on the device, a host array otherwise.
@maleadt
maleadt added this pull request to stack #870 November 27, 2026 11:51
@maleadt
maleadt merged commit b9e945e into main Nov 27, 2026
9 checks passed
@maleadt
maleadt deleted the tb/statistics branch November 27, 2026 13:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant