gpt4 book ai didi

memory-management - tensorflow : Memory leak even while closing Session?

转载 作者:行者123 更新时间:2023-12-04 07:50:51 25 4
gpt4 key购买 nike

当我意识到,即使我在 for 循环中关闭当前 session ,我的程序也会大大减慢,并且由于正在构建操作而导致内存泄漏,我只是在尝试一些四元数神经网络的东西。这是我的代码:

for step in xrange(0,200):#num_epochs * train_size // BATCH_SIZE):
338
339 with tf.Session() as sess:
340
341 offset = (BATCH_SIZE) % train_size
342 #print "Offset : %d" % offset
343
344 batch_data = []
345 batch_labels = []
346 batch_data.append(qtrain[0][offset:(offset + BATCH_SIZE)])
347 batch_labels.append(qtrain_labels[0][offset:(offset + BATCH_SIZE)]
352 retour = sess.run(test, feed_dict={x: batch_data})
357
358 test2 = feedForwardStep(retour, W_to_output,b_output)
367 #sess.close()

问题似乎来自 test2 = feedForward(..) .我需要在执行 retour 后声明这些操作一次,因为 retour不能是占位符(我需要遍历它)。没有这条线,程序运行得非常好,速度很快,而且没有内存泄漏。我不明白为什么 TensorFlow 似乎在尝试“保存” test2即使我关闭 session ...

最佳答案

TL;DR: 关闭 session 不会释放 tf.Graph Python 程序中的数据结构,并且如果循环的每次迭代都将节点添加到图形中,那么就会出现泄漏。

由于您的功能feedForwardStep创建新的 TensorFlow 操作,您可以在 for 中调用它循环,那么您的代码中就会出现泄漏——尽管是一个微妙的泄漏。

除非您另外指定(使用 with tf.Graph().as_default(): block ),否则所有 TensorFlow 操作都将添加到全局默认图中。这意味着每次调用 tf.constant() , tf.matmul() , tf.Variable()等将对象添加到全局数据结构中。有两种方法可以避免这种情况:

  • 构建您的程序,以便您构建一次图形,然后使用 tf.placeholder() 在每次迭代中输入不同值的操作。您在问题中提到这可能是不可能的。
  • 在每个 for 循环中显式创建一个新图。如果图形的结构取决于当前迭代中可用的数据,这可能是必要的。你可以这样做:
    for step in xrange(200):
    with tf.Graph().as_default(), tf.Session() as sess:
    # Remainder of loop body goes here.

    请注意,在此版本中,您不能使用 TensorOperation来自先前迭代的对象。 (例如,从您的代码片段中不清楚 test 的来源。)
  • 关于memory-management - tensorflow : Memory leak even while closing Session?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35695183/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com