Skip to content

tf.function with input_signature slower on unseen sequence length #29075

Closed

Description

@guillaumekln

System information

  • Have I written custom code: Yes
  • OS Platform and Distribution: Linux Ubuntu 16.04:
  • TensorFlow installed from: binary
  • TensorFlow version: 2.0.0-dev20190526
  • Python version: 3.6.6
  • CUDA/cuDNN version: 10.0
  • GPU model and memory: GTX 1060

Describe the current behavior

When running a tf.function on 3D inputs (a batch of sequence), I found that the execution is slower on unseen sequence length even if a compatible input_signature is set. On a large graph, this results in a low GPU usage and a growing CPU memory usage for several iterations until most sequence lengths are seen. It is as if new graphs were compiled internally even though the function does not seem to be retraced.

This effect does not affect eager mode or V1 graph mode where the execution directly runs at its target speed and memory usage.

Describe the expected behavior

tf.function with an input signature should behave like graph mode with constant memory usage and no "warmup" phase.

Code to reproduce the issue

While this issue is very visible on large graphs, I tried to compile a small example to consistently show the effect:

import time
import itertools
import random

import tensorflow as tf

def generate_token_based_shapes(num_tokens=4096):
    while True:
        length = random.randint(1, 100)
        batch_size = int(num_tokens / length)
        yield (batch_size, length)

# Generate 500k tensors of shape [None, None, 512] but with similar total size.
shapes = list(itertools.islice(generate_token_based_shapes(), 500000))
dataset = tf.data.Dataset.from_tensor_slices(shapes)
dataset = dataset.shuffle(len(shapes))
dataset = dataset.map(lambda shape: tf.zeros(tf.concat([shape, [512]], axis=0)))
dataset = dataset.repeat()
dataset = dataset.prefetch(1)

# Define a model with some layers.
model = tf.keras.Sequential([
    tf.keras.layers.Dense(1024),
    tf.keras.layers.Dense(1024),
    tf.keras.layers.Dense(1024),
    tf.keras.layers.Dense(1024),
    tf.keras.layers.Dense(1024)])

@tf.function(input_signature=(tf.TensorSpec([None, None, 512], dtype=tf.float32),))
def run_step(inputs):
    return model(inputs)

seen_lengths = set()
for x in dataset:
    length = x.shape[1]
    start = time.time()
    _ = run_step(x)
    end = time.time()
    print(length in seen_lengths, end - start)
    seen_lengths.add(length)

Other info / logs

The above code produced the following logs when run on CPU:

False 0.43003296852111816
False 0.11496973037719727
False 0.11308979988098145
False 0.11620664596557617
False 0.11439895629882812
False 0.11322546005249023
True 0.095062255859375
False 0.11357808113098145
False 0.11438512802124023
False 0.11338496208190918
False 0.1123197078704834
False 0.11295366287231445
False 0.11250948905944824
False 0.11576318740844727
False 0.1139533519744873
False 0.11278915405273438
False 0.11090493202209473
True 0.09256935119628906
False 0.11287093162536621
False 0.11374545097351074
False 0.11446619033813477
False 0.11277508735656738
False 0.11354255676269531
False 0.11325383186340332
False 0.1137855052947998
False 0.11451315879821777
False 0.11423110961914062
True 0.09340834617614746
False 0.1146705150604248
False 0.11285781860351562
False 0.11371898651123047
True 0.09309053421020508
True 0.09239482879638672
True 0.09140896797180176
False 0.11467862129211426
False 0.11377716064453125
False 0.11178278923034668
False 0.11260485649108887
True 0.09450674057006836
True 0.09363818168640137
True 0.09272456169128418
False 0.11517977714538574
False 0.11325454711914062
True 0.09257698059082031
False 0.11360836029052734
True 0.09241485595703125
False 0.11343145370483398
True 0.09368515014648438
False 0.11366653442382812
True 0.09125065803527832
False 0.1126089096069336
False 0.11182904243469238
True 0.09548735618591309
True 0.09283709526062012

When the length is unseen, it takes about 0.113s but 0.092s after that.

On this example the effect is small but I'm trying to train a Transformer model with tf.function and it takes very long for the training to reach full speed. The CPU memory usage also keeps growing during this "warmup" phase. The same model works well when integrated with tf.estimator as I'm trying to move from Estimator to V2 custom loops.

Activity

  1. self-assigned this
    on May 29, 2019
  2. added
    comp:runtime
    on May 30, 2019
  3. muddham commented on May 30, 2019

    @muddham

    @guillaumekln Able to reproduce the issue, but the numbers in the output are different from the numbers you mentioned.

  4. guillaumekln commented on Jun 7, 2019

    @guillaumekln
    ContributorAuthor

    Any update? This is still valid as of 2.0.0.dev20190606.

  5. added
    stat:awaiting tensorflower
    on Jun 10, 2019
  6. alextp commented on Jun 10, 2019

    @alextp
    Contributor

    @allenlavoie do we retrace even when a signature is passed?

  7. allenlavoie commented on Jun 10, 2019

    @allenlavoie
    Member

    We retrace in some cases (e.g. distribution strategy changed), but not for newly shaped Tensors. Easy enough to add a Python nonlocal counter or a logging statement to the function body to check how many times it gets traced; that may be a good start to debugging.

  8. guillaumekln commented on Jun 10, 2019

    @guillaumekln
    ContributorAuthor

    The tf.function itself is not retraced. For reference, it worked properly in the alpha release (to compare with the logs above):

    False 0.49825453758239746
    False 0.09595465660095215
    False 0.09451770782470703
    False 0.0943748950958252
    False 0.09402847290039062
    False 0.09326910972595215
    True 0.09315991401672363
    False 0.09505486488342285
    False 0.09238004684448242
    False 0.09103155136108398
    False 0.09470963478088379
    False 0.09449291229248047
    True 0.09190535545349121
    False 0.09163832664489746
    True 0.09249663352966309
    False 0.09634065628051758
    False 0.09385347366333008
    False 0.09270620346069336
    False 0.09623479843139648
    False 0.09488368034362793
    True 0.093353271484375
    False 0.09451007843017578
    False 0.09360551834106445
    False 0.09260439872741699
    False 0.09208202362060547
    False 0.09282684326171875
    True 0.09669733047485352
    False 0.09361767768859863
    False 0.09194278717041016
    False 0.09254956245422363
    False 0.09276223182678223
    False 0.09399724006652832
    True 0.09332799911499023
    False 0.09316015243530273
    True 0.09275269508361816
    False 0.09307003021240234
    True 0.0928955078125
    True 0.09315705299377441
    True 0.0956425666809082
    False 0.09328627586364746
    True 0.09452319145202637
    True 0.09224057197570801
    True 0.09405398368835449
    False 0.09274768829345703
    False 0.09326839447021484
    
  9. removed
    stat:awaiting tensorflower
    on Jun 11, 2019
  10. guillaumekln commented on Jun 12, 2019

    @guillaumekln
    ContributorAuthor

    So after bisecting the nightly builds, I found that this behavior was introduced in 2.0.0.dev20190329. Then I ran git bisect on commits from 2019-03-27 to 2019-03-29 and found that this was likely introduced by 1e5407a. The commit content appears relevant to this issue.

    cc @er91.

  11. 31 remaining items

  12. guillaumekln commented on Nov 1, 2019

    @guillaumekln
    ContributorAuthor

    How do you know that you have iterated through the dataset entirely, in order to compute several metrics at the end of an epoch ? Writing try: iter.next() except tf.errors.OutOfRangeError: return None inside _train_step does not seem to work.

    @georgesterpu Would it work for you to catch the exception outside the tf.function?

    If this help, I'm using this construct to iterate on datasets. The decorated function is turned into a callable that returns a generator over its outputs. The exception is used as the end condition.

  13. mdanatg commented on Nov 2, 2019

    @mdanatg

    +1 @guillaumekln , catching the exception outside the tf.function should work as well. That would simplify your code quite a bit, and works so long as you don't need to wrap the outer loop in a function.

    As for avoiding assumptions on the structure, or to write it by hand, we can craft a version of map_structure that can work with None shapes:

      def empty_or_zeros(shape, dtype):
        empty_shape = [0 if s is None else s for s in shape]
        return tf.zeros(empty_shape, dtype=dtype)
      return tf.nest.map_structure(empty_or_zeros, it.output_shapes, it.output_types)
    
  14. georgesterpu commented on Nov 3, 2019

    @georgesterpu
    Contributor

    Thank you for your advice, @guillaumekln and @mdanatg

    The code snippet of @mdanatg works well for the train step, and it returns several warnings:

    OwnedIterator.output_shapes (from tensorflow.python.data.ops.iterator_ops) is deprecated and will be removed in a future version.
    Instructions for updating:
    Use `tf.compat.v1.data.get_output_shapes(iterator)`.
    
    OwnedIterator.output_types (from tensorflow.python.data.ops.iterator_ops) is deprecated and will be removed in a future version.
    Instructions for updating:
    Use `tf.compat.v1.data.get_output_types(iterator)`.
    

    However, my other issue was with the evaluation loop, as explained in #29075 (comment)
    My step functions do not return a structure identical to the one of the iterator. Instead, they return either a scalar loss (train step) or a tfa.seq2seq.FinalBeamSearchDecoderOutput struct (eval step). On the optional.has_value() False branch I won't have a reference to an instance of that structure.

    I've also tried a slightly simplified version of @guillaumekln's construct. The step function takes as input a function that returns iterator.__next__(), and is called inside a try...except block of the infinite while loop. Within an epoch this seems to run as fast as the Optional code, however it seems to have an overhead at the start of each epoch that makes it significantly slower. I could see the warning below at the start of each epoch (I think it is related to an Embedding layer), suggesting that the graph was rebuilt every time:

    /tensorflow_core/python/framework/indexed_slices.py:434: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory.
      "Converting sparse IndexedSlices to a dense Tensor of unknown shape. "
    

    And it also logs this warning:

    2019-11-03 19:29:10.605954: W tensorflow/core/common_runtime/base_collective_executor.cc:217] BaseCollectiveExecutor::StartAbort Out of range: End of sequence
    	 [[{{node IteratorGetNext}}]]
    	 [[IteratorGetNext/_20]]
    2019-11-03 19:29:10.605963: W tensorflow/core/common_runtime/base_collective_executor.cc:217] BaseCollectiveExecutor::StartAbort Out of range: End of sequence
    	 [[{{node IteratorGetNext}}]]
    
  15. mdanatg commented on Nov 4, 2019

    @mdanatg

    If you have a colab where all these can be reproduced, it would be helpful to make sure I don't misunderstand anything.

    FinalBeamSearchDecoderOutput is a namedtuple, so nest.map_structure should be able to deal with it properly, but I may be missing something.

    About the second solution, if _run_step takes a function it might retrace excessively - what if you just directly pass the iterator? If you call next(it) inside the @tf.function, the OutOfRangeError should bubble all the way into the eager runtime.

  16. szc11121 commented on Apr 2, 2020

    @szc11121

    I confirm this is fixed in 2.0.0.dev20190829. When running the code to reproduce, there is no longer a noticeable time difference between seen and unseen sequence lengths:

    False 0.378192663192749
    False 0.11128377914428711
    False 0.11080718040466309
    False 0.10891008377075195
    False 0.10831356048583984
    False 0.10732555389404297
    False 0.10800600051879883
    False 0.10589814186096191
    False 0.1084296703338623
    False 0.10618948936462402
    False 0.10782027244567871
    False 0.10433292388916016
    False 0.10707211494445801
    False 0.1098027229309082
    True 0.10712003707885742
    False 0.10629463195800781
    True 0.10657715797424316
    False 0.1062629222869873
    False 0.10881710052490234
    False 0.10586357116699219
    True 0.10734868049621582
    False 0.1084589958190918
    False 0.1089639663696289
    False 0.10571050643920898
    True 0.10631895065307617
    False 0.10663580894470215
    False 0.10557937622070312
    True 0.10591363906860352
    True 0.10362792015075684
    False 0.10501718521118164
    False 0.107269287109375
    False 0.10628437995910645
    False 0.1069636344909668
    False 0.10788226127624512
    True 0.10770535469055176
    

    I propose to cherry-pick this into r2.0, see #32080.
    same issue here. but it seems there is still a more important question remain to be done: even there is no difference between unseen sequence length, but tf.function is still much slower than eager mode when I run the example code.
    In my situation, I also have different sequence length between batchs, after I use tf.funtion with input_signature, it runs 4-5x slower than eager mode and 10x slower than tf1, I tried 2.0, 2.1, 2.2 but problem still unsolved. that's really upset :(

  17. mdanatg commented on Apr 2, 2020

    @mdanatg

    @szc11121 is it also an issue in tf-nightly? If so, please include a snippet of code to reproduce the slowness and reopen this thread.

  18. szc11121 commented on Apr 4, 2020

    @szc11121

    @szc11121 is it also an issue in tf-nightly? If so, please include a snippet of code to reproduce the slowness and reopen this thread.

    sorry to reply late, but I finally can reproduce the problem now. I create a colab notebook here to reproduce the problem, in output you can see training step in graph mode is 10x slower than eager mode. It seems it is a problem about tf.keras.layers.Embedding(), not variable sequence length, so I annotate some code.

    update: it looks fine if we use tf.nn.embedding_lookup instead of tf.keras.layers.Embbeding

  19. mdanatg commented on Apr 6, 2020

    @mdanatg

    @szc11121 indeed, looks like a performance issue with embedding layers. I modified your code a little and filed #38287 to track the issue separately.

  20. dathudeptrai commented on Apr 24, 2020

    @dathudeptrai

    somehow this bug still happened on the TF 2.1 and TF-nightly. I need warm-up model with the input length from 1-300 to make sure maximize performance on practice. @alextp

  21. mdanatg commented on Apr 24, 2020

    @mdanatg

    @dathudeptrai does the model warm up faster if you use tf.function(experimental_relax_shapes=True)?

  22. dathudeptrai commented on Apr 24, 2020

    @dathudeptrai

    @mdanatg i use saved graph, do i need tf.function?

  23. mdanatg commented on Apr 24, 2020

    @mdanatg

    I think saved graphs don't require tf.function (because it was already applied before saving them). @k-w-w thoughts?

  24. dathudeptrai commented on Apr 24, 2020

    @dathudeptrai

    I think this bug is extremely affecting user decisions in NLP deployment. Everything is fine for me when I am aware of this and use a warm-up variable length trick to avoid this slow bug.

  25. mdanatg commented on Apr 27, 2020

    @mdanatg

    @dathudeptrai Consider following #38287, it will help push for a faster resolution.

  26. MMingabc commented on Nov 11, 2022

    @MMingabc

    I think this bug is extremely affecting user decisions in NLP deployment. Everything is fine for me when I am aware of this and use a warm-up variable length trick to avoid this slow bug.

    Hi, dathudeptrai
    I am a faithful user of your TensorFlowTTS. A lot of my code is based on your project. I am facing this exact problem when inferencing on GPUs. Do we have a better solution now? I am a little sad hearing you are stiring to PyTorch. Looking forwards to owesome updates in TensorFlowTTS.

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

Metadata

Metadata

Assignees

Labels

TF 2.0comp:runtimetype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions