How to perform explicit array broadcasting like np.broadcast_to/torch.expand in Julia?

As a fellow Python ML person, hello!

I think it’s difficult to suggest a completely general solution because broadcasting semantics differ so much between Numpy-like libraries and Julia. For this specific case, @mcabbott’s first solution above would probably be the most “natural” coming from Python. Tweaked just slightly to match your code snippet:

broadcast_a = as
# Julia doesn't have a built-in unsqueeze, but this is exactly unsqueeze(1) in PyTorch
broadcast_b = reshape(bs, size(bs, 1), 1, size(bs, 2))
c = sqrt.(sum((broadcast_a .- broadcast_b).^2, dims=1))
# optionally, to match the row -> column-first change. N.B. I snuck this in to avoid writing dropdims
c = reshape(c, size(bs, 2), size(as, 2))

At least for PyTorch, yes: https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html#torch.Tensor.expand

Edit: I just tried the versions with comprehensions but did not manage to make them work with Zygote. Assuming you want to run some kind of AD with this, the reshape + broadcasting or einsum versions are the way to go.