albanD:

Assuming that you want to reduce dimension -1 of A and dimension -2 of B,


Hi,
I have tried your solution. But I met some errors. I use the code below.
a = torch.rand(2, 8, 3, 3)
b = torch.rand(2, 4, 3, 3)
ans = torch.matmul(a.unsqueeze(3), b.unsqueeze(2))

And I got the error:
ans = torch.matmul(a.unsqueeze(3), b.unsqueeze(2))
RuntimeError: The size of tensor a (8) must match the size of tensor b (4) at non-singleton dimension 1