How can I compute this function in a way that handles gradients correctly?
def f(x):
    return torch.where(x > 0, x, x / (1 - x))

This issue 1 causes an incorrect nan gradient at x == 1:
x = torch.tensor(1., requires_grad=True)
y = f(x)
print(y)
y.backward()
print(x.grad)

I tried using masked_scatter 1 but it also doesn’t work:
def f(x):
    return x.masked_scatter(x < 0, x / (1 - x))