{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "FYLyuStTYesc" }, "source": [ "##### Copyright 2020 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "cellView": "form", "execution": { "iopub.execute_input": "2022-12-14T20:49:47.596284Z", "iopub.status.busy": "2022-12-14T20:49:47.595693Z", "iopub.status.idle": "2022-12-14T20:49:47.599400Z", "shell.execute_reply": "2022-12-14T20:49:47.598875Z" }, "id": "PVm-iEoxYesf" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "3MPf91rVYesq" }, "source": [ "# Grappler による TensorFlow グラフ最適化" ] }, { "cell_type": "markdown", "metadata": { "id": "zmNCsZlgYesr" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
TensorFlow.org で表示Google Colab で実行GitHub でソースを表示 ノートブックをダウンロード
" ] }, { "cell_type": "markdown", "metadata": { "id": "l0qacLgyYess" }, "source": [ "## 概要\n", "\n", "TensorFlow は、グラフ実行と Eager Execution の両方を使用して計算を実行します。`tf.Graph`には、計算の単位を表す`tf.Operation`オブジェクト(演算)と、演算間を流れるデータの単位を表す`tf.Tensor`オブジェクトのセットが含まれています。\n", "\n", "Grappler は、TensorFlow ランタイム内のデフォルトのグラフ最適化システムです。Grappler は、グラフモード(`tf.function`内)で最適化を適用して、グラフの簡略化や、プロシージャ間の最適化を可能にする関数本体のインライン化などその他の高レベルの最適化により、TensorFlow 計算のパフォーマンスを向上させます。`tf.Graph`を最適化すると、グラフノードの計算リソースへのマッピングを最適化することによってデバイスのピークメモリ使用量が削減され、ハードウェアの使用率が向上します。\n", "\n", "`tf.Graph`の最適化をより細かく制御するには、`tf.config.optimizer.set_experimental_options()`を使用します。\n" ] }, { "cell_type": "markdown", "metadata": { "id": "A-zkJgR5Yesw" }, "source": [ "## 使用可能なグラフオプティマイザ\n", "\n", "Grappler は`MetaOptimizer`と呼ばれるトップレベルのドライバを通してグラフの最適化を実行します。TensorFlowでは、次のグラフオプティマイザの使用が可能です。\n", "\n", "- *定数折り畳みオプティマイザ -* 可能な場合にグラフの定数ノードを折り畳むことによりテンソルの値を静的に推測し、定数を使用して結果をマテリアライズします。\n", "- *算術オプティマイザ -* 一般的な副次式を消去し、算術ステートメントを簡略化することにより、算術演算を簡略化します。\n", "- *レイアウトオプティマイザ -* テンソルのレイアウトを最適化することにより、畳み込みなどのデータフォーマットに依存する演算をより効率的に実行します。\n", "- *リマッパーオプティマイザ -* 一般的に発生するサブグラフを最適化された結合モノリシックカーネルに置き換えることによって、サブグラフをより効率的な実装に再マップします。\n", "- *メモリオプティマイザ -* グラフを分析して各演算のピークメモリ使用量を確認し、CPU-GPU メモリコピー演算を挿入してGPUメモリをCPUのメモリにスワップすることにより、ピークメモリ使用量を減らします。\n", "- *依存オプティマイザ -* 制御の依存関係を削除または並べ替えすることにより、モデルステップのクリティカルパスを短縮、または他の最適化を有効化します。 Identity などの実質的な NoOp ノードも削除します。\n", "- *プルーニングオプティマイザ -* グラフからの出力に影響を与えないノードを削除します。通常はこれを最初に実行することにより、グラフのサイズを縮小化し、他の Grappler パスの処理を高速化します。\n", "- *関数オプティマイザ -* TensorFlow プログラムの関数ライブラリを最適化し、関数本体をインライン展開することにより、他のプロシージャ間最適化を可能にします。\n", "- *形状オプティマイザ -* 形状および形状関連の情報に関する演算のサブグラフを最適化します。\n", "- *自動並列オプティマイザ -* バッチの次元に沿って分割することにより、グラフを自動的に並列化します。このオプティマイザはデフォルトではオフです。\n", "- *ループオプティマイザ -* ループ内からループ不変のサブグラフを引き上げ、冗長なスタック演算をループ外に移動させることにより、グラフ制御フローを最適化します。また、静的に既知のトリップカウントを使用してループを最適化することにより、静的に既知の条件付き分岐のデッドブランチを削除します。\n", "- *スコープアロケーターオプティマイザ -* スコープアロケーターを導入することにより、データの移動を削減し、一部の演算を統合します。\n", "- *ホスト固定オプティマイザ -* 小さな演算を CPU にスワップします。このオプティマイザはデフォルトではオフです。\n", "- *自動混合精度オプティマイザ -* パフォーマンスを向上させるために、適用可能な場合にデータ型を float16 に変換します。現在、GPU にのみ適用されます。\n", "- *デバッグストリッパー -* グラフから `tf.debugging.Assert`、 `tf.debugging.check_numerics`、`tf.print`などのデバッグ演算関連のノードをストリップします。このオプティマイザはデフォルトではオフです。" ] }, { "cell_type": "markdown", "metadata": { "id": "WZAUsxyWYess" }, "source": [ "## セットアップ\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T20:49:47.603161Z", "iopub.status.busy": "2022-12-14T20:49:47.602615Z", "iopub.status.idle": "2022-12-14T20:49:49.503901Z", "shell.execute_reply": "2022-12-14T20:49:49.502991Z" }, "id": "6BRIDzO6ypoY" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2022-12-14 20:49:48.539011: 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\n", "2022-12-14 20:49:48.539107: 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\n", "2022-12-14 20:49:48.539117: 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.\n" ] } ], "source": [ "import numpy as np\n", "import timeit\n", "import traceback\n", "import contextlib\n", "\n", "\n", "import tensorflow as tf" ] }, { "cell_type": "markdown", "metadata": { "id": "1O-XL1nxJX0X" }, "source": [ "オプティマイザの状態を簡単に切り替えるためのコンテキストマネージャを作成します。" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T20:49:49.508158Z", "iopub.status.busy": "2022-12-14T20:49:49.507779Z", "iopub.status.idle": "2022-12-14T20:49:49.512070Z", "shell.execute_reply": "2022-12-14T20:49:49.511446Z" }, "id": "uRuhVoAlYesz" }, "outputs": [], "source": [ "@contextlib.contextmanager\n", "def options(options):\n", " old_opts = tf.config.optimizer.get_experimental_options()\n", " tf.config.optimizer.set_experimental_options(options)\n", " try:\n", " yield\n", " finally:\n", " tf.config.optimizer.set_experimental_options(old_opts)" ] }, { "cell_type": "markdown", "metadata": { "id": "E2o4kZtK0DoA" }, "source": [ "## Grappler 使用の有無による実行パフォーマンスを比較する\n", "\n", "TensorFlow 2 以降は、デフォルトで Eager Execution が実装されています。デフォルトの実行を Graph モードに切り替えるには、デフォルトで `tf.function` を使用します。Grappler はバックグラウンドで自動的に実行し、上記のグラフオプティマイザを適用して実行パフォーマンスを向上させます。\n" ] }, { "cell_type": "markdown", "metadata": { "id": "3sh8RoLJ96IT" }, "source": [ "### 定数折り畳みオプティマイザ\n", "\n", "導入的な例として、定数に対して演算を実行し、出力を返す関数を 1 つ考えます。" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T20:49:49.515598Z", "iopub.status.busy": "2022-12-14T20:49:49.515068Z", "iopub.status.idle": "2022-12-14T20:49:49.518989Z", "shell.execute_reply": "2022-12-14T20:49:49.518270Z" }, "id": "jOW_OSzMJEvN" }, "outputs": [], "source": [ "def test_function_1():\n", " @tf.function\n", " def simple_function(input_arg):\n", " print('Tracing!')\n", " a = tf.constant(np.random.randn(2000,2000), dtype = tf.float32)\n", " c = a\n", " for n in range(50):\n", " c = c@a\n", " return tf.reduce_mean(c+input_arg)\n", "\n", " return simple_function" ] }, { "cell_type": "markdown", "metadata": { "id": "tFVgUhhzLKIo" }, "source": [ "定数折り畳みオプティマイザをオフにして、関数を実行します。" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T20:49:49.522025Z", "iopub.status.busy": "2022-12-14T20:49:49.521773Z", "iopub.status.idle": "2022-12-14T20:50:06.123205Z", "shell.execute_reply": "2022-12-14T20:50:06.122468Z" }, "id": "KDMGsOHrJqKD" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'constant_folding': False, 'disable_model_pruning': False, 'disable_meta_optimizer': False}\n", "Tracing!\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Vanilla execution: 0.0013519179997274478 s\n" ] } ], "source": [ "with options({'constant_folding': False}):\n", " print(tf.config.optimizer.get_experimental_options())\n", " simple_function = test_function_1()\n", " # Trace once\n", " x = tf.constant(2.2)\n", " simple_function(x)\n", " print(\"Vanilla execution:\", timeit.timeit(lambda: simple_function(x), number = 1), \"s\")" ] }, { "cell_type": "markdown", "metadata": { "id": "ykMXfo8qO41z" }, "source": [ "定数折り畳みオプティマイザを有効にして関数を再度実行し、関数実行の高速化を観察します。" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T20:50:06.127073Z", "iopub.status.busy": "2022-12-14T20:50:06.126376Z", "iopub.status.idle": "2022-12-14T20:50:08.354176Z", "shell.execute_reply": "2022-12-14T20:50:08.353389Z" }, "id": "73pc0gfFKY8l" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'constant_folding': True, 'disable_model_pruning': False, 'disable_meta_optimizer': False}\n", "Tracing!\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Constant folded execution: 0.0007739210000181629 s\n" ] } ], "source": [ "with options({'constant_folding': True}):\n", " print(tf.config.optimizer.get_experimental_options())\n", " simple_function = test_function_1()\n", " # Trace once\n", " x = tf.constant(2.2)\n", " simple_function(x)\n", " print(\"Constant folded execution:\", timeit.timeit(lambda: simple_function(x), number = 1), \"s\")" ] }, { "cell_type": "markdown", "metadata": { "id": "83w8rfcRVhWb" }, "source": [ "### デバッグ ストリッパー オプティマイザ\n", "\n", "入力引数の数値をチェックし、それを返す単純な関数を見てみましょう。 " ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T20:50:08.357875Z", "iopub.status.busy": "2022-12-14T20:50:08.357376Z", "iopub.status.idle": "2022-12-14T20:50:08.360969Z", "shell.execute_reply": "2022-12-14T20:50:08.360392Z" }, "id": "j2DvqEr8haut" }, "outputs": [], "source": [ "def test_function_2():\n", " @tf.function\n", " def simple_func(input_arg):\n", " output = input_arg\n", " tf.debugging.check_numerics(output, \"Bad!\")\n", " return output\n", " return simple_func" ] }, { "cell_type": "markdown", "metadata": { "id": "ywKG3WRbpYB8" }, "source": [ "まず最初に、デバッグストリッパーオプティマイザをオフにして関数を実行します。 " ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T20:50:08.364433Z", "iopub.status.busy": "2022-12-14T20:50:08.363915Z", "iopub.status.idle": "2022-12-14T20:50:08.633893Z", "shell.execute_reply": "2022-12-14T20:50:08.633210Z" }, "id": "LsE-y6iQWSwH" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2022-12-14 20:50:08.397437: E tensorflow/core/kernels/check_numerics_op.cc:293] abnormal_detected_host @0x7f8d5a600100 = {0, 1} Bad!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/tmpfs/tmp/ipykernel_74478/3616845043.py\", line 4, in \n", " test_func(p1)\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/python/util/traceback_utils.py\", line 153, in error_handler\n", " raise e.with_traceback(filtered_tb) from None\n", "tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:\n", "\n", "Detected at node 'CheckNumerics' defined at (most recent call last):\n", " File \"/usr/lib/python3.9/runpy.py\", line 197, in _run_module_as_main\n", " return _run_code(code, main_globals, None,\n", " File \"/usr/lib/python3.9/runpy.py\", line 87, in _run_code\n", " exec(code, run_globals)\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/ipykernel_launcher.py\", line 17, in \n", " app.launch_new_instance()\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/traitlets/config/application.py\", line 992, in launch_instance\n", " app.start()\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/ipykernel/kernelapp.py\", line 711, in start\n", " self.io_loop.start()\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tornado/platform/asyncio.py\", line 215, in start\n", " self.asyncio_loop.run_forever()\n", " File \"/usr/lib/python3.9/asyncio/base_events.py\", line 601, in run_forever\n", " self._run_once()\n", " File \"/usr/lib/python3.9/asyncio/base_events.py\", line 1905, in _run_once\n", " handle._run()\n", " File \"/usr/lib/python3.9/asyncio/events.py\", line 80, in _run\n", " self._context.run(self._callback, *self._args)\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/ipykernel/kernelbase.py\", line 510, in dispatch_queue\n", " await self.process_one()\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/ipykernel/kernelbase.py\", line 499, in process_one\n", " await dispatch(*args)\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/ipykernel/kernelbase.py\", line 406, in dispatch_shell\n", " await result\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/ipykernel/kernelbase.py\", line 729, in execute_request\n", " reply_content = await reply_content\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/ipykernel/ipkernel.py\", line 411, in do_execute\n", " res = shell.run_cell(\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/ipykernel/zmqshell.py\", line 531, in run_cell\n", " return super().run_cell(*args, **kwargs)\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/IPython/core/interactiveshell.py\", line 2940, in run_cell\n", " result = self._run_cell(\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/IPython/core/interactiveshell.py\", line 2995, in _run_cell\n", " return runner(coro)\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/IPython/core/async_helpers.py\", line 129, in _pseudo_sync_runner\n", " coro.send(None)\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/IPython/core/interactiveshell.py\", line 3194, in run_cell_async\n", " has_raised = await self.run_ast_nodes(code_ast.body, cell_name,\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/IPython/core/interactiveshell.py\", line 3373, in run_ast_nodes\n", " if await self.run_code(code, result, async_=asy):\n", " File \"/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/IPython/core/interactiveshell.py\", line 3433, in run_code\n", " exec(code_obj, self.user_global_ns, self.user_ns)\n", " File \"/tmpfs/tmp/ipykernel_74478/3616845043.py\", line 4, in \n", " test_func(p1)\n", " File \"/tmpfs/tmp/ipykernel_74478/2241890286.py\", line 5, in simple_func\n", " tf.debugging.check_numerics(output, \"Bad!\")\n", "Node: 'CheckNumerics'\n", "Bad! : Tensor had Inf values\n", "\t [[{{node CheckNumerics}}]] [Op:__inference_simple_func_131]\n" ] } ], "source": [ "test_func = test_function_2()\n", "p1 = tf.constant(float('inf'))\n", "try:\n", " test_func(p1)\n", "except tf.errors.InvalidArgumentError as e:\n", " traceback.print_exc(limit=2)" ] }, { "cell_type": "markdown", "metadata": { "id": "URHpboM8xLN6" }, "source": [ "`test_func`に対する`Inf`引数のため、`tf.debugging.check_numerics`には無効な引数エラーが発生します。" ] }, { "cell_type": "markdown", "metadata": { "id": "CuPSha9YmJRo" }, "source": [ "デバッグストリッパーオプティマイザを有効にして、関数を再度実行します。 " ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2022-12-14T20:50:08.637378Z", "iopub.status.busy": "2022-12-14T20:50:08.636916Z", "iopub.status.idle": "2022-12-14T20:50:08.650567Z", "shell.execute_reply": "2022-12-14T20:50:08.649993Z" }, "id": "UPJ7ygHnWP6B" }, "outputs": [], "source": [ "with options({'debug_stripper': True}):\n", " test_func2 = test_function_2()\n", " p1 = tf.constant(float('inf'))\n", " try:\n", " test_func2(p1)\n", " except tf.errors.InvalidArgumentError as e:\n", " traceback.print_exc(limit=2)" ] }, { "cell_type": "markdown", "metadata": { "id": "nAsESNUB1QpI" }, "source": [ "デバッグストリッパーオプティマイザがグラフから`tf.debug.check_numerics`ノードを取り除き、エラーを発生させることなく関数を実行します。 " ] }, { "cell_type": "markdown", "metadata": { "id": "wHC6tR9GvFgW" }, "source": [ "## まとめ\n", "\n", "TensorFlow ランタイムは Grappler を使用して、実行前にグラフを自動的に最適化します。`tf.config.optimizer.set_experimental_options`を使用すると、様々なグラフオプティマイザを有効または無効にすることができます。\n", "\n", "Grappler に関する詳しい情報は、TensorFlow グラフの最適化をご覧ください。" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "graph_optimization.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.16" } }, "nbformat": 4, "nbformat_minor": 0 }