Multiple Matrix Multiplication (chained)

Hey !

I would like to know if there is a way to multiply multiple matrices as a chain.
Let’s say I have matrices M1, M2, … M23, and I want to do: M1 @ M2 @ M3 @ ... @ M23.
I see only a for loop or a recursive function for that … that wouldn’t be very effective I guess.

Any suggestions ?
Thanks !

Someone Please Answer this

The proposed approach seems to work:

m1 = torch.randn(1, 2)
m2 = torch.randn(2, 3)
m3 = torch.randn(3, 4)
m4 = torch.randn(4, 5)

res = m1 @ m2 @ m3 @ m4

Are you seeing any errors using it?

Whats the difference between chain_matmul and @. What is better to use?

Thanks

I would recommend to use torch.chain_matmul as it should be more efficient.
From the docs:

This product is efficiently computed using the matrix chain order algorithm which selects the order in which incurs the lowest cost in terms of arithmetic operations.

Thanks a lot for your help