Repository navigation
Description
#880 computes products of a Dual matrix and a real matrix with BLAS on Julia ≥ 1.13. This tracks the products of #854 that still take the generic kernel. The first version of #880 (872aa27) covered most of them, and its benchmarks show the trade-offs.
Matrix products
real * Dual, alsoreal' * Dual: the values and partials ofBhave to be rearranged first, e.g. into ak×(N+1)nmatrix for a singlegemm, and the result assembled back intoC.Dual * Dual, alsoDual * Dual', as in the reproducer of LinearAlgebra.mul! with Matrix{Dual} does not dispatch to BLAS #854:A * value(B)is aDual * realproduct, andvalue(A) * partials(B)areal * Dualone.
Both allocate temporaries, which the generic kernel doesn't, and only pay off from n ≈ 16–32. For n×n matrices they were up to 7× (real * Dual) and 20× (Dual * Dual) slower at n = 2. At large sizes they were 2–24× faster, e.g. 5.0× and 7.9× for the example of #854 (500×300 by 300×400, N = 3). So they would need a size threshold. A copy-free real * Dual is possible with one gemm per column of B, but those are (N+1)×k by k×m products, which BLAS handles poorly.
Matrix–vector products
real * Dualvector: copy-free, as the values and partials ofy = A * x, as an(N+1)×mmatrix, are those ofxtimestranspose(A). Faster than the generic kernel from n ≈ 16–64, but up to 3.5× slower below.Dual * realvector: onegemvon the reinterpreted matrix. It was 1.06–4.3× slower in the review's benchmarks (aarch64, n ≤ 128), but 17× faster forN = 8with256×256Float32matrices on x86, so it is worth measuring again.
GPU arrays
cuBLAS and GPUArrays define the 7-argument mul! for their arrays of any element type, and Julia picks those methods for CuArrays of Duals, which keep the generic kernel. Using cuBLAS would need e.g. a cuBLAS extension. In the first version of #880 (RTX 5090, 2048×2048 matrices, N = 4), Dual * real took 1.3 instead of 6.9 ms, real * Dual 1.6 instead of 4.0 ms, and Dual * Dual 2.8 instead of 9.0 ms. Small products are bound by launch latency: 15–31 μs instead of 10–11 μs for 256×256 by 256×128.
Julia < 1.13, which has no 7-argument mul!, keeps the generic kernel for all products.
The main use for real * Dual and Dual * Dual is forward-over-reverse through dense layers (FluxML/Zygote.jl#1784), where the inputs are Duals and the weights are real: W * x, W' * Δ, and Δ * x' for the gradient of W. With the first version of #880, the gradient of a Flux MLP loss with a WGAN-GP penalty went from 2.0 to 1.45 ms on CPU.
🧔♂️🤖 Assisted by Claude Opus 5.5
Activity