• Executes the provided function fn and after it is executed, cleans up all intermediate tensors allocated by fn except those returned by fn. fn must not return a Promise (async functions not allowed). The returned result can be a complex object.

    Using this method helps avoid memory leaks. In general, wrap calls to operations in tf.tidy for automatic memory cleanup.

    NOTE: Variables do not get cleaned up when inside a tidy(). If you want to dispose variables, please use tf.disposeVariables or call dispose() directly on variables.

    // y = 2 ^ 2 + 1
    const y = tf.tidy(() => {
    // a, b, and one will be cleaned up when the tidy ends.
    const one = tf.scalar(1);
    const a = tf.scalar(2);
    const b = a.square();

    console.log('numTensors (in tidy): ' + tf.memory().numTensors);

    // The value returned inside the tidy function will return
    // through the tidy, in this case to the variable y.
    return b.add(one);
    });

    console.log('numTensors (outside tidy): ' + tf.memory().numTensors);
    y.print();

    Type Parameters

    • T extends TensorContainer

    Parameters

    • nameOrFn: string | ScopeFn<T>

      The name of the closure, or the function to execute. If a name is provided, the 2nd argument should be the function. If debug mode is on, the timing and the memory usage of the function will be tracked and displayed on the console using the provided name.

    • Optionalfn: ScopeFn<T>

      The function to execute.

    Returns T