Skip to content

Multiply matrices of Duals by real matrices with BLAS - #880

Open
CarloLucibello wants to merge 2 commits into
masterfrom
cl/blas-mul
Open

CarloLucibello wants to merge 2 commits into
masterfrom
cl/blas-mul

Conversation

@CarloLucibello

@CarloLucibello CarloLucibello commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Addresses #854 for the product of a matrix of Duals and a real matrix, the case the issue names (mul!(C, A, B) with A isa Matrix{<:Dual} and B isa Matrix{Float64}).

On Julia ≥ 1.13, this adds a method of the storage-level mul!(C, tA, tB, A, B, α, β) for strided matrices C and A of Dual{T,V,N} and B of V, with V a Float32 or Float64. Viewed as numbers, an m×k matrix of Duals is an (N+1)m×k matrix, so A * B is a single BLAS gemm on reinterpret(V, C) and reinterpret(V, A), without copies or allocations. B may be transposed or adjoint.

Everything else takes the generic method as before:

  • older Julia versions;
  • transposed A, Symmetric or Hermitian B, and views without unit row stride;
  • Dual scalars α/β, nested Duals and mixed precision;
  • mismatched sizes, so the errors are LinearAlgebra's;
  • 2×2 and 3×3 products, which LinearAlgebra also computes without BLAS;
  • in NaN-safe mode, non-finite α, β or entries of B, as BLAS does not zero the product of a zero partial and an Inf or NaN.

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, for n×n matrices of Float64 with N partials (Julia 1.13.4, 1 BLAS thread, Zen 5):

n N = 1 N = 4 N = 8
2 1.10 1.03 1.10
3 1.04 1.04 1.06
4 0.92 0.38 1.27
8 0.34 0.09 0.09
16 0.23 0.07 0.06
64 0.31 0.09 0.09
128 0.45 0.07 0.07

🧔‍♂️🤖 Assisted by Claude Opus 5.5

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

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.19%. Comparing base (730e156) to head (5e10c3e).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@devmotion devmotion left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 * real maps 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 with Dual * real only, and add the others in a follow-up once we have a good idea of when they're beneficial? The Dual * real vector 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-arg mul!(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 invoke of LinearAlgebra internals), to check error messages, and to add a few small-size cases as well as views and nested Duals, which hit the fallback.

Comment thread src/dual.jl Outdated
# 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}}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/dual.jl Outdated
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}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It also excludes e.g. Rational or Irrational α/β. Would a simple runtime check be clearer?

Comment thread src/dual.jl Outdated

# 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"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/dual.jl Outdated
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)) &&

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/dual.jl Outdated

# `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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/dual.jl Outdated

function _blas_mul!(f!, C, A, B, α, β)
_check_mul(C, A, B)
if NANSAFE_MODE_ENABLED && !(_finite_values(A) && _finite_values(B))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/dual.jl Outdated
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}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread test/MiscTest.jl Outdated

function test_mul(C, A, B, α, β)
C0 = copy(C)
@test which(mul!, typeof.((C, A, B, α, β))).module === ForwardDiff

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread test/MiscTest.jl Outdated
@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))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we check the error messages as well?

Comment thread test/MiscTest.jl Outdated

@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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@CarloLucibello CarloLucibello changed the title Compute products of Dual matrices with BLAS Multiply matrices of Duals by real matrices with BLAS Dec 1, 2026
@CarloLucibello

Copy link
Copy Markdown
Member Author

Thanks for the review and the benchmarks! I've taken your suggestions:

  • The PR now only covers Dual * real, as one method of the 7-argument mul! on Julia ≥ 1.13: a single BLAS call on the reinterpreted C and A, without allocations. The wrapper unions, the 1.10 workaround and the helpers are gone, older Julia versions keep the current behaviour, and the vector methods are dropped.
  • α and β are checked at runtime: only Dual scalars take the generic method, so e.g. Rational and Irrational ones use BLAS. In NaN-safe mode, the method also checks that α, β and B are finite.
  • _check_mul is gone: with mismatched sizes the method calls the generic one, so the errors and the sizes in their messages are LinearAlgebra's, and there is no aliasing check.
  • 2×2 and 3×3 products take the generic method too, as LinearAlgebra does for BLAS types. These are now within 10% (about 1 ns) of master, and the one slowdown left is 1.27× for N = 8, n = 4 (table in the description).
  • The tests check only results and error messages, and add small sizes, views with and without unit row stride, nested Duals, Symmetric, and Dual scalars.

Two things I ran into with the 7-argument method:

  • For matrices of BLAS types, it's the generic kernel: with 400×400 Matrix{Float64}s, mul!(C, 'N', 'N', A, B, true, false) is 10× slower than mul!(C, A, B). So the method calls the 5-argument mul! on the reinterpreted arrays.
  • cuBLAS and GPUArrays define it for their arrays of any element type, and Julia picks their methods for CuArrays and JLArrays of Duals. So GPU arrays keep the generic kernel, with unchanged results and no ambiguities.

real * Dual and Dual * Dual could come in a follow-up, with a size threshold. They're the products in forward-over-reverse through dense layers (FluxML/Zygote.jl#1784), where the inputs are Duals and the weights are real.

The failure on Julia 1.14.0-beta2 is a segfault in LLVM in HessianTest, which runs before MiscTest; master fails the same job with it (https://github.com/JuliaDiff/ForwardDiff.jl/actions/runs/43883934137).

🧔‍♂️🤖 Assisted by Claude Opus 5.5

This branch has not been deployed

No deployments
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.

2 participants