Repository navigation
Multiply matrices of Duals by real matrices with BLAS - #880
CarloLucibello wants to merge 2 commits into
Conversation
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 <noreply@anthropic.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #880 +/- ##
==========================================
+ Coverage 91.05% 91.19% +0.14%
==========================================
Files 11 11
Lines 1084 1147 +63
==========================================
+ Hits 987 1046 +59
- Misses 97 101 +4 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
devmotion
left a comment
There was a problem hiding this comment.
I was curious how the methods behave for smaller matrices, since many ForwardDiff users work with fairly small ones, so I ran a few benchmarks (macOS aarch64, Julia 1.12/1.13, 1 BLAS thread, Chairmarks). The large-size speedups reproduce nicely, e.g. Dual * Dual with N=4, n=256 takes 6.8 ms instead of 55 ms on master. For small sizes, though, I see some slowdowns, and the in-place mul! now allocates, which is a bit unfortunate given that #854 is about the in-place case:
| N | n | D*R |
R*D |
D*D |
transpose(D)*D |
D*r (vec) |
R*d (vec) |
|---|---|---|---|---|---|---|---|
| 1 | 2 | 4.8 | 7.1 (6) | 12.6 (8) | 20.3 (10) | 4.3 | 2.6 |
| 1 | 8 | 0.34 | 0.78 | 1.24 | 1.91 | 1.74 | 1.92 |
| 1 | 64 | 0.18 | 0.15 | 0.29 | 0.16 | 1.10 | 0.75 |
| 4 | 4 | 1.8 | 5.1 | 7.2 | 7.1 | 2.1 | 3.5 |
| 4 | 16 | 0.51 | 0.95 | 1.01 | 1.14 | 1.07 | 0.90 |
| 8 | 8 | 0.90 | 2.9 | 3.1 | 3.0 | 1.33 | 1.58 |
| 8 | 16 | 0.64 | 1.30 | 1.23 | 1.39 | 1.08 | 0.95 |
| 8 | 128 | 0.39 | 0.49 | 0.40 | 0.46 | 1.06 | 0.65 |
(time with this PR / time on master for square n×n products; numbers in parentheses are the allocations of the in-place mul!, which are 0 on master)
Some thoughts:
Dual * realmaps to a single BLAS call without any copies, so it's the clearest win. The other cases need to copy/permute the operands and only start to pay off around n ≈ 16–32. Maybe we could start withDual * realonly, and add the others in a follow-up once we have a good idea of when they're beneficial? TheDual * realvector method seems to be slightly slower than the generic path at all sizes I tried (in line with the table in the PR description), so I think we could drop it.- I'm a bit worried about method ambiguities when overloading the 5-arg
mul!with wrapper unions. The Julia 1.10/GPUArrays special case is an example of that. Since Julia 1.13, LinearAlgebra provides the public 7-argmul!(C, tA, tB, A, B, α, β)for exactly this purpose. What do you think about using it instead, even if older Julia versions then keep the current behaviour? - It would be great if we could slim down the implementation a bit. Currently there are ~20 internal helpers and aliases (some of which already exist in LinearAlgebra, e.g.
AdjOrTrans), plus five quite similar method signatures. I added some concrete suggestions inline. - For the tests, it would be nice to stick to public behaviour (e.g. no checks of which method is dispatched to, and no
invokeof LinearAlgebra internals), to check error messages, and to add a few small-size cases as well as views and nestedDuals, which hit the fallback.
| # 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}} |
There was a problem hiding this comment.
LinearAlgebra already defines AdjOrTrans, and StridedMaybeAdjOrTransMat is very close to _BlasMatrix, so maybe we could reuse those? With the 7-arg mul! on Julia ≥ 1.13, the wrapper unions wouldn't be needed at all.
| 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} |
There was a problem hiding this comment.
It also excludes e.g. Rational or Irrational α/β. Would a simple runtime check be clearer?
|
|
||
| # 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" |
There was a problem hiding this comment.
This workaround is a good example of the ambiguity problems we can run into when overloading the 5-arg mul!. Other packages that overload mul! for their array types may cause similar issues. That's one reason I'd prefer the public 7-arg method.
| 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)) && |
There was a problem hiding this comment.
I think the generic path doesn't throw in this case, so this would be a behaviour change, and mightalias is quite conservative. Do we need this check? If the inner mul! calls handled the size checks, maybe _check_mul could be removed altogether.
|
|
||
| # `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 |
There was a problem hiding this comment.
As far as I know, closures without captured state (or with only isbits captures) broadcast fine over GPU arrays, so I think we could use closures here and drop the callable structs.
|
|
||
| function _blas_mul!(f!, C, A, B, α, β) | ||
| _check_mul(C, A, B) | ||
| if NANSAFE_MODE_ENABLED && !(_finite_values(A) && _finite_values(B)) |
There was a problem hiding this comment.
I think α and β should be checked here as well. In the generic path, scaling goes through _mul_partial, so with α = Inf zero partials stay zero, whereas BLAS gives NaN.
| 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} |
There was a problem hiding this comment.
In my benchmarks, this method is a bit slower than the generic path at all sizes (1.06–4.3×, for N = 1, 4, 8 and n = 2–128), which also matches your table. Maybe we can just drop it?
|
|
||
| function test_mul(C, A, B, α, β) | ||
| C0 = copy(C) | ||
| @test which(mul!, typeof.((C, A, B, α, β))).module === ForwardDiff |
There was a problem hiding this comment.
Could we test only the results here, rather than which method is dispatched to? The same applies to line 274 and the invoke at line 285.
| @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)) |
There was a problem hiding this comment.
Could we check the error messages as well?
|
|
||
| @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 |
There was a problem hiding this comment.
It would be nice to also test views and nested Duals here, to make sure the fallback still gives correct results.
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 <noreply@anthropic.com>
Dual matrices with BLASDuals by real matrices with BLAS
|
Thanks for the review and the benchmarks! I've taken your suggestions:
Two things I ran into with the 7-argument method:
The failure on Julia 1.14.0-beta2 is a segfault in LLVM in 🧔♂️🤖 Assisted by Claude Opus 5.5 |
Addresses #854 for the product of a matrix of
Duals and a real matrix, the case the issue names (mul!(C, A, B)withA isa Matrix{<:Dual}andB isa Matrix{Float64}).On Julia ≥ 1.13, this adds a method of the storage-level
mul!(C, tA, tB, A, B, α, β)for strided matricesCandAofDual{T,V,N}andBofV, withVaFloat32orFloat64. Viewed as numbers, anm×kmatrix ofDuals is an(N+1)m×kmatrix, soA * Bis a single BLASgemmonreinterpret(V, C)andreinterpret(V, A), without copies or allocations.Bmay be transposed or adjoint.Everything else takes the generic method as before:
A,SymmetricorHermitianB, and views without unit row stride;Dualscalarsα/β, nestedDuals and mixed precision;α,βor entries ofB, as BLAS does not zero the product of a zero partial and anInforNaN.GPU arrays keep the generic kernel, since cuBLAS and GPUArrays define this
mul!method for their arrays of any element type, and those methods are more specific. There are no method ambiguities with LinearAlgebra, SparseArrays, StaticArrays, GPUArrays, CUDA and JLArrays.Time of
mul!(C, A, B)with this PR over the time on master, forn×nmatrices ofFloat64withNpartials (Julia 1.13.4, 1 BLAS thread, Zen 5):nN = 1N = 4N = 8🧔♂️🤖 Assisted by Claude Opus 5.5