This shouldn’t work for batch sizes > 1.
However, this code should work:
a = torch.randn(2, 5, 3)
b = torch.randn(2, 5, 3)

res = a.unsqueeze(2) - b.unsqueeze(1)
# res[batch_idx, i] corresponds to (a[batch_idx, i] - b[batch_idx])

The extra dimension is added so that the tensors will automatically be broadcasted.
Basically this would be equal to (a.unsqueeze(1) - b.unsqueeze(0)).