I am trying to use variable-length input by masking and padding with NaNs in order to quickly see masking errors if they happen.
But the backpropagation propagates the NaNs backward even if they are masked out
Example:

vec = torch.cuda.DoubleTensor([1,2,float(‘nan’)])
mask = torch.cuda.ByteTensor([1,1,0])
vec_var= Variable(vec)
scalar_var = Variable(torch.cuda.DoubleTensor([4]), requires_grad=True)
res_var = (scalar_var*vec_var)[mask].sum()
print(res_var)
res_var.backward()
print(scalar_var.grad)

Gives

Variable containing:
12
[torch.cuda.DoubleTensor of size 1 (GPU 0)]
Variable containing:
nan
[torch.cuda.DoubleTensor of size 1 (GPU 0)]

Why is that? In my view the NaNs at the end are not part of any calculation, they should not influence backpropagation at all.
Is it a bug or expected behavior?