Add batch dimension to this multiplication

Hi, I have two tensors with shapes (20,10) and (Batch, 10) and I want to multiply them to get out the shape (Batch, 20, 10). I can easily do it without the batch dimension like this (torch.rand(20, 10) * torch.rand(10)) but I can’t make it work with batch

Hi Damian!

Use unsqueeze() to line up the dimensions appropriately, and then let
pytorch’s broadcasting handle your batch dimension:

>>> import torch
>>> torch.__version__
'1.10.2'
>>> (torch.rand (20, 10) * torch.rand (6, 10).unsqueeze (1)).shape
torch.Size([6, 20, 10])

Best.

K. Frank