Memory leak when using tf.browser.toPixels()

Viewed 752

The following line is causing a memory leak .

await tf.browser.toPixels(val, temp);

val is an array of dimensions img_size * img_size and temp is a canvas . One tensor is not being disposed . Since it is an asynchronous call it cannot be put inside a tf.tidy() . Also according to official documentation tf.browser.toPixels() should return a promise .So how can we dispose the tensor which is being formed ? (Size of tensor = img_size * img_size *4 )

Relevant Code :

let val ;     //val is an array not a tensor
        tf.tidy(()=>{
        let values = model.predict(batched).dataSync(); //batched is a tensor
        values = Array.from(values);
        //scale values
        values = values.map(x => x * 255)
        val = new Array();
        while (values.length > 0) val.push(values.splice(0, image_size));
        });
        await tf.browser.toPixels(val, temp); //this line causes leak,commenting it fixes it
        finalRes.getContext('2d').drawImage(temp, dx, dy);

2 Answers

This was an internal bug in tfjs . It has been fixed now here

the tensor needs to be disposed explicitly after using tf.browser.toPixels

tf.dispose(val)

More details can be found here

Related