I modified the algorithm to a more simple form that removed for cycle and if, and it works properly:
diff2 = (torch.flatten(input) - torch.flatten(target)) ** 2.0 * torch.flatten(mask)
result = torch.sum(diff2) / torch.sum(mask)
return result

Thanks!