Repository navigation
Description
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
muddham commentedon May 30, 2019
@guillaumekln Able to reproduce the issue, but the numbers in the output are different from the numbers you mentioned.
guillaumekln commentedon Jun 7, 2019
Any update? This is still valid as of
2.0.0.dev20190606.alextp commentedon Jun 10, 2019
@allenlavoie do we retrace even when a signature is passed?
allenlavoie commentedon Jun 10, 2019
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.
guillaumekln commentedon Jun 10, 2019
The
tf.functionitself is not retraced. For reference, it worked properly in the alpha release (to compare with the logs above):guillaumekln commentedon Jun 12, 2019
So after bisecting the nightly builds, I found that this behavior was introduced in
2.0.0.dev20190329. Then I rangit bisecton 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.
31 remaining items
guillaumekln commentedon Nov 1, 2019
@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.
mdanatg commentedon Nov 2, 2019
+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:
georgesterpu commentedon Nov 3, 2019
Thank you for your advice, @guillaumekln and @mdanatg
The code snippet of @mdanatg works well for the train step, and it returns several warnings:
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.FinalBeamSearchDecoderOutputstruct (eval step). On theoptional.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 theOptionalcode, 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:And it also logs this warning:
mdanatg commentedon Nov 4, 2019
If you have a colab where all these can be reproduced, it would be helpful to make sure I don't misunderstand anything.
FinalBeamSearchDecoderOutputis a namedtuple, sonest.map_structureshould be able to deal with it properly, but I may be missing something.About the second solution, if
_run_steptakes a function it might retrace excessively - what if you just directly pass the iterator? If you callnext(it)inside the @tf.function, theOutOfRangeErrorshould bubble all the way into the eager runtime.szc11121 commentedon Apr 2, 2020
mdanatg commentedon Apr 2, 2020
@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.
szc11121 commentedon Apr 4, 2020
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
mdanatg commentedon Apr 6, 2020
@szc11121 indeed, looks like a performance issue with embedding layers. I modified your code a little and filed #38287 to track the issue separately.
dathudeptrai commentedon Apr 24, 2020
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
mdanatg commentedon Apr 24, 2020
@dathudeptrai does the model warm up faster if you use
tf.function(experimental_relax_shapes=True)?dathudeptrai commentedon Apr 24, 2020
@mdanatg i use saved graph, do i need tf.function?
mdanatg commentedon Apr 24, 2020
I think saved graphs don't require tf.function (because it was already applied before saving them). @k-w-w thoughts?
dathudeptrai commentedon Apr 24, 2020
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.
mdanatg commentedon Apr 27, 2020
@dathudeptrai Consider following #38287, it will help push for a faster resolution.
MMingabc commentedon Nov 11, 2022
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.