I need to compute log(1 + exp(x)) and then use automatic differentiation on it. But for too large x, it outputs inf because of the exponentiation:
>>> x = torch.tensor([0., 1., 100.], requires_grad=True)
>>> x.exp().log1p()
tensor([0.6931, 1.3133, inf], grad_fn=<Log1PBackward>)
Since log(1 + exp(x)) ≈ x for large x, I thought I could replace the infs with x using torch.where. But when doing this, I still get nan for the gradient of too large values. Do you know why this happens and if there is another way to make it work?
>>> exp = x.exp()
>>> y = x.where(torch.isinf(exp), exp.log1p()) # Replace infs with x
>>> y # No infs
tensor([ 0.6931, 1.3133, 100.0000], grad_fn=<SWhereBackward>)
>>> y.sum().backward() # Automatic differentiation
>>> x.grad # Why is there a nan and how can I get rid of it?
tensor([0.5000, 0.7311, nan])