How to multiply a batch of lists of vectors by a list of matrices?

I have a batch of lists of vectors
[[v_11, v_12, …, v_1n], [v_21, v_22, …, v_2n], …]
and a list of matrices
[M_1, M_2, …, M_n]
and I want to compute the product
[[M_1 v_11, M_2 v_12, …, M_n v_1n], [M_1 v_21, M_2 v_22, …, M_n v_2n], …].

Is there a vectorized way to do this?

You could try using torch.stack to convert your list of vectors and list of matrices into 2 different Tensors. Then just apply @ or torch.einsum to perform the matrix multiplication.

import torch

list1 = [torch.randn(5) for _ in range(10)]
list2 = [torch.randn(5) for _ in range(10)]

matrix1 = [torch.randn(5,5) for _ in range(10)]

list1tensor = torch.stack(list1, dim=0)
list2tensor = torch.stack(list2, dim=0)
matrix1tensor = torch.stack(matrix1, dim=0)

mv1 = torch.einsum("bij,bj->bi",matrix1tensor, list1tensor)
mv2 = torch.einsum("bij,bj->bi",matrix1tensor, list2tensor)