Dear Julia developers,
I was thinking of writing some code, or maybe even a package, that can compute generic tensor contractions, traces etc.
A contraction of two tensors would be any operation where you start with arrays A and B with NA and NB dimensions, and
some indices of A will be contracted with equally sized indices in B (like the inner index in matrix multiplication) and others will
be present in the output.
I am still thinking of the best syntax, but something like
C["i,j,k"]=A["k,m,n,i"]B["n,j,m"]
seems to be very popular in similar C++ style libraries.
A naive approach is to use permutedims to reshuffle the dimensions of A and B such that the open indices can be grouped together and the contraction indices can be grouped together, then reshape to matrices, use matrix multiplication, reshape to get the original dimension back, and do a final permutedims to get the dimensions as requested in the output tensor. This requires in general three permutedims and thus three internal objects that require memory allocation and deallocation, so I would like to avoid that by writing a better approach that does not require temporise and is cache friendly, as inspired by the fallback method general_matmatmul in Base.LinAlg. I would of course also like to reuse as much of the code in Base as possible, and not have to rewrite almost identical code.
In that respect, I was wondering, however, why generic_matmatmul, which is a fallback for Base.LinAlg.BLAS.gemm!, was chosen not to exactly mimic gemm! so as to allow also to add the result of A*B to C (with some coefficients) rather than just overwriting C. It would be a near-zero cost operation to modify this function. If it is then also called gemm! instead of generic_matmatmul, it would be completely transparant.
Similarly, it would be nice to have a permutedims! which adds rather then overwrites (like a combination of permutedims! and axpy!).
I can of course modify this myself, but want to check first the original motivation behind the current approach.
Best regards,
Jutho