tf.browser.fromPixel(视频)导致内存泄漏

tf.browser.fromPixel(video) causes memory leak

我想使用tf.browser.fromPixels(video)从视频中获取当前帧数据,但是每次调用此函数时,都会发生内存泄漏。 TensorFlow.js版本

1.3.1 Browser version Chrome Version 75.0.3770.142 Here is the code that is causing the memory leak.

async function drawScreen () {

    console.log(tf.memory());

    var frame = tf.tidy( () => {

    return  tf.browser.fromPixels (videoElement, 3).expandDims(0).toFloat().div(tf.scalar(255))

    });

    console.log(tf.memory());

    hr_image_0 = tf.tidy( () => {

    return net.execute(frame).squeeze().clipByValue(0,1);

    });

    tf.dispose(frame);

    console.log(tf.memory());

    tf.browser.toPixels(hr_image_0, ccanvas);

    await tf.tidy( () =>  {

     tf.browser.toPixels(hr_image_0, ccanvas);

    });

    console.log(tf.memory());

}

我用过

requstAnimationFrame()

调用drawScreen函数。 运行Chrome上的代码,控制台打印如下

Object { unreliable: false, numBytesInGPU: 210113944, numTensors: 172,numDataBuffers: 172, numBytes: 211660580 }

CH6EX8.html:129:11 Object {unreliable: false, numBytesInGPU: 210344344, numTensors: 173,nnumDataBuffers: 173, numBytes: 211833380 }

CH6EX8.html:135:11 Object {unreliable: false, numBytesInGPU: 212187544, numTensors: 173, numDataBuffers: 173, numBytes: 213215780 }

CH6EX8.html:141:11 Object { unreliable: false, numBytesInGPU: 213745048, numTensors: 173, numDataBuffers: 173, numBytes: 213215780 }

有什么方法可以消除泄漏。

根据文档:

Executes the provided function fn and after it is executed, cleans up all intermediate tensors allocated by fn except those returned by fn

tf.tidy 确实删除了中间张量。但在这种情况下,没有任何中间张量要移除。随着您不断调用 drawscreen 方法,缓冲区将不断增加,该方法将始终 return tf.browser.fromPixels (videoElement, 3).expandDims(0).toFloat().div(tf.scalar(255)) 从而将缓冲区分配给内存中的张量创建。

要清除未使用的张量,调用 drawScreen 的方法应包含在 tf.tidy 中以处理从图像创建张量时使用的张量。

由于drawScreen被requestAnimation调用,tf.tidy可以是里面的顶层函数

async function drawScreen () {
  tf.tidy(() => {
   // do all operations here
  })
}

另一种选择是使用 tf.dispose 在图像绘制到屏幕后处理 framehr_image_0

await tf.browser.toPixels(hr_image_0, ccanvas);
tf.dispose(hr_image_0)