1

尽管使用 tidy() 和 dispose() 来防止内存泄漏,但我的 tfjs-node 应用程序由于内存不足而崩溃。我设法在下面的代码中重现了这个问题:

import * as tf from '@tensorflow/tfjs-node'

let x = tf.variable(tf.scalar(1))

function model(){
  for(let i = 0; i < 100; i++){
    let b = tf.tidy(() => { return tf.mul(2, 3) })
    b.dispose()
    console.log(tf.memory().numTensors)
  }
  return x
}

//this call shows just 2 tensors throughout each of model()'s iterations
model()

const optimizer = tf.train.sgd(0.001);
optimizer.minimize(() => {
  //this call shows the number of tensors increasing each iteration up to about 200
  return model()
})

在 model() 函数中,我循环了 100 次,每次创建一个张量,然后立即对其调用 dispose()。model() 函数然后返回一个变量 x。

如果我正常调用我的 model() 函数,则在 100 次迭代中的每一次迭代中,活动张量的数量都保持在 2。这是我期望发生的。但是,当我在 optimizer.minimize() 中调用 model() 时,似乎 dispose() 调用被完全忽略了。张量的数量每次迭代都会增加。最后,大约有 200 个累积张量。

对于这个特定的示例代码,内存泄漏不是一个大问题,但对于我的实际应用程序,内存泄漏是巨大的,并导致应用程序几乎立即崩溃。关于如何解决这个问题的任何建议?

4

0 回答 0