Does keras.backend.clear_session deletes sessions in a process or globally?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
When you train multiple models in a loop or run many experiments sequentially, memory usage can grow steadily. Keras provides keras.backend.clear_session() to reset the state and free resources. A common question is whether this function affects only the current process or clears sessions across all running processes. The short answer is that clear_session() is process-scoped. It resets the Keras/TensorFlow state within the process that calls it and has no effect on other processes. This article explains what the function does, when to use it, and how to combine it with other memory management techniques.
What clear_session() Actually Does
When you create a Keras model, TensorFlow allocates GPU memory, builds a computation graph (in TF1-style code), and registers various internal objects like layers, optimizers, and metrics. Over time, especially in a loop that builds and discards models, these objects accumulate.
keras.backend.clear_session() performs the following cleanup.
- Destroys the current TensorFlow graph and creates a new one.
- Resets the Keras global state, including layer name counters and the UID counter.
- Releases references to models, layers, and other Keras objects so that Python's garbage collector can reclaim their memory.
Without the clear_session() call, each iteration would leave behind graph nodes and layer references, causing memory usage to climb.
Process-Level Scope, Not Global
Each Python process maintains its own TensorFlow session and Keras backend state. When you call clear_session(), only the state in the calling process is affected.
This design makes sense because operating system processes have isolated memory spaces. There is no mechanism for a function call in one process to reach into another process's memory and release TensorFlow resources.
If you are using Python's multiprocessing module to run parallel training jobs, each worker process has its own independent Keras session. Calling clear_session() in one worker does not touch the others.
When to Use clear_session()
Hyperparameter Search Loops
When you iterate over many hyperparameter combinations, each iteration creates a new model. Without cleanup, the accumulated graph nodes and layer objects consume increasing amounts of memory.
Cross-Validation
Similar to hyperparameter search, k-fold cross-validation builds a fresh model for each fold.
Jupyter Notebooks
Notebooks are long-lived processes. If you redefine and retrain models many times in the same kernel, memory will grow. Calling clear_session() between experiments helps keep memory usage stable.
Combining with Other Memory Techniques
clear_session() alone may not free all memory, especially GPU memory that TensorFlow pre-allocates. Here are complementary techniques.
Python garbage collection. After deleting the model and clearing the session, explicitly invoke the garbage collector.
Limiting GPU memory growth. By default, TensorFlow allocates all available GPU memory. You can configure it to allocate incrementally instead.
This does not release memory after clear_session(), but it prevents TensorFlow from grabbing all GPU memory upfront, which reduces waste when running smaller models.
Common Pitfalls
Expecting GPU memory to be fully released. TensorFlow's GPU memory allocator does not always return memory to the OS after clear_session(). The memory may be reused by subsequent TensorFlow operations within the same process, but it will not appear as free in nvidia-smi. If you need to truly free GPU memory, you must terminate the process.
Calling clear_session() while a model is still in use. If you clear the session and then try to call model.predict() on a previously built model, you will get errors because the underlying graph has been destroyed. Always finish all work with a model before clearing.
Forgetting to delete the Python model object. clear_session() resets the Keras global state, but the Python variable still holds a reference to the model object. Use del model before calling clear_session() so the garbage collector can actually reclaim the memory.
Assuming thread safety. In a multi-threaded program where threads share the same process, calling clear_session() from one thread can destroy the graph that another thread is actively using. In multi-threaded setups, either give each thread its own tf.Graph and tf.Session, or coordinate access carefully.
Summary
keras.backend.clear_session() is a process-level function. It resets the Keras backend state, destroys the current TensorFlow graph, and releases internal references within the calling process. It has no effect on other processes. Use it between model-building iterations, such as in hyperparameter search, cross-validation, or notebook experiments, to prevent memory from growing unchecked. Pair it with del model and gc.collect() for more thorough cleanup, and be aware that GPU memory may not be fully returned to the OS until the process exits.
Related reading
- Does model.compile initialize all the weights and biases in Keras tensorflow backend?
- Does SHAP in Python support Keras or TensorFlow models while using DeepExplainer?
- Does TensorBoard TensorFlow have the features to add labels for axes and legends on plots? If so, how?
- Does TensorFlow 1.9 support Python 3.7
- Does make sense use dynamic learning rate in AdamOptimizer?
- Does scikit-learn perform real multivariate regression multiple dependent variables?
- Does python-requests support HTTP2 and asynchronous calls?
- Does Python have a package/module management system?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.