Hi,
You can do this using a hook which will return the new value to use
     output = torch.reshape(output, [2,2])
     output.register_hook(lambda grad: grad * mask.float())
     loss = torch.nn.functional.mse_loss(target, output)