I think there might be a slight mistake in the example. Not important because directionally correct but I believe that instead of being:
loss.mean().backward()
you should write:
loss = loss / torch.sum(mask)
loss.backward()