Skip to content

Tensorflow 2.3.0 is much slower than PyTorch 1.4.0 in backward propagation. (20 times slower) #42475

Closed

Description

@TAIYISONG

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:

  1. Both versions use GPU.
  2. tf.function is used.
  3. Training batch size and data is exactly the same.
  4. 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

  1. WindQAQ commented on Aug 18, 2020

    @WindQAQ
    Member

    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.

    1. You use adam for tf and sgd for pytorch: adam is much more time-consuming than sgd.
    2. remove tf.function decorator: I'm not sure why removing this is faster.

    https://colab.research.google.com/drive/1a__vqNBplMV8SvQpjfTlACFJsjwqsFn3?usp=sharing

  2. TAIYISONG commented on Aug 19, 2020

    @TAIYISONG
    Author

    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.

    1. You use adam for tf and sgd for pytorch: adam is much more time-consuming than sgd.
    2. remove tf.function decorator: I'm not sure why removing this is faster.

    https://colab.research.google.com/drive/1a__vqNBplMV8SvQpjfTlACFJsjwqsFn3?usp=sharing

    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:

    1. [email protected] takes 0.009s.
    2. Torch-SGD takes 0.009s.
    3. [email protected] takes 0.09s
      (above points are the same as in @WindQAQ notebook and findings)
    4. [email protected] takes 0.9s
    5. [email protected] takes 0.5s
    6. Torch-Adam takes 0.03s

    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.

  3. added
    TF 2.3
    on Aug 19, 2020
  4. dathudeptrai commented on Aug 19, 2020

    @dathudeptrai

    @TAIYISONG @WindQAQ maybe this issue related with (#38287).

  5. TAIYISONG commented on Aug 19, 2020

    @TAIYISONG
    Author

    @TAIYISONG @WindQAQ maybe this issue related with (#38287).

    @dathudeptrai
    Yes it seems similar, and this issue is more on optimizer side #42475. Both are about unacceptable slow training speed.

  6. added
    comp:autograph
    on Aug 26, 2020
  7. added
    stat:awaiting tensorflower
    on Nov 6, 2020
  8. mdanatg commented on Nov 6, 2020

    @mdanatg

    @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.function is 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.function as 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.function on the original code, TF was actually faster in the limit:

    TF Eager:

    1 step takes 0.4307682514190674 s
    1 step takes 0.013715505599975586 s
    1 step takes 0.013556718826293945 s
    

    PyTorch:

    1 step takes 0.21025729179382324 s
    1 step takes 0.010649442672729492 s
    1 step takes 0.015627145767211914 s
    

    I'll modify the code in your colab a bit to demonstrate how to effectively run it with @tf.function as well, for comparison. Will post an update in a few hours with that.

  9. added
    comp:keras
    comp:core
    and removed
    comp:autograph
    on Nov 7, 2020
  10. 5 remaining items

  11. mdanatg commented on Nov 9, 2020

    @mdanatg

    Thanks. I don't think I have access to the original colab so I made some copies. But indeed I forgot to change SGD back to Adam in 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.

  12. TAIYISONG commented on Nov 9, 2020

    @TAIYISONG
    Author

    Thanks. I don't think I have access to the original colab so I made some copies. But indeed I forgot to change SGD back to Adam in 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.

    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)

    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.)

    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?

  13. mdanatg commented on Nov 9, 2020

    @mdanatg

    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!

  14. fridex commented on Nov 9, 2020

    @fridex

    Is this bug specific only to tensorflow==2.3.0 or does it apply also to older versions?

  15. mdanatg commented on Nov 9, 2020

    @mdanatg

    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.

  16. TAIYISONG commented on Nov 9, 2020

    @TAIYISONG
    Author

    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. :)

  17. added
    stat:awaiting tensorflower
    on Nov 13, 2020
  18. jvishnuvardhan commented on Nov 9, 2021

    @jvishnuvardhan
    Contributor

    @TAIYISONG Looks like this was resolved in recent TF versions. I ran your code with TF2.7 and the computation times are similar. Please check the gist here. Thanks!

  19. added
    stat:awaiting response
    and removed
    stat:awaiting tensorflower
    on Nov 9, 2021
  20. TAIYISONG commented on Nov 10, 2021

    @TAIYISONG
    Author

    @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!!! :)

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

Metadata

Metadata

Labels

TF 2.3comp:corecomp:kerasstat:awaiting responsetype:performance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions