TF 1.x 및 compat.v1 API 심볼 자동 재작성

TensorFlow.org에서보기 Google Colab에서 실행하기 GitHub에서 소스 보기 노트북 다운로드하기

TensorFlow 2.x에는 TF 1.x 및 tf.compat.v1 API로부터 많은 API 변경이 도입되었는데, 예를 들면 인수 순서 변경, 심볼 이름 바꾸기 및 매개변수의 기본값 변경을 들 수 있습니다. 이러한 모든 변경 사항을 수동으로 적용하면 번거롭고 오류가 발생하기 쉽습니다. 변경을 간소화하고 TF 2.x로 최대한 원활하게 전환할 수 있도록 TensorFlow 팀은 레거시 코드를 새 API로 전환하는 데 도움이 되는 tf_upgrade_v2 유틸리티를 만들었습니다.

참고: tf_upgrade_v2는 TensorFlow 1.13 이상(모든 TF 2.x 빌드 포함)에 대해 자동으로 설치됩니다.

일반적인 사용법은 다음과 같습니다.

tf_upgrade_v2 \
  --intree my_project/ \
  --outtree my_project_v2/ \
  --reportfile report.txt

기존 TensorFlow 1.x 파이썬 스크립트를 TensorFlow 2.x로 변환하여 업그레이드 프로세스를 가속합니다.

변환 스크립트를 통해 많은 기계적 API 변환을 자동화할 수 있지만 많은 API는 자동으로 마이그레이션할 수 없습니다. 또한 코드가 TF2 동작 및 API와 완전히 호환되도록 만들 수도 없습니다. 따라서 이것은 마이그레이션 여정의 일부일 뿐입니다.

호환성 모듈

특정 API 기호는 단순히 문자열 교체만으로 업그레이드할 수 없습니다. 자동으로 업그레이드할 수 없는 항목은 compat.v1 모듈의 해당 위치에 매핑됩니다. 이 모듈은 tf.foo와 같은 TF 1.x 기호를 해당하는 tf.compat.v1.foo 참조로 교체합니다. import tensorflow.compat.v1 as tf를 통해 TF를 가져와서 이미 compat.v1 API를 사용하고 있는 경우 tf_upgrade_v2 스크립트는 가능한 경우 이러한 사용법을 비호환 API로 변환하려고 시도합니다. compat.v1 API는 TF2.x 동작과 일부 호환되지만 대부분은 호환되지 않습니다. 따라서 교체를 수동으로 교검사하고 가능한 한 빨리 tf.compat.v1 네임스페이스 대신 tf.* 네임스페이스의 새 API로 마이그레이션하는 것이 좋습니다.

TensorFlow 2.x 모듈의 사용 중단(예: tf.flags 및 tf.contrib)으로, 일부 변경 사항은 compat.v1로 전환하여 해결할 수 없습니다. 이 코드를 업그레이드하려면 추가 라이브러리(예: absl.flags )를 사용하거나 tensorflow / addons의 패키지로 전환해야 합니다.

권장 업그레이드 프로세스

이 가이드의 나머지 부분에서는 심볼 재작성 스크립트를 사용하는 방법을 보여줍니다. 이 스크립트는 사용하기 쉽지만 다음 프로세스의 일부로 스크립트를 사용하는 것이 좋습니다.

  1. <strong data-md-type="double_emphasis">단위 테스트</strong>: 업그레이드 중인 코드에 적용 가능한 단위 테스트 도구 모음이 있는지 확인합니다. Python 코드와 같은 언어에서는 많은 종류의 실수가 보호되지 않습니다. TensorFlow 2.x와 호환되도록 모든 종속성이 업그레이드되었는지 확인합니다.

  2. TensorFlow 1.15 설치: TensorFlow를 최신 TensorFlow 1.x 버전(최소 1.15)으로 업그레이드하세요. 여기에는 tf.compat.v2의 최종 TensorFlow 2.0 API가 포함됩니다.

  3. 1.15로 테스트: 이 시점에서 단위 테스트를 통과했는지 확인합니다. 안전하게 시작하는 것이 중요하므로 업그레이드할 때 반복적으로 실행됩니다.

  4. 업그레이드 스크립트 실행: 테스트가 포함된 전체 소스 트리에서 tf_upgrade_v2를 실행합니다. 이렇게하면 코드가 TensorFlow 2.0에서 사용 가능한 기호만 사용하는 형식으로 업그레이드됩니다. 더 이상 사용되지 않는 기호는 tf.compat.v1으로 액세스됩니다. 이것들은 결국 수동적 인주의가 필요하지만, 즉시는 아닙니다.

  5. TensorFlow 1.15로 변환된 테스트 실행: 코드는 여전히 TensorFlow 1.15에서 제대로 실행되어야 합니다. 단위 테스트를 다시 실행하세요. 테스트에서 오류가 발생하면 업그레이드 스크립트에 버그가 있음을 의미합니다. 여기에서 공유해주세요.

  6. 업그레이드 보고서에 경고 및 오류가 있는지 확인: 스크립트를 통해 다시 점검해야 할 변환이나 수행해야 하는 수동 작업을 설명하는 보고서 파일이 작성됩니다. 예를 들어, 나머지 contrib 인스턴스를 제거하려면 수동 조치가 필요합니다. 자세한 내용은 RFC를 참조하세요.

  7. TensorFlow 2.x 설치: 이 시점에서는 기존 동작으로 실행하는 경우에도 TensorFlow 2.x 바이너리로 전환하는 것이 안전합니다.

  8. v1.disable_v2_behavior로 테스트: 테스트 기본 함수에서 v1.disable_v2_behavior()를 사용하여 테스트를 다시 실행하면 1.15에서 실행되는 것과 동일한 결과가 제공됩니다.

  9. V2 동작 활성화: 이제 테스트가 TF2 바이너리를 사용하여 작동하므로 이제 tf.estimator를 피하고 지원되는 TF2 동작만 사용하도록 코드 마이그레이션을 시작할 수 있습니다(TF2 동작 비활성화 없음). 자세한 내용은 마이그레이션 가이드를 참조하세요.

심볼 재작성 tf_upgrade_v2 스크립트 사용

설치하기

시작하기 전에 TensorFlow 2.x가 설치되어 있는지 확인합니다.

import tensorflow as tf

print(tf.__version__)
2022-12-14 20:30:18.393166: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:18.393261: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:18.393270: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
2.11.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% (2428/2428), done.[K
remote: Total 2927 (delta 503), reused 2114 (delta 424), pack-reused 0[K
Receiving objects: 100% (2927/2927), 369.04 MiB | 56.86 MiB/s, done.
Resolving deltas: 100% (503/503), done.
Updating files: 100% (2768/2768), done.

도움말 읽기

스크립트는 TensorFlow와 함께 설치해야 합니다. 기본 도움말은 다음과 같습니다.

tf_upgrade_v2 -h
2022-12-14 20:30:32.304651: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:32.304742: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:32.304752: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
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 코드 예

간단한 TensorFlow 1.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.x가 설치되어 있으면 다음과 같이 실행되지 않습니다.

(cd models/samples/cookbook/regression && python custom_regression.py)
2022-12-14 20:30:34.855852: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:34.855938: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:34.855948: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
Traceback (most recent call last):
  File "/tmpfs/src/temp/site/ko/guide/migrate/models/samples/cookbook/regression/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
2022-12-14 20:30:37.257961: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:37.258060: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:37.258071: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
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'

코드에 대한 수정 사항을 찾을 수 없으면 스크립트가 오류를 인쇄합니다.

디렉터리 트리

이 간단한 예제를 포함하여 일반적인 프로젝트는 둘 이상의 파일을 사용합니다. 일반적으로 전체 패키지를 업그레이드하여 디렉터리 트리에서 스크립트를 실행할 수도 있습니다.

# update 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
2022-12-14 20:30:39.698606: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:39.698693: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:39.698709: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
INFO line 40:7: Renamed 'tf.test.mock' to 'tf.compat.v1.test.mock'
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'
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 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 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'
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'
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 함수에 대한 하나의 경고에 유의하세요.

이제 스크립트는 TensorFlow 2.x에서 작동합니다.

tf.compat.v1 모듈은 TF 1.15에 포함되어 있기 때문에 변환된 스크립트는 TensorFlow 1.15에서도 실행됩니다.

(cd regression_v2 && python custom_regression.py 2>&1) | tail
I1214 20:30:51.466304 140359346018112 estimator.py:2083] Saving dict for global step 1000: global_step = 1000, loss = 382.97424, rmse = 2.824647
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 1000: /tmpfs/tmp/tmpbkfom1zv/model.ckpt-1000
I1214 20:30:51.506979 140359346018112 estimator.py:2143] Saving 'checkpoint_path' summary for global step 1000: /tmpfs/tmp/tmpbkfom1zv/model.ckpt-1000
Tensor("IteratorGetNext:25", shape=(None,), dtype=float64, device=/device:CPU:0)
Tensor("Squeeze:0", shape=(None,), dtype=float32)

********************************************************************************

RMS error for the test set: $2825

상세 보고서

이 스크립트는 자세한 변경 사항의 목록도 보고합니다. 이 예제에서는 안전하지 않은 변환 중 하나를 발견했으며 파일 맨 위에 경고가 포함되어 있습니다.

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/regression_test.py'
 outputting to 'regression_v2/regression_test.py'

Dataset.make_one_shot_iterator function에 대한 경고 하나에 다시 한 번 유의하세요.

다른 경우에는 출력에서 사소하지 않은 변경 사항에 대해 설명합니다.

%%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
2022-12-14 20:30:53.792273: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:53.792383: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:53.792395: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
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), rate=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
2022-12-14 20:30:56.457810: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:56.457899: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:30:56.457915: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.

출력 파일을 생성했습니다.

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

오류가 발생했습니다. 이 보고서는 실행하기 전에 수정해야 할 사항을 정확히 알려줍니다. 처음 세 가지 오류는 다음과 같습니다.

cat deeplab_report.txt | grep -i models/research/deeplab | grep -i error | head -n 3
models/research/deeplab/train.py:29: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/model.py:60: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/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.

"안전" 모드

변환 스크립트에는 가져오기를 변경하여 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
2022-12-14 20:31:00.736200: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:31:00.736293: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2022-12-14 20:31:00.736304: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
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)

보시다시피 이것은 코드를 업그레이드하지 않지만 TensorFlow 1 코드가 TensorFlow 2 바이너리에 대해 실행되도록 허용합니다. 이것은 코드가 지원되는 TF 2.x 동작을 실행하고 있음을 의미하지 않습니다!

경고 사항

  • 이 스크립트를 실행하기 전에 코드의 일부를 수동으로 업데이트하면 안 됩니다. 특히 tf.math.argmax 또는 tf.batch_to_space와 같은 인수를 재정렬한 함수로 인해 스크립트가 기존 코드를 잘못 매핑하는 키워드 인수를 잘못 추가하게 됩니다.

  • 스크립트는 import tensorflow as tf 또는 import tensorflow.compat.v1 as tf를 사용하여 tensorflow를 가져온다고 가정합니다.

  • 이 스크립트는 인수의 순서를 바꾸지 않습니다. 대신, 스크립트는 인수가 재정렬된 함수에 키워드 인수를 추가합니다.

  • GitHub 저장소에서 Jupyter 메모장 및 Python 파일을 업그레이드하는 편리한 도구는 tf2up.ml을 확인하세요.

업그레이드 스크립트 버그를 보고하거나 기능을 요청하려면 GitHub에서 이슈를 제출하세요.