You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 01:40:22