Tensorflow.js: cannot return a promise inside of tidy

Viewed 1178

Load below html file, wait for the first <textarea> to fill up, then click on Check Memory button. tf.tidy(main) function is supposed to clean all tensors instead its throwing an error in the console. The error is because of async\await. In my actual code i cannot remove async\await. Below is sample code to reproduce the issue.

Please help. Thanks!

<html>

<head>
  <title>Split data as Training/Test</title>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
</head>

<body onload="tf.tidy(main)">
  <p>Total memory consumed:</p>
  <textarea rows="10" cols="50" id="memory-before"></textarea>
  <br><br>
  <button onclick="showMemory()">Check Memory</button>
  <br><br>
  <textarea rows="10" cols="50" id="memory-after"></textarea>
  <script>
    /**
     * Reading Data form CSV and splitting it into Training and Testing dataset.
     * Program to split dataset in a csv file using TensorFlow tf.split
     */
    async function main() {
      // Import data from a CSV file.
      const houseSalesDataset = tf.data.csv("http://127.0.0.1:8080/dataset/kc_house_data.csv");

      // Extract x and y values to plot.
      let pointsDataset = houseSalesDataset.map(record => ({
        x: record.sqft_living,
        y: record.price
      }));

      let pointsArray = await pointsDataset.toArray();

      // Extract Features (inputs) and store it in a tensor.
      let featureValues = pointsArray.map(point => point.x);
      let featureTensor = tf.tensor2d(featureValues, [featureValues.length, 1]);

      // Extract Labels (output) and store it in a tensor.
      let labelValues = pointsArray.map(points => points.y);
      let labelTensor = tf.tensor2d(labelValues, [labelValues.length, 1]);

      document.getElementById('memory-before').innerHTML = JSON.stringify(tf.memory(), null, '\t');
    }

    function showMemory() {
      document.getElementById('memory-after').innerHTML = JSON.stringify(tf.memory(), null, '\t');
    }
  </script>
</body>

</html>

Output:

enter image description here

Update:

Moved the tidy function invocation from onload to inside <script> tag as shown below but tidy is still not cleaning the memory.

tf.tidy(() => { main() });
1 Answers

i think the solution would be

const handelOnloadevent = async()=>{

tf.tidy(await main());
}



<body onload="handelOnloadevent"></body>

if tf.tidy doesn't accept the promise then just resolve the promise before passing it to tf.tidy

Related