# MSELoss when mask is used

I’m trying to calculate MSELoss when mask is used. Suppose that I have tensor with batch_size of 2: [2, 33, 1] as my target, and another input target with the same shape. Since sequence length might differ for each example, I have also a binary mask indicating the existence of each element in the input sequence. So here is what I’m doing:

mse_loss = nn.MSELoss(reduction='none')

loss = mse_loss(input, target)

mse_loss_val = loss / loss.numel()

# now doing backpropagation
mse_loss_val.backward()


Is loss / loss.numel() a good practice? I’m skeptical, as I have to use reduction='none' and when calculating final loss value, I think I should calculate the loss only considering those loss elements that are nonzero (i.e., unmasked), however, I’m taking the average over all tensor elements with torch.numel(). I’m actually trying to take 1/n factor of MSELoss into account. Any thoughts?

Maybe a bit late, but I don’t think you want numel if you want the mean with respect to non-padded elements. Why not try mask.sum() instead of loss.numel()?

I genuinely believe you’re using mask in a wrong way. In the snippet you sent, you were multiplying the mask with the loss, that will impose a float multiplication. The most efficient way of using mask is obtained by fancy indexing. Also take a look at torch.gather function.