If I properly understand you want to run that network until it fits a condition? But backpropagating only for those results which fits the condition?
I don’t know if there is an elegant way to do that.
Only possible fast way would be. This approach would by-pass the graph computation, thus, would be faster.
x_old ...
while(1):
     with torch.no_grad():
          x = f(x_old)
     if condition:
         x = f(x_old)
         break
     else:
         x_old=x

Another way would be cutting the computational graph. This would probably use more memory and would be slower as all the graph would stay over there (but wouldn’t affect backprop)
while(1):
     x = f(x)
     if condition:
         break
     else:
         x = x.detach()

There is a 3rd option that would be deleting the graph but I don’t really know if that’s possible.
Anyway, this pipeline looks a bit strange to me.