![]() | ![]() | ![]() | ![]() |
TensorFlow 2.0には、引数の並べ替え、シンボルの名前変更、パラメーターのデフォルト値の変更など、多くのAPIの変更が含まれています。これらの変更をすべて手動で実行するのは面倒で、エラーが発生しやすくなります。変更を合理化し、TF 2.0への移行を可能な限りシームレスにするために、TensorFlowチームはレガシーコードを新しいAPIに移行するのに役立つtf_upgrade_v2
ユーティリティを作成しました。
一般的な使用法は次のとおりです。
tf_upgrade_v2 \ --intree my_project/ \ --outtree my_project_v2/ \ --reportfile report.txt
既存のTensorFlow1.xPythonスクリプトをTensorFlow2.0に変換することで、アップグレードプロセスを加速します。
変換スクリプトは可能な限り自動化しますが、スクリプトでは実行できない構文上および文体上の変更がまだあります。
互換性モジュール
特定のAPIシンボルは、文字列置換を使用するだけではアップグレードできません。コードがTensorFlow2.0で引き続きサポートされるようにするために、アップグレードスクリプトにはcompat.v1
モジュールが含まれてcompat.v1
ます。このモジュールは、 tf.foo
などのtf.foo
シンボルを同等のtf.compat.v1.foo
参照にtf.compat.v1.foo
ます。互換性モジュールは優れていますが、置換を手動で校正し、 tf.compat.v1
名前空間ではなくtf.*
名前空間の新しいAPIにtf.compat.v1
移行することをお勧めします。
なぜならTensorFlow 2.xのモジュール非推奨(例えば、のtf.flags
及びtf.contrib
)、いくつかの変更は、に切り替えることで回避することができないcompat.v1
。このコードをアップグレードするには、追加のライブラリ( absl.flags
)を使用するか、 tensorflow / addonsのパッケージに切り替える必要があります。
推奨されるアップグレードプロセス
このガイドの残りの部分では、アップグレードスクリプトの使用方法を示します。アップグレードスクリプトは簡単に使用できますが、次のプロセスの一部としてスクリプトを使用することを強くお勧めします。
単体テスト:アップグレードするコードに、妥当な範囲の単体テストスイートがあることを確認します。これはPythonコードであるため、この言語は多くのクラスの間違いからユーザーを保護しません。また、TensorFlow2.0と互換性があるようにすでにアップグレードされている依存関係があることを確認してください。
TensorFlow 1.14をインストールします。TensorFlowを最新のTensorFlow1.xバージョン(少なくとも1.14)にアップグレードします。これには、tf.compat.v2の最終的なTensorFlow 2.0APIが含まれ
tf.compat.v2
。1.14でテスト:この時点でユニットテストに合格していることを確認します。アップグレードすると繰り返し実行されるため、グリーンから始めることが重要です。
アップグレードスクリプトを実行します。テストを含め、ソースツリー全体で
tf_upgrade_v2
を実行します。これにより、コードがTensorFlow2.0で使用可能なシンボルのみを使用する形式にアップグレードされます。非推奨のシンボルには、tf.compat.v1
を使用してアクセスしtf.compat.v1
。これらは最終的には手動による注意が必要になりますが、すぐには必要ありません。変換されたテストをTensorFlow1.14で実行します。コードはTensorFlow1.14でも正常に実行されるはずです。単体テストを再度実行します。ここでのテストにエラーがある場合は、アップグレードスクリプトにバグがあることを意味します。お知らせください。
警告とエラーがないかアップグレードレポートを確認します。スクリプトは、再確認する必要のある変換、または実行する必要のある手動アクションを説明するレポートファイルを書き込みます。例:contribの残りのインスタンスは、削除するために手動のアクションが必要になります。詳細な手順については、RFCを参照してください。
TensorFlow 2.0をインストールする:この時点で、TensorFlow2.0に安全に切り替えることができます。
v1.disable_v2_behavior
テスト:テストのメイン関数でalv1.disable_v2_behavior()
してテストを再実行すると、1.14で実行した場合と同じ結果が得られます。V2動作を有効にする:テストがv2 APIを使用して機能するようになったので、v2動作をオンにすることを検討し始めることができます。コードの記述方法によっては、変更が必要になる場合があります。詳細については、移行ガイドを参照してください。
アップグレードスクリプトの使用
セットアップ
開始する前に、TensorlFlow2.0がインストールされていることを確認してください。
import tensorflow as tf
print(tf.__version__)
2.3.0
tensorflow / models gitリポジトリのクローンを作成して、テストするコードを作成します。
git clone --branch r1.13.0 --depth 1 https://github.com/tensorflow/models
Cloning into 'models'... remote: Enumerating objects: 2927, done.[K remote: Counting objects: 100% (2927/2927), done.[K remote: Compressing objects: 100% (2449/2449), done.[K remote: Total 2927 (delta 509), reused 2036 (delta 403), pack-reused 0[K Receiving objects: 100% (2927/2927), 369.04 MiB | 44.65 MiB/s, done. Resolving deltas: 100% (509/509), done. Checking out files: 100% (2768/2768), done.
ヘルプを読む
スクリプトはTensorFlowとともにインストールする必要があります。組み込みのヘルプは次のとおりです。
tf_upgrade_v2 -h
2020-09-10 01:42:59.274658: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 usage: tf_upgrade_v2 [-h] [--infile INPUT_FILE] [--outfile OUTPUT_FILE] [--intree INPUT_TREE] [--outtree OUTPUT_TREE] [--copyotherfiles COPY_OTHER_FILES] [--inplace] [--no_import_rename] [--no_upgrade_compat_v1_import] [--reportfile REPORT_FILENAME] [--mode {DEFAULT,SAFETY}] [--print_all] Convert a TensorFlow Python file from 1.x to 2.0 Simple usage: tf_upgrade_v2.py --infile foo.py --outfile bar.py tf_upgrade_v2.py --infile foo.ipynb --outfile bar.ipynb tf_upgrade_v2.py --intree ~/code/old --outtree ~/code/new optional arguments: -h, --help show this help message and exit --infile INPUT_FILE If converting a single file, the name of the file to convert --outfile OUTPUT_FILE If converting a single file, the output filename. --intree INPUT_TREE If converting a whole tree of files, the directory to read from (relative or absolute). --outtree OUTPUT_TREE If converting a whole tree of files, the output directory (relative or absolute). --copyotherfiles COPY_OTHER_FILES If converting a whole tree of files, whether to copy the other files. --inplace If converting a set of files, whether to allow the conversion to be performed on the input files. --no_import_rename Not to rename import to compat.v2 explicitly. --no_upgrade_compat_v1_import If specified, don't upgrade explicit imports of `tensorflow.compat.v1 as tf` to the v2 apis. Otherwise, explicit imports of the form `tensorflow.compat.v1 as tf` will be upgraded. --reportfile REPORT_FILENAME The name of the file where the report log is stored.(default: report.txt) --mode {DEFAULT,SAFETY} Upgrade script mode. Supported modes: DEFAULT: Perform only straightforward conversions to upgrade to 2.0. In more difficult cases, switch to use compat.v1. SAFETY: Keep 1.* code intact and import compat.v1 module. --print_all Print full log to stdout instead of just printing errors
TF1コードの例
簡単なTensorFlow1.0スクリプトを次に示します。
head -n 65 models/samples/cookbook/regression/custom_regression.py | tail -n 10
# Calculate loss using mean squared error average_loss = tf.losses.mean_squared_error(labels, predictions) # Pre-made estimators use the total_loss instead of the average, # so report total_loss for compatibility. batch_size = tf.shape(labels)[0] total_loss = tf.to_float(batch_size) * average_loss if mode == tf.estimator.ModeKeys.TRAIN: optimizer = params.get("optimizer", tf.train.AdamOptimizer)
TensorFlow 2.0がインストールされていると、実行されません。
(cd models/samples/cookbook/regression && python custom_regression.py)
2020-09-10 01:43:01.613673: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 Traceback (most recent call last): File "custom_regression.py", line 162, in <module> tf.logging.set_verbosity(tf.logging.INFO) AttributeError: module 'tensorflow' has no attribute 'logging'
単一ファイル
アップグレードスクリプトは、単一のPythonファイルで実行できます。
!tf_upgrade_v2 \
--infile models/samples/cookbook/regression/custom_regression.py \
--outfile /tmp/custom_regression_v2.py
2020-09-10 01:43:03.844314: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 INFO line 38:8: Renamed 'tf.feature_column.input_layer' to 'tf.compat.v1.feature_column.input_layer' INFO line 43:10: Renamed 'tf.layers.dense' to 'tf.compat.v1.layers.dense' INFO line 46:17: Renamed 'tf.layers.dense' to 'tf.compat.v1.layers.dense' INFO line 57:17: tf.losses.mean_squared_error requires manual check. tf.losses have been replaced with object oriented versions in TF 2.0 and after. The loss function calls have been converted to compat.v1 for backward compatibility. Please update these calls to the TF 2.0 versions. INFO line 57:17: Renamed 'tf.losses.mean_squared_error' to 'tf.compat.v1.losses.mean_squared_error' INFO line 61:15: Added keywords to args of function 'tf.shape' INFO line 62:15: Changed tf.to_float call to tf.cast(..., dtype=tf.float32). INFO line 65:40: Renamed 'tf.train.AdamOptimizer' to 'tf.compat.v1.train.AdamOptimizer' INFO line 68:39: Renamed 'tf.train.get_global_step' to 'tf.compat.v1.train.get_global_step' INFO line 83:9: tf.metrics.root_mean_squared_error requires manual check. tf.metrics have been replaced with object oriented versions in TF 2.0 and after. The metric function calls have been converted to compat.v1 for backward compatibility. Please update these calls to the TF 2.0 versions. INFO line 83:9: Renamed 'tf.metrics.root_mean_squared_error' to 'tf.compat.v1.metrics.root_mean_squared_error' INFO line 142:23: Renamed 'tf.train.AdamOptimizer' to 'tf.compat.v1.train.AdamOptimizer' INFO line 162:2: Renamed 'tf.logging.set_verbosity' to 'tf.compat.v1.logging.set_verbosity' INFO line 162:27: Renamed 'tf.logging.INFO' to 'tf.compat.v1.logging.INFO' INFO line 163:2: Renamed 'tf.app.run' to 'tf.compat.v1.app.run' TensorFlow 2.0 Upgrade Script ----------------------------- Converted 1 files Detected 0 issues that require attention -------------------------------------------------------------------------------- Make sure to read the detailed log 'report.txt'
コードの修正が見つからない場合、スクリプトはエラーを出力します。
ディレクトリツリー
この簡単な例を含む一般的なプロジェクトでは、複数のファイルを使用します。通常、パッケージ全体をアップグレードする必要があるため、スクリプトはディレクトリツリーでも実行できます。
# upgrade the .py files and copy all the other files to the outtree
!tf_upgrade_v2 \
--intree models/samples/cookbook/regression/ \
--outtree regression_v2/ \
--reportfile tree_report.txt
2020-09-10 01:43:06.108169: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1 INFO line 82:10: tf.estimator.LinearRegressor: Default value of loss_reduction has been changed to SUM_OVER_BATCH_SIZE; inserting old default value tf.keras.losses.Reduction.SUM. INFO line 105:2: Renamed 'tf.logging.set_verbosity' to 'tf.compat.v1.logging.set_verbosity' INFO line 105:27: Renamed 'tf.logging.INFO' to 'tf.compat.v1.logging.INFO' INFO line 106:2: Renamed 'tf.app.run' to 'tf.compat.v1.app.run' INFO line 58:10: tf.estimator.LinearRegressor: Default value of loss_reduction has been changed to SUM_OVER_BATCH_SIZE; inserting old default value tf.keras.losses.Reduction.SUM. INFO line 101:2: Renamed 'tf.logging.set_verbosity' to 'tf.compat.v1.logging.set_verbosity' INFO line 101:27: Renamed 'tf.logging.INFO' to 'tf.compat.v1.logging.INFO' INFO line 102:2: Renamed 'tf.app.run' to 'tf.compat.v1.app.run' WARNING line 125:15: Changing dataset.make_one_shot_iterator() to tf.compat.v1.data.make_one_shot_iterator(dataset). Please check this transformation. INFO line 72:10: tf.estimator.DNNRegressor: Default value of loss_reduction has been changed to SUM_OVER_BATCH_SIZE; inserting old default value tf.keras.losses.Reduction.SUM. INFO line 96:2: Renamed 'tf.logging.set_verbosity' to 'tf.compat.v1.logging.set_verbosity' INFO line 96:27: Renamed 'tf.logging.INFO' to 'tf.compat.v1.logging.INFO' INFO line 97:2: Renamed 'tf.app.run' to 'tf.compat.v1.app.run' INFO line 38:8: Renamed 'tf.feature_column.input_layer' to 'tf.compat.v1.feature_column.input_layer' INFO line 43:10: Renamed 'tf.layers.dense' to 'tf.compat.v1.layers.dense' INFO line 46:17: Renamed 'tf.layers.dense' to 'tf.compat.v1.layers.dense' INFO line 57:17: tf.losses.mean_squared_error requires manual check. tf.losses have been replaced with object oriented versions in TF 2.0 and after. The loss function calls have been converted to compat.v1 for backward compatibility. Please update these calls to the TF 2.0 versions. INFO line 57:17: Renamed 'tf.losses.mean_squared_error' to 'tf.compat.v1.losses.mean_squared_error' INFO line 61:15: Added keywords to args of function 'tf.shape' INFO line 62:15: Changed tf.to_float call to tf.cast(..., dtype=tf.float32). INFO line 65:40: Renamed 'tf.train.AdamOptimizer' to 'tf.compat.v1.train.AdamOptimizer' INFO line 68:39: Renamed 'tf.train.get_global_step' to 'tf.compat.v1.train.get_global_step' INFO line 83:9: tf.metrics.root_mean_squared_error requires manual check. tf.metrics have been replaced with object oriented versions in TF 2.0 and after. The metric function calls have been converted to compat.v1 for backward compatibility. Please update these calls to the TF 2.0 versions. INFO line 83:9: Renamed 'tf.metrics.root_mean_squared_error' to 'tf.compat.v1.metrics.root_mean_squared_error' INFO line 142:23: Renamed 'tf.train.AdamOptimizer' to 'tf.compat.v1.train.AdamOptimizer' INFO line 162:2: Renamed 'tf.logging.set_verbosity' to 'tf.compat.v1.logging.set_verbosity' INFO line 162:27: Renamed 'tf.logging.INFO' to 'tf.compat.v1.logging.INFO' INFO line 163:2: Renamed 'tf.app.run' to 'tf.compat.v1.app.run' INFO line 40:7: Renamed 'tf.test.mock' to 'tf.compat.v1.test.mock' TensorFlow 2.0 Upgrade Script ----------------------------- Converted 7 files Detected 1 issues that require attention -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- File: models/samples/cookbook/regression/automobile_data.py -------------------------------------------------------------------------------- models/samples/cookbook/regression/automobile_data.py:125:15: WARNING: Changing dataset.make_one_shot_iterator() to tf.compat.v1.data.make_one_shot_iterator(dataset). Please check this transformation. Make sure to read the detailed log 'tree_report.txt'
dataset.make_one_shot_iterator
関数に関する1つの警告に注意してください。
これで、スクリプトはTensorFlow2.0で機能します。
tf.compat.v1
モジュールであるため、変換されたスクリプトはTensorFlow1.14でも実行されることに注意してください。
(cd regression_v2 && python custom_regression.py 2>&1) | tail
data = raw_dataframe() File "/tmpfs/src/temp/site/en/guide/regression_v2/automobile_data.py", line 67, in raw_dataframe dtype=COLUMN_TYPES, na_values="?") File "/home/kbuilder/.local/lib/python3.6/site-packages/pandas/io/parsers.py", line 686, in read_csv return _read(filepath_or_buffer, kwds) File "/home/kbuilder/.local/lib/python3.6/site-packages/pandas/io/parsers.py", line 449, in _read _validate_names(kwds.get("names", None)) File "/home/kbuilder/.local/lib/python3.6/site-packages/pandas/io/parsers.py", line 417, in _validate_names raise ValueError("Names should be an ordered collection.") ValueError: Names should be an ordered collection.
詳細レポート
スクリプトは、詳細な変更のリストも報告します。この例では、安全でない可能性のある変換が1つ見つかり、ファイルの先頭に警告が含まれていました。
head -n 20 tree_report.txt
TensorFlow 2.0 Upgrade Script ----------------------------- Converted 7 files Detected 1 issues that require attention -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- File: models/samples/cookbook/regression/automobile_data.py -------------------------------------------------------------------------------- models/samples/cookbook/regression/automobile_data.py:125:15: WARNING: Changing dataset.make_one_shot_iterator() to tf.compat.v1.data.make_one_shot_iterator(dataset). Please check this transformation. ================================================================================ Detailed log follows: ================================================================================ ================================================================================ Input tree: 'models/samples/cookbook/regression/' ================================================================================ -------------------------------------------------------------------------------- Processing file 'models/samples/cookbook/regression/linear_regression_categorical.py' outputting to 'regression_v2/linear_regression_categorical.py'
Dataset.make_one_shot_iterator function
に関する1つの警告に再度注意してください。
その他の場合、出力は重要な変更の理由を説明します。
%%writefile dropout.py
import tensorflow as tf
d = tf.nn.dropout(tf.range(10), 0.2)
z = tf.zeros_like(d, optimize=False)
Writing dropout.py
!tf_upgrade_v2 \
--infile dropout.py \
--outfile dropout_v2.py \
--reportfile dropout_report.txt > /dev/null
2020-09-10 01:43:10.977249: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
cat dropout_report.txt
TensorFlow 2.0 Upgrade Script ----------------------------- Converted 1 files Detected 0 issues that require attention -------------------------------------------------------------------------------- ================================================================================ Detailed log follows: ================================================================================ -------------------------------------------------------------------------------- Processing file 'dropout.py' outputting to 'dropout_v2.py' -------------------------------------------------------------------------------- 3:4: INFO: Changing keep_prob arg of tf.nn.dropout to rate, and recomputing value. 4:4: INFO: Renaming tf.zeros_like to tf.compat.v1.zeros_like because argument optimize is present. tf.zeros_like no longer takes an optimize argument, and behaves as if optimize=True. This call site specifies something other than optimize=True, so it was converted to compat.v1. --------------------------------------------------------------------------------
変更されたファイルの内容は次のとおりです。スクリプトが引数名を追加して、移動および名前変更された引数を処理する方法に注意してください。
cat dropout_v2.py
import tensorflow as tf d = tf.nn.dropout(tf.range(10), 1 - (0.2)) z = tf.compat.v1.zeros_like(d, optimize=False)
大規模なプロジェクトには、いくつかのエラーが含まれる場合があります。たとえば、deeplabモデルを変換します。
!tf_upgrade_v2 \
--intree models/research/deeplab \
--outtree deeplab_v2 \
--reportfile deeplab_report.txt > /dev/null
2020-09-10 01:43:13.488610: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
出力ファイルを生成しました:
ls deeplab_v2
README.md datasets input_preprocess.py train.py __init__.py deeplab_demo.ipynb local_test.sh utils common.py eval.py local_test_mobilenetv2.sh vis.py common_test.py export_model.py model.py core g3doc model_test.py
しかし、エラーがありました。レポートは、これを実行する前に修正する必要があるものを特定するのに役立ちます。最初の3つのエラーは次のとおりです。
cat deeplab_report.txt | grep -i models/research/deeplab | grep -i error | head -n 3
models/research/deeplab/export_model.py:25:7: ERROR: Using member tf.contrib.slim in deprecated module tf.contrib. tf.contrib.slim cannot be converted automatically. tf.contrib will not be distributed with TensorFlow 2.0, please consider an alternative in non-contrib TensorFlow, a community-maintained repository such as tensorflow/addons, or fork the required code. models/research/deeplab/eval.py:28:7: ERROR: Using member tf.contrib.slim in deprecated module tf.contrib. tf.contrib.slim cannot be converted automatically. tf.contrib will not be distributed with TensorFlow 2.0, please consider an alternative in non-contrib TensorFlow, a community-maintained repository such as tensorflow/addons, or fork the required code. models/research/deeplab/eval.py:146:8: ERROR: Using member tf.contrib.metrics.aggregate_metric_map in deprecated module tf.contrib. tf.contrib.metrics.aggregate_metric_map cannot be converted automatically. tf.contrib will not be distributed with TensorFlow 2.0, please consider an alternative in non-contrib TensorFlow, a community-maintained repository such as tensorflow/addons, or fork the required code.
「セーフ」モード
変換スクリプトには、 tensorflow.compat.v1
モジュールを使用するようにインポートを変更するだけの低侵襲のSAFETY
モードもあります。
cat dropout.py
import tensorflow as tf d = tf.nn.dropout(tf.range(10), 0.2) z = tf.zeros_like(d, optimize=False)
tf_upgrade_v2 --mode SAFETY --infile dropout.py --outfile dropout_v2_safe.py > /dev/null
2020-09-10 01:43:17.892207: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library libcudart.so.10.1
cat dropout_v2_safe.py
import tensorflow.compat.v1 as tf d = tf.nn.dropout(tf.range(10), 0.2) z = tf.zeros_like(d, optimize=False)
ご覧のとおり、これによってコードがアップグレードされることはありませんが、TensorFlow1コードをTensorFlow2で実行できます。
警告
このスクリプトを実行する前に、コードの一部を手動で更新しないでください。特に、
tf.argmax
やtf.batch_to_space
ような引数を並べ替えた関数は、スクリプトが既存のコードを誤ってマップするキーワード引数を誤って追加する原因になります。スクリプトは、
import tensorflow as tf
使用してtensorflow
がインポートされることを前提としています。このスクリプトは引数を並べ替えません。代わりに、スクリプトは、引数が並べ替えられた関数にキーワード引数を追加します。
GitHubリポジトリ内のJupyterノートブックとPythonファイルをアップグレードするための便利なツールについては、 tf2up.mlを確認してください。
アップグレードスクリプトのバグを報告したり、機能をリクエストしたりするには、 GitHubで問題を報告してください。また、TensorFlow 2.0をテストしている場合は、それについてお聞きしたいと思います。 TF 2.0テストコミュニティに参加し、 testing @ tensorflow.orgに質問とディスカッションを送信してください。