Repository navigation
Description
System information
- Have I written custom code (as opposed to using a stock example script provided in TensorFlow): there is a custom MWE code snippet included in the issue
- OS Platform and Distribution: Linux Elementary Loki (Ubuntu 16.04)
- TensorFlow installed from (source or binary): binary
- TensorFlow version: 2.0.0-alpha0
- Python version: 3.7.1
Describe the current behavior
Generating several models with no input shape specified results in normal memory occupancy:
import time
from tensorflow import keras
for _ in range(100):
model = keras.models.Sequential()
model.add(keras.layers.Dense(120, activation='relu'))
model.compile(loss='binary_crossentropy',
optimizer=keras.optimizers.SGD())
time.sleep(0.1)This is the behavior expected when the input shape is specified. However, when multiple models are generated within the same program life cycle, the specification of an input shape seems to produce a memory leak.
If the input shape is specified when the models are created, they pile up in memory, without being destroyed. Also the execution time seems to increase quite a lot.
import time
from tensorflow import keras
for _ in range(100):
model = keras.models.Sequential()
model.add(keras.layers.Dense(120, activation='relu', input_shape=(10, 10)))
model.compile(loss='binary_crossentropy',
optimizer=keras.optimizers.SGD())
time.sleep(0.1)Describe the expected behavior
Model generation should behave the same from a memory point of view regardless of whether the input shape is specified or not.
Code to reproduce the issue
It is enough to execute the code snippets included in the issue. In order to generate the memory occupancy, the memory_profiler package can be used. Assuming the code snippet is pasted in a file called test.py, run:
$ mprof run --include-children python test.py
$ mprof plot
Other info / logs
I generated a list of all the objects for the 2 code snippets, using Pympler.
from pympler import muppy
from pympler import summary
...
all_objects = muppy.get_objects()
occupancy = summary.summarize(all_objects)
summary.print_(occupancy)For the models generated without input shape, here is the result:
types | # objects | total size
======================================================================== | =========== | ============
<class 'str | 79278 | 14.02 MB
<class 'dict | 14468 | 6.93 MB
<class 'code | 25252 | 3.49 MB
<class 'type | 2582 | 2.57 MB
<class 'list | 8573 | 944.06 KB
<class 'tuple | 12079 | 796.21 KB
<class 'set | 732 | 466.12 KB
<class 'weakref | 4475 | 349.61 KB
<class 'abc.ABCMeta | 341 | 346.27 KB
<class 'tensorflow.core.framework.op_def_pb2.ArgDef | 3822 | 328.45 KB
<class 'google.protobuf.pyext.cpp_message.GeneratedProtocolMessageType | 369 | 320.16 KB
<class 'cell | 5921 | 277.55 KB
function (__init__) | 1694 | 224.98 KB
<class 'property | 2466 | 192.66 KB
<class 'wrapper_descriptor | 2353 | 183.83 KB
And here is the snapshot for the models generated with the input shape.
types | # objects | total size
================================================================ | =========== | ============
<class 'tuple | 296304 | 26.77 MB
<class 'dict | 71296 | 16.14 MB
<class 'str | 84828 | 14.54 MB
<class 'int | 395032 | 10.55 MB
<class 'list | 98027 | 9.89 MB
<class 'code | 25281 | 3.49 MB
<class 'type | 2587 | 2.58 MB
<class 'set | 2944 | 975.00 KB
<class 'tensorflow.python.framework.ops.Operation | 14100 | 771.09 KB
<class 'tensorflow.python.framework.ops.Operation._InputList | 14100 | 771.09 KB
<class 'tensorflow.python.framework.ops.Tensor | 14100 | 771.09 KB
<class 'tensorflow.python.pywrap_tensorflow_internal.TF_Output | 13200 | 721.88 KB
<class 'SwigPyObject | 14100 | 660.94 KB
<class 'collections.OrderedDict | 1262 | 622.22 KB
<class 'weakref | 6127 | 478.67 KB
Edit: typo in keras.models
Edit: typo in keras.layers


Activity
muddham commentedon May 21, 2019
@b3by I ran the code, but did not see any output, does this need any modifications in the code, if not please suggest me to reproduce the issue
b3by commentedon May 21, 2019
Unless you look at your system manager or htop, the way you can see the memory leak is by plotting the memory consumption using
memory_profiler. Did you execute the script by running the following?It should open up a matplotlib plot with the memory taken by the script.
karmel commentedon Jun 6, 2019
This is expected behavior, as the model has to be rebuilt if no input shape is available. You can use clear_session to clear the current Keras session.
b3by commentedon Jun 6, 2019
I just tried to include
tf.keras.backend.clear_session()into the test script (both before and after the sleep), but no luck with that, the memory leak is still there. Now if this was really an expected behaviour, that would mean the bug is actually in the
clear_sessionmethod. I understand your point, but I just can't wrap my mind around the idea that old model instances are not destroyed just because the new ones have to be rebuilt.robieta commentedon Jun 7, 2019
To follow up on what @karmel said:
When you make a Sequential model without input shape specified there isn't actually enough information at compile time to create the weights. (For instance in the dense layer above, there's no way to know that the kernel needs to be shape [10, 120] and it can't allocate a [???, 120] Variable.) So Sequential defers weight creation until it sees the first batch, at which point it can create variables. So the lack of memory growth is simply reflecting the fact that the example doesn't reach the point to which allocation is deferred.
On the other hand, when input shape is provided then Sequential actually can allocate weights before seeing the first batch. The reason that those weights aren't freed when the model goes out of scope is that unless otherwise specified, all tensors used by keras share the same global graph. It has the nice property of allowing mixing and matching of models (this is why you can compose models from other models, for instance), but it also means that this graph holds references to weights and therefore blocks their garbage collection even beyond the life of the python Model object.
tf.keras.backend.clear_sessiondestroys the underlying global graph, and therefore allows variables to be freed. The reason you're seeing different behavior is that there was a bug where clear_session didn't work in 2.0, and the fix (5956c7e) was added after the alpha cut. If you trytf-nightly-2.0-previewit should do the right thing.I've replicated your example (which was stellar, by the way. top notch repro.) and confirmed that clear_session works as intended in the latest nightly build: https://gist.github.com/robieta/474aa37a76ba242d9f5ea2e5284c9fab
We're also actively looking into the broader issue of making keras more gc friendly, so stay tuned.
tensorflow-bot commentedon Jun 7, 2019
Are you satisfied with the resolution of your issue?
Yes
No
b3by commentedon Jun 7, 2019
@robieta spot on. Brilliant explanation and excellent notebook, thank you very much. The shared global graph explains things, I was just unlucky to stump in a bug (fixed in nightly) that was concealed in a normal behaviour that I took for a bug. I already patched my code so that I spawn a new process every time I train a new fold, but I might try with the nightly version and see if my whole project breaks.
Memory leak when input shape is not specified
dorlivne commentedon Sep 25, 2019
will this fix work in beta1?