Skip to content

Cpu memory leak when using tf.function with gpu model. #29027

Closed

Description

@jiarenyf

System information

  • Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Yes.
  • OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Ubuntu 18.04
  • Mobile device (e.g. iPhone 8, Pixel 2, Samsung Galaxy) if the issue happens on mobile device:
  • TensorFlow installed from (source or binary): binary
  • TensorFlow version (use command below): v1.12.1-2319-g81f2165 2.0.0-dev20190520
  • Python version: 3.7
  • Bazel version (if compiling from source):
  • GCC/Compiler version (if compiling from source):
  • CUDA/cuDNN version: 10.1/7.1
  • GPU model and memory:

Describe the current behavior
When using tf.function, the cpu memory usage increase forever.

Describe the expected behavior
No cpu memory leak when training models on gpu device using 'tf.function'.

Code to reproduce the issue
A part of my code, since the whole source code is huge...
And the dataset_train in the following code is a tf.data.DataSet object.

    DATA_TRAIN_SPEC = [
        tf.TensorSpec(shape=(None, IMAGE_FIX_HEIGHT, None, 3), dtype=tf.float32),
        tf.TensorSpec(shape=None, dtype=tf.int32),
        tf.TensorSpec(shape=None, dtype=tf.int32),
        tf.TensorSpec(shape=None, dtype=tf.int32),
    ]

    # @tf.function(input_signature=DATA_TRAIN_SPEC)
    def train_step(*batch_data):
        imgs, labels, imgs_width, labels_len = batch_data
        with tf.GradientTape() as tape:
            logits = model(imgs, training=True)
            logits_len = tf.cast(tf.math.ceil(
                tf.divide(imgs_width, block_size)), tf.int32)
            loss, accuracy = loss_fn(
                labels, logits, labels_len, logits_len, CLASSES)
        grads = tape.gradient(loss, model.trainable_variables)
        optimizer.apply_gradients(zip(grads, model.trainable_variables))

        return loss, accuracy

    def train_epoch(epoch):
        print(f'Epoch {epoch} training start ...')
        for step, batch_data in enumerate(dataset_train.take(num)):
            loss, accuracy = train_step(*batch_data)

            if (step+1) % ARGS.show_per_iterations == 0:
                loss, accuracy = get_numpy((loss, accuracy))

                loss_mean = np.mean(loss)
                accuracy_mean = np.mean(accuracy)*100

                prefix = f'Epoch#{epoch}/Step#{step+1}/training'
                print(f'Loss of {prefix} is: {"%.6f"%loss_mean} ...')
                print(f'Accuracy of {prefix} is: {"%.3f"%accuracy_mean}% ...')
        print(f'Epoch {epoch} training finish ...\n')

Activity

  1. changed the title [-]Cpu memory leak when using `tf.function`.[/-] [+]Cpu memory leak when using `tf.function` with gpu model.[/+] on May 25, 2019
  2. jiarenyf commented on May 25, 2019

    @jiarenyf
    Author

    @muddham @ry @jmhodges @eggie5 Can anyone help me, please, thank you~

  3. self-assigned this
    on May 27, 2019
  4. added
    comp:ops
    on May 27, 2019
  5. jvishnuvardhan commented on Jun 11, 2019

    @jvishnuvardhan
    Contributor

    @jiarenyf Can you check this issue which is similar to yours and try it with TF.2.0.0-beta0 and let us know how it works. Thanks!

  6. added
    stat:awaiting response
    on Jun 11, 2019
  7. guillaumekln commented on Jun 14, 2019

    @guillaumekln
    Contributor

    Possibly similar to #29075.

  8. removed
    stat:awaiting response
    on Jun 15, 2019
  9. jiarenyf commented on Jun 16, 2019

    @jiarenyf
    Author

    @jvishnuvardhan Thank you for the suggestion.
    However, the problem still occurs after pip install tensorflow-gpu==2.0.0-beta0.
    I also tried tf.keras.xxx.clear_session, and it took no effect for me.

    I have uploaded the code in the_codes, could you please help me to debug, thank you.
    You could run the code by:

    sh install.sh
    unzip new.zip
    unzip new_datas.zip
    cd new
    python train.py --config=./config/train/train001.json
    

    I have refactor the code, so it look different from the one I mentioned 20 days ago, while the problem is the same:
    When running without @tf.function the cpu_memory cost is as most 4.8GB and the gpu_util is 70%~100%, while running with @tf.function the cpu_memory keep increasing till over 10GB and the gpu_util is always 0%.
    Thank you.

  10. jiarenyf commented on Jun 19, 2019

    @jiarenyf
    Author

    Since no one answers this question, I will delete the codes uploaded in one drive and switch my codes to use pytorch instead. Bye bye.

  11. tensorflow-bot commented on Jun 19, 2019

    @tensorflow-bot

    Are you satisfied with the resolution of your issue?
    Yes
    No

  12. Ain-Crad commented on Aug 31, 2019

    @Ain-Crad

    Check if batch_data which in the train_step() function has changed its dimention(or some data in batch_data is accumulating) every epoch. Because if that @tf.function will create a new graph every epoch.

    (Have been troubled by this problem for a long time, and finally solved with help of a classmate)
    Have a good day.
    @jiarenyf

  13. zxk19981227 commented on Nov 21, 2019

    @zxk19981227

    Sir have you solved your problem? I also met a problem like this but some reshape is used in my programme but i have no idea how to fixed the leak of CPU memory.

  14. Ain-Crad commented on Nov 21, 2019

    @Ain-Crad

    Sir have you solved your problem? I also met a problem like this but some reshape is used in my programme but i have no idea how to fixed the leak of CPU memory.

    Hi,
    The follow @tf.function instruction in Tensorflow may provide some clues:

    Note that unlike other TensorFlow operations, we don't convert python numerical inputs to tensors. Moreover, a new graph is generated for each distinct python numerical value, for example calling g(2) and g(3) will generate two new graphs (while only one is generated if you call g(tf.constant(2)) and g(tf.constant(3))). Therefore, python numerical inputs should be restricted to arguments that will have few distinct values, such as hyperparameters like the number of layers in a neural network.

    More information about @tf.function.

    So, check if have obey this, otherwise it will generate new graph each batch, and that will significantly raise your CPU memory.

    Good luck.

  15. moulicm111 commented on Jun 8, 2020

    @moulicm111

    Thank you @Ain-Crad . tf-function decorator is main culprit for increase of ram .
    In my case
    total_loss = loss_1(inp,tar) + lambda*loss_2(inp,tar)
    does lambda here cause a problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

comp:opstype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions