From 2ade6c03134683c57a9640a05beb6fdbcbe9c86b Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Fri, 27 Nov 2026 12:51:10 +0100 Subject: [PATCH] Move the Statistics methods into a package extension GPUArrays loaded Statistics.jl for every user, although its methods only matter to code that loads Statistics.jl itself. They now live in StatisticsExt. The overrides that only exist because Statistics.jl's generic methods index into the array (`_mean`, `covzm` and the two-argument `corzm`) move to their own file, in one section per upstream fix (JuliaStats/Statistics.jl#223, #224 and #225), so each can be deleted once GPUArrays requires a Statistics.jl release with it. Julia 1.10 always loads the Statistics.jl it ships with, so that means dropping 1.10. --- Project.toml | 3 +- .../StatisticsExt/StatisticsExt.jl | 71 +++-------------- ext/StatisticsExt/workarounds.jl | 79 +++++++++++++++++++ src/GPUArrays.jl | 1 - 4 files changed, 92 insertions(+), 62 deletions(-) rename src/host/statistics.jl => ext/StatisticsExt/StatisticsExt.jl (83%) create mode 100644 ext/StatisticsExt/workarounds.jl diff --git a/Project.toml b/Project.toml index 5ff4db0ae..44910ebd0 100644 --- a/Project.toml +++ b/Project.toml @@ -19,13 +19,14 @@ Reexport = "189a3867-3050-52da-a836-e630ba90ab69" ScopedValues = "7e506255-f358-4e82-b7e4-beb19740aa63" Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b" SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" -Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [weakdeps] JLD2 = "033835bb-8acc-5ee8-8aae-3f567f8a3819" +Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [extensions] JLD2Ext = "JLD2" +StatisticsExt = "Statistics" [compat] AcceleratedKernels = "0.5.8" diff --git a/src/host/statistics.jl b/ext/StatisticsExt/StatisticsExt.jl similarity index 83% rename from src/host/statistics.jl rename to ext/StatisticsExt/StatisticsExt.jl index 8957a3e13..21d3dc714 100644 --- a/src/host/statistics.jl +++ b/ext/StatisticsExt/StatisticsExt.jl @@ -1,3 +1,8 @@ +module StatisticsExt + +using GPUArrays +using GPUArrays: AK +using LinearAlgebra using Statistics # Two passes, as Statistics.jl: `mean` first, then the sum of `abs2(a - m)`, fused into one @@ -40,47 +45,6 @@ Statistics._std(A::AbstractGPUArray, corrected::Bool, mean, dims) = Statistics._std(A::AbstractGPUArray, corrected::Bool, mean, ::Colon) = sqrt.(Statistics.var(A; corrected=corrected, mean=mean, dims=:)) -# Like Statistics.jl, accumulate in the floating-point type of the result and divide -# afterwards: summing integers overflows, and scaling each term first loses precision. -# The accumulator type is inferred, as computing it from `first(A)` would need scalar indexing. -function Statistics._mean(f, A::AbstractGPUArray, dims) - isempty(A) && return sum(f, A; dims) / 0 - S = Base.promote_op(f, eltype(A)) - T = promote_type(Base.promote_op(/, S, Int), S) - result = sum(_mean_convert(f, T), A; dims) - if dims isa Colon - result / length(A) - else - result ./= _mean_denom(A, dims) - end -end - -# `f` and `T` are static parameters rather than captured values, so the closure stays isbits -# when `f` is a type (e.g. `mean(Float32, A)`) and can be passed to a kernel. -_mean_convert(f::F, ::Type{T}) where {F,T} = x -> convert(T, f(x)) -_mean_convert(::Type{F}, ::Type{T}) where {F,T} = x -> convert(T, F(x)) - -function Statistics.covzm(x::AbstractGPUMatrix, vardim::Int=1; corrected::Bool=true) - C = Statistics.unscaled_covzm(x, vardim) - T = promote_type(typeof(one(eltype(C)) / 1), eltype(C)) - A = convert(AbstractArray{T}, C) - b = 1//(size(x, vardim) - corrected) - A .*= b - return A -end - -# (also for two arguments: the type of the scaled result is inferred, not taken from `first(C)`, -# so that without variables the result is an empty matrix rather than a BoundsError) -function Statistics.covzm(x::AbstractGPUVecOrMat, y::AbstractGPUVecOrMat, vardim::Int; - corrected::Bool=true) - C = Statistics.unscaled_covzm(x, y, vardim) - T = promote_type(typeof(one(eltype(C)) / 1), eltype(C)) - A = convert(AbstractArray{T}, C) - b = 1//(Statistics._getnobs(x, y, vardim) - corrected) - A .*= b - return A -end - function Statistics.cov2cor!(C::AbstractGPUMatrix{T}, xsd::AbstractGPUArray) where T nx = length(xsd) size(C) == (nx, nx) || throw(DimensionMismatch("inconsistent dimensions")) @@ -96,25 +60,6 @@ function Statistics.corzm(x::AbstractGPUMatrix, vardim::Int=1) return Statistics.cov2cor!(c, sqrt.(diag(c))) end -# Statistics.jl's `cov2cor!` for two sets of standard deviations, as one broadcast -# (`xsd` and `ysd` hold one value per row and column of `C`, or are a number) -function _cov2cor!(C, xsd, ysd) - xcol = xsd isa AbstractArray ? reshape(xsd, :, 1) : xsd - yrow = ysd isa AbstractArray ? reshape(ysd, 1, :) : ysd - C .= Statistics.clampcor.(C ./ (xcol .* yrow)) - return C -end - -Statistics.corzm(x::AbstractGPUVector, y::AbstractGPUMatrix, vardim::Int=1) = - _cov2cor!(Statistics.unscaled_covzm(x, y, vardim), sqrt(sum(abs2, x)), - sqrt.(sum(abs2, y; dims=vardim))) -Statistics.corzm(x::AbstractGPUMatrix, y::AbstractGPUVector, vardim::Int=1) = - _cov2cor!(Statistics.unscaled_covzm(x, y, vardim), sqrt.(sum(abs2, x; dims=vardim)), - sqrt(sum(abs2, y))) -Statistics.corzm(x::AbstractGPUMatrix, y::AbstractGPUMatrix, vardim::Int=1) = - _cov2cor!(Statistics.unscaled_covzm(x, y, vardim), sqrt.(sum(abs2, x; dims=vardim)), - sqrt.(sum(abs2, y; dims=vardim))) - # The correlation of two vectors, from the three sums Statistics.jl accumulates in one loop, # here in one reduction, and with its scaling (which keeps `xy / sqrt(xx * yy)` from overflowing) function Statistics.corm(x::AbstractGPUVector{<:Number}, mx, y::AbstractGPUVector{<:Number}, my) @@ -339,3 +284,9 @@ Statistics.quantile(v::AbstractGPUVector, p::Real; sorted::Bool=false, alpha::Re Statistics.quantile(A::AbstractGPUArray, p::Union{AbstractArray, Tuple{Vararg{Real}}}; sorted::Bool=false, alpha::Real=1.0, beta::Real=alpha) = _quantiles(vec(A), p, sorted, alpha, beta) + +# Overrides that only avoid scalar indexing in Statistics.jl's methods, until fixes upstream are +# released; the file says when each can go. +include("workarounds.jl") + +end diff --git a/ext/StatisticsExt/workarounds.jl b/ext/StatisticsExt/workarounds.jl new file mode 100644 index 000000000..aead53796 --- /dev/null +++ b/ext/StatisticsExt/workarounds.jl @@ -0,0 +1,79 @@ +# Workarounds for Statistics.jl methods that would work on GPU arrays as they are, but index +# into them (to take a type from `first(A)`, or in a loop over the elements), which GPU arrays +# only allow as slow scalar indexing. Each section names the Statistics.jl pull request that +# fixes its methods, and can be deleted as a whole once GPUArrays requires a Statistics.jl +# release with that fix. Julia 1.10 always loads the Statistics.jl it ships with, so that +# means dropping 1.10; until then, the sections can at most be skipped on newer Statistics.jl +# with `pkgversion(Statistics)`. The helpers defined here are only used here. + + +## JuliaStats/Statistics.jl#223: `mean` infers its accumulator type instead of calling `f` on +## `first(A)` + +# Like Statistics.jl, accumulate in the floating-point type of the result and divide +# afterwards: summing integers overflows, and scaling each term first loses precision. +# The accumulator type is inferred, as computing it from `first(A)` would need scalar indexing. +function Statistics._mean(f, A::AbstractGPUArray, dims) + isempty(A) && return sum(f, A; dims) / 0 + S = Base.promote_op(f, eltype(A)) + T = promote_type(Base.promote_op(/, S, Int), S) + result = sum(_mean_convert(f, T), A; dims) + if dims isa Colon + result / length(A) + else + result ./= _mean_denom(A, dims) + end +end + +# `f` and `T` are static parameters rather than captured values, so the closure stays isbits +# when `f` is a type (e.g. `mean(Float32, A)`) and can be passed to a kernel. +_mean_convert(f::F, ::Type{T}) where {F,T} = x -> convert(T, f(x)) +_mean_convert(::Type{F}, ::Type{T}) where {F,T} = x -> convert(T, F(x)) + + +## JuliaStats/Statistics.jl#224: `cov` infers the type of its scaled result instead of taking it +## from `first(C)` + +function Statistics.covzm(x::AbstractGPUMatrix, vardim::Int=1; corrected::Bool=true) + C = Statistics.unscaled_covzm(x, vardim) + T = promote_type(typeof(one(eltype(C)) / 1), eltype(C)) + A = convert(AbstractArray{T}, C) + b = 1//(size(x, vardim) - corrected) + A .*= b + return A +end + +# (also for two arguments: the type of the scaled result is inferred, not taken from `first(C)`, +# so that without variables the result is an empty matrix rather than a BoundsError) +function Statistics.covzm(x::AbstractGPUVecOrMat, y::AbstractGPUVecOrMat, vardim::Int; + corrected::Bool=true) + C = Statistics.unscaled_covzm(x, y, vardim) + T = promote_type(typeof(one(eltype(C)) / 1), eltype(C)) + A = convert(AbstractArray{T}, C) + b = 1//(Statistics._getnobs(x, y, vardim) - corrected) + A .*= b + return A +end + + +## JuliaStats/Statistics.jl#225: `cor` of two dense arrays normalizes with a broadcast instead of +## a loop + +# Statistics.jl's `cov2cor!` for two sets of standard deviations, as one broadcast +# (`xsd` and `ysd` hold one value per row and column of `C`, or are a number) +function _cov2cor!(C, xsd, ysd) + xcol = xsd isa AbstractArray ? reshape(xsd, :, 1) : xsd + yrow = ysd isa AbstractArray ? reshape(ysd, 1, :) : ysd + C .= Statistics.clampcor.(C ./ (xcol .* yrow)) + return C +end + +Statistics.corzm(x::AbstractGPUVector, y::AbstractGPUMatrix, vardim::Int=1) = + _cov2cor!(Statistics.unscaled_covzm(x, y, vardim), sqrt(sum(abs2, x)), + sqrt.(sum(abs2, y; dims=vardim))) +Statistics.corzm(x::AbstractGPUMatrix, y::AbstractGPUVector, vardim::Int=1) = + _cov2cor!(Statistics.unscaled_covzm(x, y, vardim), sqrt.(sum(abs2, x; dims=vardim)), + sqrt(sum(abs2, y))) +Statistics.corzm(x::AbstractGPUMatrix, y::AbstractGPUMatrix, vardim::Int=1) = + _cov2cor!(Statistics.unscaled_covzm(x, y, vardim), sqrt.(sum(abs2, x; dims=vardim)), + sqrt.(sum(abs2, y; dims=vardim))) diff --git a/src/GPUArrays.jl b/src/GPUArrays.jl index 19079e2f0..196594702 100644 --- a/src/GPUArrays.jl +++ b/src/GPUArrays.jl @@ -42,7 +42,6 @@ include("host/math.jl") include("host/random.jl") include("host/quirks.jl") include("host/uniformscaling.jl") -include("host/statistics.jl") include("host/sparse.jl") include("host/alloc_cache.jl")