diff --git a/src/artificial_artwork/nst_tf_algorithm.py b/src/artificial_artwork/nst_tf_algorithm.py index 2c3b776..6896a62 100644 --- a/src/artificial_artwork/nst_tf_algorithm.py +++ b/src/artificial_artwork/nst_tf_algorithm.py @@ -244,6 +244,10 @@ def perform_nst(self, style_network): print(" --- Finished Learning Algorithm :) ---") + # prevent out-of-memory errors or other unexpected errors (due to the + # unpredictable timing of garbage collection) in some cases + self.session_runner.close() # trigger garbage collection / memory release + def iterate(self, image_model: t.Dict[str, Layer]): # Run the session on the train_step to minimize the total cost # This is our typical iterative learning loop / iteration, where the diff --git a/src/artificial_artwork/tf_session_runner.py b/src/artificial_artwork/tf_session_runner.py index 95d0ca0..47f8b93 100644 --- a/src/artificial_artwork/tf_session_runner.py +++ b/src/artificial_artwork/tf_session_runner.py @@ -46,6 +46,21 @@ def run(self, *args, **kwargs): @property def session(self): return self._proxy_subject.interactive_session + + def close(self): + """Close the session and trigger garbage collection to free up resources. + + Closes the Tensorflow Interactive Session, which triggers garbage + collection to free up resources from memory. + + Calling this method can prevent Tensorflow Error: "An interactive + session is already active. This can cause out-of-memory errors or some + other unexpected errors (due to the unpredictable timing of garbage + collection) in some cases. You must explicitly call + `InteractiveSession.close()` to release resources held by the other + session(s). Please use `tf.Session()` if you intend to productionize. + """ + self._proxy_subject.interactive_session.close() @classmethod def with_default_graph_reset(cls):