Repository navigation
Compute median, quantile, two-argument cov/cor and complex var on the device - #868
Merged
Merged
Conversation
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.
This was referenced Nov 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Several Statistics functions either scalar-index GPU arrays or copy them to the host:
median(A; dims)goes throughmapslices, andmedian!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.quantileandquantile!goes through Statistics'sort!(v, lo, hi, PartialQuickSort)and then reads each order statistic separately.cov(X, Y)takes its result type fromfirst(C).cor(x, y)accumulates in a scalar loop, andcor(X, Y)scales with acov2cor!loop.var(A; dims)of complex arrays falls back to Statistics' loop, because GPUArrays'varmonly 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.varmnow 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-vectorcorsums 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, becauseislesssorts 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_quantilearithmetic, run on host stand-ins for the sorted data, so the interpolation is bit-identical for everyalpha/beta. Out-of-bounds probabilities and NaN ormissingdata are reported in Statistics' order.quantile!sorts its input, as its docstring says.quantileleaves 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 makesmediananother 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 arraypreturns an array inp's container: a host array for hostp, a GPU array for GPUp. A tuplepgives a tuple.medianof 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'mapslicesthrows aBoundsError). It returns aUnion{Missing,T}array when slices containmissing(mapslicesfails to storemissingafter a slice that had a median).varm(A, M::AbstractArray)withoutdimsthrows anArgumentError(Statistics throws aMethodError).covwith no variables returns an empty matrix (Statistics throws aBoundsErrorfromfirst(C)).medianof an integer array alongdimsis 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,PermutedDimsand strided views still scalar-index, because offirst(A)in Statistics'_mean. That is being fixed upstream.Performance
RTX 5080, Float32 data, best of 10, synchronized:
median(v), 2^26 elementsmedian(v), 10^6 elementsmedian(A; dims=1), 4096×4096median(A; dims=2), 4096×4096median(B; dims=1), 64×2^20quantile(v, [0.1, 0.5, 0.9]), 2^26Array(v))quantile(v, [0.1, 0.5, 0.9]), 10^6Other backends, Float32, a 2^24-element vector and a 4096×4096 matrix, best of 5:
median(v)median(A; dims=1)quantile(v, [0.1, 0.5, 0.9])On Metal, whole-vector
mediangets 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
missingdata, 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/varpart 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.meanwas already handled by #825.