torch.max(-gX2, 0).sum() gives you the penalty you want to apply.
I assumed that you wanted to try and apply it with gradient descent, the same way you learn your original loss.
So you want the derivative of this new penalty (and yes this is a second derivative-like thing) wrt your weights.