Broadcast Tensor to Have Certain Size

Hi!

I have a tensor variable x, that may come in sizes (,), (n,), (1, n) or (m,n).
Independently of the particular case, I would like to explicitly broadcast x to be two-dimensional.
In other words, is there a single call like y = x.broadcast_to_dim(2) that will do nothing if x has size (1,n) or (m,n), and will insert an axis on the left if x has size (n,) and two axes on the left if x has size (,), making x of size (1,n) in both cases?

Thanks a lot!

Does something like

if x.dim() == 1:
    x = x.epxand(1, n)

work?

Best regards

Tomas

Thanks!

I now did

if x.dim() <= 1:
    x = x.expand(1, *(x.size() or [1]))

which does the job, but unfortunately must be part of my forward method.
What kind of toll does this check have on performance?

Not much, as it is metadata only. But you might try expand(1, -1) instead of the complicated thing or treat dim() == 0 and 1 separately.