I often use Hadamard products, which I currently implement using *
operator. However, my view
s are often incorrect, causing some sort of Cartesian-style product, eg if I want to Hadamard product two vectors of length 128, I end up with a matrix of size 128 x 128.
Of course, as soon as I notice this, I can fix it by putting on an appropriate view
, but I make this mistake all the time so I end up putting in print
statements before and after every Hadamard product to check I’m not doing this silly thing.
Is there some existing Hadamard/per-element multiplication function that does not allow broadcasting?
Edit: for now, I’ve just created a bespoke function
def Hadamard(one, two):
if one.size() != two.size():
raise Exception('size mismatch %s vs %s' % (str(list(one.size())), str(list(two.size()))))
res = one * two
assert res.numel() == one.numel()
return res