Best practice to write code compatible to both TensorFlow 1 and 2

拥有回忆 提交于 2020-04-17 22:56:06

问题


This official guide explains how to migrate TF 1 code to TF 2. This is however not what I want. I want that my code runs fine on both TF 1 and TF 2 (and I only want the non-eager mode). Also, I slowly want to use some of the new features, but in an optional way. (E.g. the user could pass some option like --use-fancy-new-tf2-feature, which would only work with TF 2. That's fine.) And maybe after one or two years, I would slowly drop the TF 1 support. But I definitely need this transition phase where both TF versions are supported.

I don't really see this question answered in the migration guide. Maybe the answer is that there simply is no "best practice" for this. Although I think that other bigger projects probably would want to do sth similar. Or maybe the answer is that this would be way too much effort, and so they simply migrate directly.

I could maybe do sth like this:

try:
  # https://www.tensorflow.org/guide/migrate
  import tensorflow.compat.v1 as tf
  tf.disable_v2_behavior()
except ImportError:
  import tensorflow as tf

However, that has some drawbacks:

  • I would need to place this code snippet in every module where I use TF.
    • I could put this in some own module, like tf_import.py, and then simply do from tf_import import tf everywhere. But this is somewhat ugly.
  • This might make code complicated which actually wants to use some new TF 2 feature.

I could maybe do sth like this:

try:
  # https://www.tensorflow.org/guide/migrate
  import tensorflow.compat.v1 as tf1
  tf1.disable_v2_behavior()
  import tensorflow as tf2
except ImportError:
  import tensorflow as tf1
  tf2 = None

This might be more clean. But I'm not sure if this is the way to go. Or how other people do it.

Also, instead of calling disable_v2_behavior, I could maybe just call disable_eager_execution. But that might make some other code more difficult to make compatible for both TF 1 and TF 2.

(I'm collecting some of these thoughts in this GitHub issue for our project RETURNN.)

来源:https://stackoverflow.com/questions/60966376/best-practice-to-write-code-compatible-to-both-tensorflow-1-and-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!