Well, it’s not the same at all.
So that would be
while(some condition):
      x = f(x)
     loss = function(x)
     loss.backward()
     ...
     x = x.detach()

Last part will convert x into a leaf variable and should work