Since the first example seems to work as intended, I would recommend to try to implement your second work flow using the same code logic. Currently, I’m not sure how the second code is called, as it seems to be wrapped in a Python class.
If your memory usage is increasing in each iteration using the second code snippet, you are probably storing some tensors or references to it. Note that the gc doesn’t immediately free the deleted objects, so you could experiment with gc.set_threshold for the different levels.
It should however not run out of memory.