You can use Einstein summation.
import torch
batch_size, N, M, D, P = 4, 5, 6, 7, 8
A = torch.rand(batch_size, N, M, D)
B = torch.rand(batch_size, P, D)
print(torch.einsum('bnmd,bpd -> bnmp', [x, w]).size()) # batch_size, N, M, P