Repository navigation
Description
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):
Win10 - CUDA/cuDNN version:
CUDA 10.1/cuDNN 7 - TensorFlow version (use command below):
2.3.0 - Python version:
3.7.4 - GPU model and memory:
Geforce GTX 1660Ti (6GB)
Describe the current behavior
-
I tried to use both TF2 and PyTorch to train SkipGram model with negative sampling. But notice a huge training speed difference.
-
TF2 takes ~0.5s to finish one step while PyTorch takes ~0.01s. One step refers to use 1 batch data to do forward and backward and update the weights.
-
The main difference is in backward propagation.
-
More specifically, 'apply_gradients()' in TF2 is much slower than counterpart 'step()' in PyTorch. Does anyone know why?
-
Notes:
- Both versions use GPU.
- tf.function is used.
- Training batch size and data is exactly the same.
- Model size (vocab_size, emb_size) is the same.
- TF2:
@tf.function
def train_step_tf(pos_w, pos_v, neg_v):
print('-'*50)
with tf.GradientTape() as tape:
loss = skip_gram_model_tf(pos_w, pos_v, neg_v)
start_time = time.time()
variables = skip_gram_model_tf.trainable_variables
print('getting variables time = {}'.format(time.time() - start_time))
start_time = time.time()
gradients = tape.gradient(loss, variables)
print('init gradient time = {}'.format(time.time() - start_time))
start_time = time.time()
optimizer.apply_gradients(zip(gradients, variables)) # !!!!! this is where the major speed difference happens!!!!!
print('apply gradient time = {}'.format(time.time() - start_time))
print('-'*50)
return loss
- PyTorch:
def train_step_torch(pos_w, pos_v, neg_v):
print('-'*50)
start_time = time.time()
optimizer_torch.zero_grad()
loss = skip_gram_model_torch.forward(pos_w, pos_v, neg_v)
print('getting variables time = {}'.format(time.time() - start_time))
start_time = time.time()
loss.backward()
print('init gradient time = {}'.format(time.time() - start_time))
start_time = time.time()
optimizer_torch.step() # !!!!this is fast!!!!
print('apply gradient time = {}'.format(time.time() - start_time))
print('-'*50)
return loss
Describe the expected behavior
I expect the performance shouldn't be that different. Is there anything I miss to use in TF2?
Standalone code to reproduce the issue
Colab link of full code:
https://colab.research.google.com/drive/17QsTkV271LPvo6aJf1QOGuumdU8OXmVj?usp=sharing
Activity
WindQAQ commentedon Aug 18, 2020
Hi @TAIYISONG , I make some changes and see the speed is the same. Please ignore the first step because tensorflow allocates optimizer's variable slots in this step.
tf.functiondecorator: I'm not sure why removing this is faster.https://colab.research.google.com/drive/1a__vqNBplMV8SvQpjfTlACFJsjwqsFn3?usp=sharing
TAIYISONG commentedon Aug 19, 2020
Hi @WindQAQ , thanks for helping me out! (What is the 'first step' you are referring to?)
Your suggestion works. But I test out some scenarios on my own machine (1660Ti) following your idea:
(above points are the same as in @WindQAQ notebook and findings)
and still find something worth digging into:
Compare (1 vs 2);
Yes TF with this setting could be as fast as PyTorch as you point out.
Compare (1 vs 3) and (4 vs 5);
Why @tf.function works to accelerate Adam, but not SGD (even 10 times slower)?
Compare (5 vs 6);
In terms of using Adam, why TF is ~20 times slower than PyTorch ? (original question)
Compare (1 vs 4):
Different optimizer and tf.function usage can make 100 times training speed difference?!
Compare (2 vs 6):
PyTorch is more stable in terms of switching optimizer. (yes Adam is much more time-consuming than SGD.)
What is the black magic behind the scene?
It's kind of awkward if TF is much less stable than PyTorch in terms of switching and testing different optimizer.
dathudeptrai commentedon Aug 19, 2020
@TAIYISONG @WindQAQ maybe this issue related with (#38287).
TAIYISONG commentedon Aug 19, 2020
@dathudeptrai
Yes it seems similar, and this issue is more on optimizer side #42475. Both are about unacceptable slow training speed.
mdanatg commentedon Nov 6, 2020
@TAIYISONG this is an interesting comparison. There are a few things which are probably not obvious, and I think this issue highlights some of them. Let me detail the differences first, and then I'll look into making the necessary modifications so that we can measure the actual performance of tf.function.
First, I should note that
@tf.functionis more similar to TorchScript than it it to PyTorch. When comparing TensorFlow directly with PyTorch, it's more of an apples-to-apples comparison to run the TF code eagerly. So in this case, you should remove the@tf.function.Of course, the same code (or something similar) should work with
tf.functionas well, but in this case it's running into problem of excessive retracing. I'll add a separate comment about that.Once I removed
@tf.functionon the original code, TF was actually faster in the limit:TF Eager:
PyTorch:
I'll modify the code in your colab a bit to demonstrate how to effectively run it with
@tf.functionas well, for comparison. Will post an update in a few hours with that.5 remaining items
mdanatg commentedon Nov 9, 2020
Thanks. I don't think I have access to the original colab so I made some copies. But indeed I forgot to change
SGDback toAdamin my colab. I fixed the results. Here are the colabs as well:So it seems that even in nightly, TF is still >20 x slower than PyTorch, and judging from the CPU-only results, it seems that TF doesn't properly use the GPU in this case.
TAIYISONG commentedon Nov 9, 2020
I set the original colab as "Anyone on the internet with this link can edit". I don't have access to above 2 new colabs either, but not a big deal lol.
Is there any plan under way to 'fix' this issue in TF?
Not only about Adam optimizer inefficiency but also other original questions about tf.function are still unclear:
(quoted from the comparison I did with @WindQAQ in the beggining)
Still I would like to use the most advanced optimizer in my work. RANGER optimizer, which refers to the combo of newly introduced optimizers LOOKAHEAD and RADAM, is even worse than Adam in our tests above.
Just out of interest sake, why difference optimizers could make such big difference in performance in TF?
Is it because Adam is not supported well in GPU?
mdanatg commentedon Nov 9, 2020
Yes, this is a significant bug and we definitely plan to fix it, though I couldn't give an exact timeline. We're currently discussing a few solutions internally.
The choice of optimizer influences performance so much is due to the nature of the bug: essentially, we have some computations that are executed on the CPU (likely the embedding lookups). That causes data transfers between CPU and GPU, which are very slow. Different optimizers result in different numbers of such transfers, and that would explain why results vary so wildly.
P.S. I just realized I edited your original colab - that was not intentional, sorry about it!
cheshire commentedon Nov 9, 2020
For more context, this is explicit CPU placement in the embeddings layer: https://cs.opensource.google/tensorflow/tensorflow/+/master:tensorflow/python/keras/layers/embeddings.py;l=141?q=layers%2Fembeddings.py%20file:tensorflow
fridex commentedon Nov 9, 2020
Is this bug specific only to tensorflow==2.3.0 or does it apply also to older versions?
mdanatg commentedon Nov 9, 2020
The explicit placement was done two years ago, so it probably applies to all versions of
kers.layers.Embedding. That said, it might go unnoticed in practice if for example the embedding table is too large to fit the GPU memory, or if the model is large enough to dominate the compute time.TAIYISONG commentedon Nov 9, 2020
Thanks @mdanatg, good to know more about TF schema behind the scene and you guys are planning to update it. Looking forward to seeing the issue go away. :)
jvishnuvardhan commentedon Nov 9, 2021
@TAIYISONG Looks like this was resolved in recent TF versions. I ran your code with
TF2.7and the computation times are similar. Please check the gist here. Thanks!TAIYISONG commentedon Nov 10, 2021
@jvishnuvardhan Thanks for the update. So glad to see the issue is resolved in 2.7.0!
@mdanatg Thanks for taking this issue previously, also many thanks to the engineers who fixed this!!! :)