TensorFlow 2.11.0循环调用tf.Model.fit()内存泄漏,clear_session()无效
TensorFlow 2.11.0循环创建模型并调用fit()时的内存泄漏问题
在TensorFlow 2.11.0版本中,循环创建tf.Model实例并调用tf.Model.fit()时,内存占用会持续上升,最终触发OutOfMemory异常导致内存耗尽,即使调用tf.keras.backend.clear_session()也无法解决该问题。而在TensorFlow 2.9.2版本中运行相同代码,内存占用基本保持稳定,符合预期。
复现代码
import tensorflow as tf import time class MyModel(tf.keras.Model): def __init__(self): super().__init__() self.dense1 = tf.keras.layers.Dense(1000, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(10000, activation=tf.nn.softmax) self.dense3 = tf.keras.layers.Dense(10000, activation=tf.nn.softmax) self.dense4 = tf.keras.layers.Dense(1000, activation=tf.nn.softmax) def call(self, inputs): x = self.dense1(inputs) x = self.dense2(x) x = self.dense3(x) x = self.dense4(x) return x for r in range(0, 10000): model = MyModel() ds = tf.data.Dataset.from_tensor_slices((tf.random.uniform((64*4, 1000)), tf.ones((64*4)))) model.compile(optimizer='sgd', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)) model.fit(ds.batch(64)) tf.keras.backend.clear_session() time.sleep(3) print("round: ", r)
系统信息
- 操作系统平台与发行版:Ubuntu 22.04.1 LTS (GNU/Linux 5.16.10 x86_64)
- TensorFlow安装来源:源码
- TensorFlow版本:2.11.0
- Python版本:3.10.6
内容的提问来源于stack exchange,提问作者Alessio Mora
相关产品推荐
相关产品推荐

