I’m not sure what the desired result is, but maybe this manual approach might help:
# Single sample
N = 1
mask = torch.randint(0, 2, (N, 10, 10)).float()
output = torch.empty(N, 10, 10).uniform_(0, 1)
target = torch.randint(0, 2, (N, 10, 10)).float()
criterion = nn.MSELoss()
loss = mask.numel()/mask.sum() * criterion(output, target)

# Batch of 10 samples
N = 10
mask = torch.randint(0, 2, (N, 10, 10)).float()
output = torch.empty(N, 10, 10).uniform_(0, 1)
target = torch.randint(0, 2, (N, 10, 10)).float()
criterion = nn.MSELoss(reduction='none')
loss = (mask.size(1)*mask.size(2))/mask.sum([1, 2]) * criterion(output, target).mean([1, 2])
loss = loss.mean()