If you use
retain_graph=True

you in every loop, it should not surprising that nothing gets freed up (just from the literal meaning of “retain” – not to say you should have seen known before but maybe it is a good thing to remember).
What happens is if you don’t have that is that the thing says “trying to backward twice blabla”, and that is true!
In the end, you need to detach hidden_in at the end of your loop before starting the next to “forget what has happened”.
Best regards
Thomas