From 872aa27171cf72d7c47fdfd3ab35170271ce9804 Mon Sep 17 00:00:00 2001 From: CarloLucibello Date: Tue, 1 Dec 2026 20:30:19 +0100 Subject: [PATCH 1/2] Compute products of `Dual` matrices with BLAS Add 5-argument `mul!` methods for dense arrays of `Dual`s over `Float32` or `Float64` that multiply their values and partials with BLAS (CUBLAS for GPU arrays) instead of the generic fallback. Fixes #854. Co-Authored-By: Claude Opus 5.5 --- src/dual.jl | 129 +++++++++++++++++++++++++++++++++++++++++++++++ test/MiscTest.jl | 70 +++++++++++++++++++++++++ 2 files changed, 199 insertions(+) diff --git a/src/dual.jl b/src/dual.jl index 64b43a62..f84dec5e 100644 --- a/src/dual.jl +++ b/src/dual.jl @@ -873,6 +873,135 @@ function _eigen_hermitian(A::DualMatrixRealComplex{T,<:Real,N}) where {T,N} return Eigen(_to_duals(Val(T), λ, λ_partials), _to_duals(Val(T), Q, Q_partials)) end +# Matrix products with BLAS # +#---------------------------# + +# A dense array of `Dual{T,V,N}` stores N+1 numbers of type `V` per element: the value, then the +# partials. Products are linear in each factor, so for `V<:BlasReal` we compute them on these +# numbers with BLAS (or the vendor library of a GPU array) instead of the generic fallback. + +const _AdjOrTrans{T,S} = Union{Adjoint{T,S},Transpose{T,S}} +const _DualMatrix{T,V,N} = Union{DenseMatrix{Dual{T,V,N}},_AdjOrTrans{Dual{T,V,N},<:DenseMatrix{Dual{T,V,N}}}} +const _BlasMatrix{V} = Union{StridedMatrix{V},_AdjOrTrans{V,<:StridedMatrix{V}}} +# excludes `Dual` scalars +const _BlasScalar = Union{Integer,AbstractFloat} + +# On Julia 1.10, GPUArrays overloads `mul!` for GPU arrays of any element type, which would make +# methods for all dense outputs ambiguous +@static if VERSION < v"1.11" + const _DualOutMatrix{T,V,N} = Matrix{Dual{T,V,N}} + const _DualOutVector{T,V,N} = Vector{Dual{T,V,N}} +else + const _DualOutMatrix{T,V,N} = DenseMatrix{Dual{T,V,N}} + const _DualOutVector{T,V,N} = DenseVector{Dual{T,V,N}} +end + +# `(N+1, size(x)...)` array of the values and partials of `x` +function _fields(x::DenseArray{Dual{T,V,N}}) where {T,V,N} + return N == 0 ? reshape(reinterpret(V, x), 1, size(x)...) : reinterpret(reshape, V, x) +end + +_dense(A::DenseMatrix) = A +_dense(A::_AdjOrTrans) = copy(A) + +# `(k, n, N+1)` array of the values and partials of the `k×n` matrix `B`, with the partials of +# each column of `B` contiguous so that a single product with BLAS covers all of them +_stacked_fields(B::DenseMatrix{<:Dual}) = permutedims(_fields(B), (2, 3, 1)) +_stacked_fields(B::_AdjOrTrans{<:Dual,<:DenseMatrix}) = permutedims(_fields(parent(B)), (3, 2, 1)) + +function _check_mul(C, A, B) + mA, nA = size(A) + mB, nB = size(B, 1), size(B, 2) + nA == mB || throw(DimensionMismatch(lazy"A has dimensions ($mA,$nA) but B has dimensions ($mB,$nB)")) + size(C, 1) == mA && size(C, 2) == nB || + throw(DimensionMismatch(lazy"C has dimensions $(size(C)), should have ($mA,$nB)")) + (Base.mightalias(C, A) || Base.mightalias(C, B)) && + throw(ArgumentError("output array must not be aliased with an input array")) + return nothing +end + +# `Dual`s from their values and partials, and partials added to `Dual`s; as callable structs +# rather than closures so that they can be broadcast over GPU arrays +struct _ToDual{T} end +(::_ToDual{T})(v, ps...) where {T} = Dual{T}(v, ps) +struct _AddPartials end +(::_AddPartials)(d::Dual{T}, ps...) where {T} = Dual{T}(value(d), partials(d) + Partials(ps)) + +_planes(X::AbstractArray{<:Any,3}, ::Val{K}) where {K} = ntuple(l -> view(X, :, :, l), Val(K)) + +# Viewed as numbers, `A` is a `(N+1)m×k` matrix and `C` a `(N+1)m×n` one +function _mul_dual_real!(C::AbstractVecOrMat{Dual{T,V,N}}, A, B, α, β) where {T,V,N} + mul!(reinterpret(V, C), reinterpret(V, _dense(A)), B, α, β) + return C +end + +function _mul_real_dual!(C::AbstractMatrix{Dual{T,V,N}}, A, B, α, β) where {T,V,N} + m, (k, n) = size(A, 1), size(B) + Bs = _stacked_fields(B) + Cs = similar(Bs, m, n, N + 1) + mul!(reshape(Cs, m, n * (N + 1)), A, reshape(Bs, k, n * (N + 1)), α, false) + AB = Broadcast.broadcasted(_ToDual{T}(), _planes(Cs, Val(N + 1))...) + # `C` may be uninitialized if `β` is zero + iszero(β) ? (C .= AB) : (C .= AB .+ β .* C) + return C +end + +# The fields of `y = A * x` are the `(N+1)×m` matrix `fields(x) * transpose(A)` +function _mul_real_dual!(y::AbstractVector{Dual{T,V,N}}, A, x, α, β) where {T,V,N} + mul!(_fields(y), _fields(x), transpose(A), α, β) + return y +end + +# The values of `A` times `B`, plus the partials of `A` times the values of `B` +function _mul_dual_dual!(C::AbstractMatrix{Dual{T,V,N}}, A, B, α, β) where {T,V,N} + Ad = _dense(A) + m, (k, n) = size(A, 1), size(B) + Bs = reshape(_stacked_fields(B), k, n * (N + 1)) + mul!(reinterpret(V, C), reinterpret(V, Ad), view(Bs, :, 1:n), α, β) + if N > 0 + Cs = similar(Bs, m, n, N) + mul!(reshape(Cs, m, n * N), value.(Ad), view(Bs, :, (n + 1):(n * (N + 1))), α, false) + C .= _AddPartials().(C, _planes(Cs, Val(N))...) + end + return C +end + +# NaN-safe mode zeroes the product of a zero partial and a value that is not finite, which BLAS +# does not, so with such values we take LinearAlgebra's generic method +_finite_values(X::AbstractArray{<:Dual}) = all(isfinite ∘ value, X) +_finite_values(X::AbstractArray) = all(isfinite, X) + +function _generic_mul!(C::AbstractMatrix, A, B, α, β) + return invoke(mul!, Tuple{AbstractMatrix,AbstractVecOrMat,AbstractVecOrMat,Number,Number}, C, A, B, α, β) +end +function _generic_mul!(y::AbstractVector, A, x, α, β) + return invoke(mul!, Tuple{AbstractVector,AbstractVecOrMat,AbstractVector,Number,Number}, y, A, x, α, β) +end + +function _blas_mul!(f!, C, A, B, α, β) + _check_mul(C, A, B) + if NANSAFE_MODE_ENABLED && !(_finite_values(A) && _finite_values(B)) + return _generic_mul!(C, A, B, α, β) + end + return f!(C, A, B, α, β) +end + +function LinearAlgebra.mul!(C::_DualOutMatrix{T,V,N}, A::_DualMatrix{T,V,N}, B::_BlasMatrix{V}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} + return _blas_mul!(_mul_dual_real!, C, A, B, α, β) +end +function LinearAlgebra.mul!(C::_DualOutMatrix{T,V,N}, A::_BlasMatrix{V}, B::_DualMatrix{T,V,N}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} + return _blas_mul!(_mul_real_dual!, C, A, B, α, β) +end +function LinearAlgebra.mul!(C::_DualOutMatrix{T,V,N}, A::_DualMatrix{T,V,N}, B::_DualMatrix{T,V,N}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} + return _blas_mul!(_mul_dual_dual!, C, A, B, α, β) +end +function LinearAlgebra.mul!(y::_DualOutVector{T,V,N}, A::_DualMatrix{T,V,N}, x::StridedVector{V}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} + return _blas_mul!(_mul_dual_real!, y, A, x, α, β) +end +function LinearAlgebra.mul!(y::_DualOutVector{T,V,N}, A::_BlasMatrix{V}, x::DenseVector{Dual{T,V,N}}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} + return _blas_mul!(_mul_real_dual!, y, A, x, α, β) +end + # Functions in SpecialFunctions which return tuples # # Their derivatives are not defined in DiffRules # #---------------------------------------------------# diff --git a/test/MiscTest.jl b/test/MiscTest.jl index e8068e95..ec5f92b2 100644 --- a/test/MiscTest.jl +++ b/test/MiscTest.jl @@ -219,4 +219,74 @@ end @test B_mmatrix == B end +@testset "matrix products with BLAS" begin + randdual(V, N, dims...) = ForwardDiff.Dual{TestTag,V,N}[ForwardDiff.Dual{TestTag}(rand(V), ntuple(_ -> rand(V), N)) for _ in CartesianIndices(dims)] + values_of(X) = eltype(X) <: ForwardDiff.Dual ? ForwardDiff.value.(X) : X + partials_of(X, i) = eltype(X) <: ForwardDiff.Dual ? ForwardDiff.partials.(X, i) : zero(X) + + function test_mul(C, A, B, α, β) + C0 = copy(C) + @test which(mul!, typeof.((C, A, B, α, β))).module === ForwardDiff + @test mul!(C, A, B, α, β) === C + # `C` may hold NaNs if `β` is zero + scaled(X, Y) = iszero(β) ? α * X : α * X + β * Y + @test ForwardDiff.value.(C) ≈ scaled(values_of(A) * values_of(B), ForwardDiff.value.(C0)) + for i in 1:ForwardDiff.npartials(eltype(C)) + ∂AB = partials_of(A, i) * values_of(B) + values_of(A) * partials_of(B, i) + @test ForwardDiff.partials.(C, i) ≈ scaled(∂AB, ForwardDiff.partials.(C0, i)) + end + end + + @testset "N = $N" for N in (0, 2) + m, k, n = 3, 4, 2 + D(dims...) = randdual(Float64, N, dims...) + # `N = 0` only differs in how the fields are viewed + for β in (0.0, 0.5), wrap in (N == 0 ? (false,) : (false, true)) + α = 2.0 + C(dims...) = iszero(β) ? fill(ForwardDiff.Dual{TestTag}(NaN, ntuple(_ -> NaN, N)), dims...) : D(dims...) + # transposed and adjoint factors + fA(X) = wrap ? transpose(permutedims(X)) : X + fB(X) = wrap ? adjoint(permutedims(X)) : X + test_mul(C(m, n), fA(D(m, k)), fB(rand(k, n)), α, β) + test_mul(C(m, n), fA(rand(m, k)), fB(D(k, n)), α, β) + test_mul(C(m, n), fA(D(m, k)), fB(D(k, n)), α, β) + test_mul(C(m), fA(D(m, k)), rand(k), α, β) + test_mul(C(m), fB(rand(m, k)), D(k), α, β) + end + test_mul(D(m, n), view(rand(m + 1, k), 2:(m + 1), :), D(k, n), true, false) + test_mul(D(m, n), D(m, 0), D(0, n), true, false) + end + + A, B = randdual(Float32, 3, 3, 4), randdual(Float32, 3, 4, 2) + test_mul(randdual(Float32, 3, 3, 2), A, B, true, false) + @test ForwardDiff.value.(A * B) ≈ ForwardDiff.value.(A) * ForwardDiff.value.(B) + + D2(dims...) = randdual(Float64, 2, dims...) + @test_throws DimensionMismatch mul!(D2(3, 2), D2(3, 4), rand(5, 2)) + @test_throws DimensionMismatch mul!(D2(2, 2), rand(3, 4), D2(4, 2)) + @test_throws DimensionMismatch mul!(D2(3), rand(3, 4), D2(5)) + A = D2(3, 3) + @test_throws ArgumentError mul!(A, A, rand(3, 3)) + @test_throws ArgumentError mul!(A, rand(3, 3), transpose(A)) + + # `Dual` scalars take the generic path + A, B, α = D2(3, 4), rand(4, 2), ForwardDiff.Dual{TestTag}(2.0, (1.0, 0.0)) + @test which(mul!, typeof.((D2(3, 2), A, B, α, false))).module === LinearAlgebra + C = mul!(D2(3, 2), A, B, α, false) + @test ForwardDiff.value.(C) ≈ 2 * ForwardDiff.value.(A) * B + @test ForwardDiff.partials.(C, 1) ≈ (ForwardDiff.value.(A) + 2 * ForwardDiff.partials.(A, 1)) * B + + if ForwardDiff.NANSAFE_MODE_ENABLED + # zero partials times values that are not finite stay zero + A = ForwardDiff.Dual{TestTag}.([1.0 2.0; 3.0 4.0], 0.0) + B = [Inf 1.0; 1.0 1.0] + for (X, Y) in ((A, B), (B, A), (A, ForwardDiff.Dual{TestTag}.(B, 0.0))) + C = X * Y + Cg = invoke(mul!, Tuple{AbstractMatrix,AbstractVecOrMat,AbstractVecOrMat,Number,Number}, similar(C), X, Y, true, false) + @test isequal(ForwardDiff.value.(C), ForwardDiff.value.(Cg)) + @test iszero(ForwardDiff.partials.(C, 1)) + end + end +end + end # module From 5e10c3eed3dc5745f6529a5d88e1ae5ff4a1f7df Mon Sep 17 00:00:00 2001 From: CarloLucibello Date: Wed, 2 Dec 2026 00:34:49 +0100 Subject: [PATCH 2/2] Multiply only `Dual` by real matrices, through the 7-argument `mul!` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Following review, replace the 5-argument `mul!` methods by one method of the storage-level 7-argument `mul!` (Julia 1.13 and later) for a strided matrix of `Dual`s times a strided real matrix, which is a single BLAS call on the reinterpreted arrays. Products of a real and a `Dual` matrix, of two `Dual` matrices, with vectors, and 2×2 and 3×3 products take the generic method again. Co-Authored-By: Claude Opus 5.5 --- src/dual.jl | 142 +++++++---------------------------------------- test/MiscTest.jl | 95 +++++++++++++------------------ 2 files changed, 58 insertions(+), 179 deletions(-) diff --git a/src/dual.jl b/src/dual.jl index f84dec5e..a4b1d922 100644 --- a/src/dual.jl +++ b/src/dual.jl @@ -876,130 +876,26 @@ end # Matrix products with BLAS # #---------------------------# -# A dense array of `Dual{T,V,N}` stores N+1 numbers of type `V` per element: the value, then the -# partials. Products are linear in each factor, so for `V<:BlasReal` we compute them on these -# numbers with BLAS (or the vendor library of a GPU array) instead of the generic fallback. - -const _AdjOrTrans{T,S} = Union{Adjoint{T,S},Transpose{T,S}} -const _DualMatrix{T,V,N} = Union{DenseMatrix{Dual{T,V,N}},_AdjOrTrans{Dual{T,V,N},<:DenseMatrix{Dual{T,V,N}}}} -const _BlasMatrix{V} = Union{StridedMatrix{V},_AdjOrTrans{V,<:StridedMatrix{V}}} -# excludes `Dual` scalars -const _BlasScalar = Union{Integer,AbstractFloat} - -# On Julia 1.10, GPUArrays overloads `mul!` for GPU arrays of any element type, which would make -# methods for all dense outputs ambiguous -@static if VERSION < v"1.11" - const _DualOutMatrix{T,V,N} = Matrix{Dual{T,V,N}} - const _DualOutVector{T,V,N} = Vector{Dual{T,V,N}} -else - const _DualOutMatrix{T,V,N} = DenseMatrix{Dual{T,V,N}} - const _DualOutVector{T,V,N} = DenseVector{Dual{T,V,N}} -end - -# `(N+1, size(x)...)` array of the values and partials of `x` -function _fields(x::DenseArray{Dual{T,V,N}}) where {T,V,N} - return N == 0 ? reshape(reinterpret(V, x), 1, size(x)...) : reinterpret(reshape, V, x) -end - -_dense(A::DenseMatrix) = A -_dense(A::_AdjOrTrans) = copy(A) - -# `(k, n, N+1)` array of the values and partials of the `k×n` matrix `B`, with the partials of -# each column of `B` contiguous so that a single product with BLAS covers all of them -_stacked_fields(B::DenseMatrix{<:Dual}) = permutedims(_fields(B), (2, 3, 1)) -_stacked_fields(B::_AdjOrTrans{<:Dual,<:DenseMatrix}) = permutedims(_fields(parent(B)), (3, 2, 1)) - -function _check_mul(C, A, B) - mA, nA = size(A) - mB, nB = size(B, 1), size(B, 2) - nA == mB || throw(DimensionMismatch(lazy"A has dimensions ($mA,$nA) but B has dimensions ($mB,$nB)")) - size(C, 1) == mA && size(C, 2) == nB || - throw(DimensionMismatch(lazy"C has dimensions $(size(C)), should have ($mA,$nB)")) - (Base.mightalias(C, A) || Base.mightalias(C, B)) && - throw(ArgumentError("output array must not be aliased with an input array")) - return nothing -end - -# `Dual`s from their values and partials, and partials added to `Dual`s; as callable structs -# rather than closures so that they can be broadcast over GPU arrays -struct _ToDual{T} end -(::_ToDual{T})(v, ps...) where {T} = Dual{T}(v, ps) -struct _AddPartials end -(::_AddPartials)(d::Dual{T}, ps...) where {T} = Dual{T}(value(d), partials(d) + Partials(ps)) - -_planes(X::AbstractArray{<:Any,3}, ::Val{K}) where {K} = ntuple(l -> view(X, :, :, l), Val(K)) - -# Viewed as numbers, `A` is a `(N+1)m×k` matrix and `C` a `(N+1)m×n` one -function _mul_dual_real!(C::AbstractVecOrMat{Dual{T,V,N}}, A, B, α, β) where {T,V,N} - mul!(reinterpret(V, C), reinterpret(V, _dense(A)), B, α, β) - return C -end - -function _mul_real_dual!(C::AbstractMatrix{Dual{T,V,N}}, A, B, α, β) where {T,V,N} - m, (k, n) = size(A, 1), size(B) - Bs = _stacked_fields(B) - Cs = similar(Bs, m, n, N + 1) - mul!(reshape(Cs, m, n * (N + 1)), A, reshape(Bs, k, n * (N + 1)), α, false) - AB = Broadcast.broadcasted(_ToDual{T}(), _planes(Cs, Val(N + 1))...) - # `C` may be uninitialized if `β` is zero - iszero(β) ? (C .= AB) : (C .= AB .+ β .* C) - return C -end - -# The fields of `y = A * x` are the `(N+1)×m` matrix `fields(x) * transpose(A)` -function _mul_real_dual!(y::AbstractVector{Dual{T,V,N}}, A, x, α, β) where {T,V,N} - mul!(_fields(y), _fields(x), transpose(A), α, β) - return y -end - -# The values of `A` times `B`, plus the partials of `A` times the values of `B` -function _mul_dual_dual!(C::AbstractMatrix{Dual{T,V,N}}, A, B, α, β) where {T,V,N} - Ad = _dense(A) - m, (k, n) = size(A, 1), size(B) - Bs = reshape(_stacked_fields(B), k, n * (N + 1)) - mul!(reinterpret(V, C), reinterpret(V, Ad), view(Bs, :, 1:n), α, β) - if N > 0 - Cs = similar(Bs, m, n, N) - mul!(reshape(Cs, m, n * N), value.(Ad), view(Bs, :, (n + 1):(n * (N + 1))), α, false) - C .= _AddPartials().(C, _planes(Cs, Val(N))...) - end - return C -end - -# NaN-safe mode zeroes the product of a zero partial and a value that is not finite, which BLAS -# does not, so with such values we take LinearAlgebra's generic method -_finite_values(X::AbstractArray{<:Dual}) = all(isfinite ∘ value, X) -_finite_values(X::AbstractArray) = all(isfinite, X) - -function _generic_mul!(C::AbstractMatrix, A, B, α, β) - return invoke(mul!, Tuple{AbstractMatrix,AbstractVecOrMat,AbstractVecOrMat,Number,Number}, C, A, B, α, β) -end -function _generic_mul!(y::AbstractVector, A, x, α, β) - return invoke(mul!, Tuple{AbstractVector,AbstractVecOrMat,AbstractVector,Number,Number}, y, A, x, α, β) -end - -function _blas_mul!(f!, C, A, B, α, β) - _check_mul(C, A, B) - if NANSAFE_MODE_ENABLED && !(_finite_values(A) && _finite_values(B)) - return _generic_mul!(C, A, B, α, β) +# Viewed as numbers, an `m×k` matrix of `Dual{T,V,N}` is an `(N+1)m×k` matrix of `V`, so its +# product with a matrix of `V` is a product of matrices of `V`, computed with BLAS. LinearAlgebra +# calls this method after unwrapping the factors (`tA`/`tB` record how), and its fallback for +# matrices of `V` is generic, so that product goes through the 5-argument `mul!`. +@static if VERSION >= v"1.13" + Base.@constprop :aggressive function LinearAlgebra.mul!(C::StridedMatrix{Dual{T,V,N}}, tA, tB, A::StridedMatrix{Dual{T,V,N}}, B::StridedMatrix{V}, α::Number, β::Number) where {T,V<:LinearAlgebra.BlasReal,N} + m, (k, n) = size(A, 1), tB == 'N' ? size(B) : reverse(size(B)) + use_blas = tA == 'N' && tB in ('N', 'T', 'C') && size(A, 2) == k && size(C) == (m, n) && + stride(A, 1) == stride(C, 1) == 1 && !(α isa Dual || β isa Dual) && + # as for matrices of `V`, small square products are faster without BLAS + !(m == k == n <= 3) && + # NaN-safe mode zeroes the product of a zero partial and a number that is not finite, + # which BLAS does not + (!NANSAFE_MODE_ENABLED || (isfinite(α) && isfinite(β) && all(isfinite, B))) + if use_blas + mul!(reinterpret(V, C), reinterpret(V, A), tB == 'N' ? B : transpose(B), α, β) + return C + end + return invoke(mul!, Tuple{AbstractVecOrMat,Any,Any,AbstractVecOrMat,AbstractVecOrMat,Number,Number}, C, tA, tB, A, B, α, β) end - return f!(C, A, B, α, β) -end - -function LinearAlgebra.mul!(C::_DualOutMatrix{T,V,N}, A::_DualMatrix{T,V,N}, B::_BlasMatrix{V}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} - return _blas_mul!(_mul_dual_real!, C, A, B, α, β) -end -function LinearAlgebra.mul!(C::_DualOutMatrix{T,V,N}, A::_BlasMatrix{V}, B::_DualMatrix{T,V,N}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} - return _blas_mul!(_mul_real_dual!, C, A, B, α, β) -end -function LinearAlgebra.mul!(C::_DualOutMatrix{T,V,N}, A::_DualMatrix{T,V,N}, B::_DualMatrix{T,V,N}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} - return _blas_mul!(_mul_dual_dual!, C, A, B, α, β) -end -function LinearAlgebra.mul!(y::_DualOutVector{T,V,N}, A::_DualMatrix{T,V,N}, x::StridedVector{V}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} - return _blas_mul!(_mul_dual_real!, y, A, x, α, β) -end -function LinearAlgebra.mul!(y::_DualOutVector{T,V,N}, A::_BlasMatrix{V}, x::DenseVector{Dual{T,V,N}}, α::_BlasScalar, β::_BlasScalar) where {T,V<:LinearAlgebra.BlasReal,N} - return _blas_mul!(_mul_real_dual!, y, A, x, α, β) end # Functions in SpecialFunctions which return tuples # diff --git a/test/MiscTest.jl b/test/MiscTest.jl index ec5f92b2..79ca872a 100644 --- a/test/MiscTest.jl +++ b/test/MiscTest.jl @@ -220,72 +220,55 @@ end end @testset "matrix products with BLAS" begin - randdual(V, N, dims...) = ForwardDiff.Dual{TestTag,V,N}[ForwardDiff.Dual{TestTag}(rand(V), ntuple(_ -> rand(V), N)) for _ in CartesianIndices(dims)] - values_of(X) = eltype(X) <: ForwardDiff.Dual ? ForwardDiff.value.(X) : X - partials_of(X, i) = eltype(X) <: ForwardDiff.Dual ? ForwardDiff.partials.(X, i) : zero(X) + D(N, dims...) = ForwardDiff.Dual{TestTag,Float64,N}[ForwardDiff.Dual{TestTag}(rand(), ntuple(_ -> rand(), N)) for _ in CartesianIndices(dims)] + vals(X) = ForwardDiff.value.(X) + parts(X, i) = ForwardDiff.partials.(X, i) - function test_mul(C, A, B, α, β) + function test_mul(C, A, B, α = true, β = false) C0 = copy(C) - @test which(mul!, typeof.((C, A, B, α, β))).module === ForwardDiff - @test mul!(C, A, B, α, β) === C - # `C` may hold NaNs if `β` is zero + # `C` may be NaN if `β` is zero scaled(X, Y) = iszero(β) ? α * X : α * X + β * Y - @test ForwardDiff.value.(C) ≈ scaled(values_of(A) * values_of(B), ForwardDiff.value.(C0)) + @test mul!(C, A, B, α, β) === C + @test vals(C) ≈ scaled(vals(A) * B, vals(C0)) for i in 1:ForwardDiff.npartials(eltype(C)) - ∂AB = partials_of(A, i) * values_of(B) + values_of(A) * partials_of(B, i) - @test ForwardDiff.partials.(C, i) ≈ scaled(∂AB, ForwardDiff.partials.(C0, i)) + @test parts(C, i) ≈ scaled(parts(A, i) * B, parts(C0, i)) end end - @testset "N = $N" for N in (0, 2) - m, k, n = 3, 4, 2 - D(dims...) = randdual(Float64, N, dims...) - # `N = 0` only differs in how the fields are viewed - for β in (0.0, 0.5), wrap in (N == 0 ? (false,) : (false, true)) - α = 2.0 - C(dims...) = iszero(β) ? fill(ForwardDiff.Dual{TestTag}(NaN, ntuple(_ -> NaN, N)), dims...) : D(dims...) - # transposed and adjoint factors - fA(X) = wrap ? transpose(permutedims(X)) : X - fB(X) = wrap ? adjoint(permutedims(X)) : X - test_mul(C(m, n), fA(D(m, k)), fB(rand(k, n)), α, β) - test_mul(C(m, n), fA(rand(m, k)), fB(D(k, n)), α, β) - test_mul(C(m, n), fA(D(m, k)), fB(D(k, n)), α, β) - test_mul(C(m), fA(D(m, k)), rand(k), α, β) - test_mul(C(m), fB(rand(m, k)), D(k), α, β) - end - test_mul(D(m, n), view(rand(m + 1, k), 2:(m + 1), :), D(k, n), true, false) - test_mul(D(m, n), D(m, 0), D(0, n), true, false) + for N in (0, 2), (m, k, n) in ((2, 2, 2), (5, 3, 4)), β in (0, 0.5) + C() = iszero(β) ? fill(ForwardDiff.Dual{TestTag}(NaN, ntuple(_ -> NaN, N)), m, n) : D(N, m, n) + test_mul(C(), D(N, m, k), rand(k, n), 2, β) + test_mul(C(), D(N, m, k), transpose(rand(n, k)), 2, β) + test_mul(C(), D(N, m, k), rand(n, k)', 2, β) + test_mul(C(), transpose(D(N, k, m)), rand(k, n), 2, β) end - - A, B = randdual(Float32, 3, 3, 4), randdual(Float32, 3, 4, 2) - test_mul(randdual(Float32, 3, 3, 2), A, B, true, false) - @test ForwardDiff.value.(A * B) ≈ ForwardDiff.value.(A) * ForwardDiff.value.(B) - - D2(dims...) = randdual(Float64, 2, dims...) - @test_throws DimensionMismatch mul!(D2(3, 2), D2(3, 4), rand(5, 2)) - @test_throws DimensionMismatch mul!(D2(2, 2), rand(3, 4), D2(4, 2)) - @test_throws DimensionMismatch mul!(D2(3), rand(3, 4), D2(5)) - A = D2(3, 3) - @test_throws ArgumentError mul!(A, A, rand(3, 3)) - @test_throws ArgumentError mul!(A, rand(3, 3), transpose(A)) - - # `Dual` scalars take the generic path - A, B, α = D2(3, 4), rand(4, 2), ForwardDiff.Dual{TestTag}(2.0, (1.0, 0.0)) - @test which(mul!, typeof.((D2(3, 2), A, B, α, false))).module === LinearAlgebra - C = mul!(D2(3, 2), A, B, α, false) - @test ForwardDiff.value.(C) ≈ 2 * ForwardDiff.value.(A) * B - @test ForwardDiff.partials.(C, 1) ≈ (ForwardDiff.value.(A) + 2 * ForwardDiff.partials.(A, 1)) * B + test_mul(view(D(2, 5, 3), 2:4, 1:2), view(D(2, 4, 6), 1:3, 2:5), view(rand(5, 3), 1:4, 1:2)) + test_mul(view(D(2, 6, 2), 1:2:6, :), view(D(2, 3, 8), :, 1:2:8), rand(4, 2)) + test_mul(D(2, 3, 2), D(2, 3, 0), rand(0, 2), π, 0.5) + test_mul(D(2, 3, 3), D(2, 3, 3), Symmetric(rand(3, 3))) + A32 = ForwardDiff.Dual{TestTag}.(rand(Float32, 3, 4), rand(Float32, 3, 4)) + test_mul(similar(A32, 3, 2), A32, rand(Float32, 4, 2), 1//2) + + A, B, α = D(2, 3, 4), rand(4, 2), ForwardDiff.Dual{TestTag}(2.0, (1.0, 0.0)) + C = mul!(D(2, 3, 2), A, B, α, false) + @test vals(C) ≈ 2 * vals(A) * B + @test parts(C, 1) ≈ (vals(A) + 2 * parts(A, 1)) * B + @test parts(C, 2) ≈ 2 * parts(A, 2) * B + + An = ForwardDiff.Dual{TestTag}.(ForwardDiff.Dual.(rand(3, 4), rand(3, 4)), ForwardDiff.Dual.(rand(3, 4), rand(3, 4))) + Cn = [sum(An[i, p] * B[p, j] for p in 1:4) for i in 1:3, j in 1:2] + @test reinterpret(Float64, An * B) ≈ reinterpret(Float64, Cn) + + # the sizes are those of the `Dual` matrices + @test_throws r"DimensionMismatch.*\(3, ?4\)" mul!(D(2, 3, 2), D(2, 3, 4), rand(5, 2)) + @test_throws r"DimensionMismatch.*\(3, 3\)" mul!(D(2, 3, 3), D(2, 3, 4), rand(4, 2)) if ForwardDiff.NANSAFE_MODE_ENABLED - # zero partials times values that are not finite stay zero - A = ForwardDiff.Dual{TestTag}.([1.0 2.0; 3.0 4.0], 0.0) - B = [Inf 1.0; 1.0 1.0] - for (X, Y) in ((A, B), (B, A), (A, ForwardDiff.Dual{TestTag}.(B, 0.0))) - C = X * Y - Cg = invoke(mul!, Tuple{AbstractMatrix,AbstractVecOrMat,AbstractVecOrMat,Number,Number}, similar(C), X, Y, true, false) - @test isequal(ForwardDiff.value.(C), ForwardDiff.value.(Cg)) - @test iszero(ForwardDiff.partials.(C, 1)) - end + # zero partials times numbers that are not finite stay zero + A, C = ForwardDiff.Dual{TestTag}.(rand(2, 3), 0.0), ForwardDiff.Dual{TestTag}.(rand(2, 2), 0.0) + @test iszero(parts(A * [Inf 1.0; 1.0 1.0; 1.0 1.0], 1)) + @test iszero(parts(mul!(similar(C), A, ones(3, 2), Inf, false), 1)) + @test iszero(parts(mul!(C, A, ones(3, 2), true, Inf), 1)) end end