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);