{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "c8Cx-rUMVX25" }, "source": [ "##### Copyright 2019 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "I9sUhVL_VZNO" }, "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": "6Y8E0lw5eYWm" }, "source": [ "# トレーニング後の float16 量子化" ] }, { "cell_type": "markdown", "metadata": { "id": "CGuqeuPSVNo-" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
TensorFlow.org で実行Google Colab を実行GitHubでソースを表示ノートブックをダウンロード
" ] }, { "cell_type": "markdown", "metadata": { "id": "BTC1rDAuei_1" }, "source": [ "## 概要\n", "\n", "[TensorFlow Lite](https://www.tensorflow.org/lite/) は、TensorFlow から TensorFlow Lite のフラットバッファ形式へのモデル変換時に、重みを 16 ビット浮動小数点値に変換することをサポートするようになりました。これにより、モデルサイズが 2 分の 1 になります。GPU などの一部のハードウェアは、この精度の低い演算でネイティブに計算でき、従来の浮動小数点よりも高速に実行できます。Tensorflow Lite GPU デリゲートは、このように実行するように構成できます。ただし、重みを float16 に変換したモデルは、追加の変更を加えなくても CPU で実行できます。float16 の重みは、最初の推論の前に float32 にアップサンプリングされます。これにより、レイテンシと精度への影響を最小限に抑え、モデルサイズを大幅に縮小できます。\n", "\n", "このチュートリアルでは、MNIST モデルを新規にトレーニングし、TensorFlow でその精度を確認してから、モデルを float16 量子化を使用した Tensorflow Lite フラットバッファに変換します。最後に、変換されたモデルの精度を確認し、元の float32 モデルと比較します。" ] }, { "cell_type": "markdown", "metadata": { "id": "2XsEP17Zelz9" }, "source": [ "## MNIST モデルの構築" ] }, { "cell_type": "markdown", "metadata": { "id": "dDqqUIZjZjac" }, "source": [ "### セットアップ" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gyqAw1M9lyab" }, "outputs": [], "source": [ "import logging\n", "logging.getLogger(\"tensorflow\").setLevel(logging.DEBUG)\n", "\n", "import tensorflow as tf\n", "from tensorflow import keras\n", "import numpy as np\n", "import pathlib" ] }, { "cell_type": "markdown", "metadata": { "id": "eQ6Q0qqKZogR" }, "source": [ "### モデルをトレーニングしてエクスポートする" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hWSAjQWagIHl" }, "outputs": [], "source": [ "# Load MNIST dataset\n", "mnist = keras.datasets.mnist\n", "(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n", "\n", "# Normalize the input image so that each pixel value is between 0 to 1.\n", "train_images = train_images / 255.0\n", "test_images = test_images / 255.0\n", "\n", "# Define the model architecture\n", "model = keras.Sequential([\n", " keras.layers.InputLayer(input_shape=(28, 28)),\n", " keras.layers.Reshape(target_shape=(28, 28, 1)),\n", " keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation=tf.nn.relu),\n", " keras.layers.MaxPooling2D(pool_size=(2, 2)),\n", " keras.layers.Flatten(),\n", " keras.layers.Dense(10)\n", "])\n", "\n", "# Train the digit classification model\n", "model.compile(optimizer='adam',\n", " loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", " metrics=['accuracy'])\n", "model.fit(\n", " train_images,\n", " train_labels,\n", " epochs=1,\n", " validation_data=(test_images, test_labels)\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "5NMaNZQCkW9X" }, "source": [ "この例では、モデルを 1 エポックでトレーニングしたので、トレーニングの精度は 96% 以下になります。" ] }, { "cell_type": "markdown", "metadata": { "id": "xl8_fzVAZwOh" }, "source": [ "### TensorFlow Lite モデルに変換する\n", "\n", "TensorFlow Lite [Converter](https://www.tensorflow.org/lite/models/convert) を使用して、トレーニング済みモデルを TensorFlow Lite モデルに変換できるようになりました。\n", "\n", "`TFLiteConverter`を使用してモデルを読み込みます。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_i8B2nDZmAgQ" }, "outputs": [], "source": [ "converter = tf.lite.TFLiteConverter.from_keras_model(model)\n", "tflite_model = converter.convert()" ] }, { "cell_type": "markdown", "metadata": { "id": "F2o2ZfF0aiCx" }, "source": [ "`.tflite`ファイルに書き込みます。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vptWZq2xnclo" }, "outputs": [], "source": [ "tflite_models_dir = pathlib.Path(\"/tmp/mnist_tflite_models/\")\n", "tflite_models_dir.mkdir(exist_ok=True, parents=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Ie9pQaQrn5ue" }, "outputs": [], "source": [ "tflite_model_file = tflite_models_dir/\"mnist_model.tflite\"\n", "tflite_model_file.write_bytes(tflite_model)" ] }, { "cell_type": "markdown", "metadata": { "id": "7BONhYtYocQY" }, "source": [ "エクスポート時にモデルを float16 に量子化するには、最初に`optimizations`フラグを設定してデフォルトの最適化を使用します。次に、float16 がターゲットプラットフォームでサポートされている型であることを指定します。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "HEZ6ET1AHAS3" }, "outputs": [], "source": [ "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n", "converter.target_spec.supported_types = [tf.float16]" ] }, { "cell_type": "markdown", "metadata": { "id": "xW84iMYjHd9t" }, "source": [ "最後に、通常どおりにモデルを変換します。デフォルトでは、変換されたモデルは呼び出しの便宜上、浮動小数点の入力と出力を引き続き使用します。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "yuNfl3CoHNK3" }, "outputs": [], "source": [ "tflite_fp16_model = converter.convert()\n", "tflite_model_fp16_file = tflite_models_dir/\"mnist_model_quant_f16.tflite\"\n", "tflite_model_fp16_file.write_bytes(tflite_fp16_model)" ] }, { "cell_type": "markdown", "metadata": { "id": "PhMmUTl4sbkz" }, "source": [ "生成されるファイルのサイズが約`1/2`であることに注意してください。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "JExfcfLDscu4" }, "outputs": [], "source": [ "!ls -lh {tflite_models_dir}" ] }, { "cell_type": "markdown", "metadata": { "id": "L8lQHMp_asCq" }, "source": [ "## TensorFlow Lite モデルを実行する" ] }, { "cell_type": "markdown", "metadata": { "id": "-5l6-ciItvX6" }, "source": [ "Python TensorFlow Lite インタープリタを使用して TensorFlow Lite モデルを実行します。" ] }, { "cell_type": "markdown", "metadata": { "id": "Ap_jE7QRvhPf" }, "source": [ "### モデルをインタープリタに読み込む" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Jn16Rc23zTss" }, "outputs": [], "source": [ "interpreter = tf.lite.Interpreter(model_path=str(tflite_model_file))\n", "interpreter.allocate_tensors()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "J8Pztk1mvNVL" }, "outputs": [], "source": [ "interpreter_fp16 = tf.lite.Interpreter(model_path=str(tflite_model_fp16_file))\n", "interpreter_fp16.allocate_tensors()" ] }, { "cell_type": "markdown", "metadata": { "id": "2opUt_JTdyEu" }, "source": [ "### 1 つの画像でモデルをテストする" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "AKslvo2kwWac" }, "outputs": [], "source": [ "test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32)\n", "\n", "input_index = interpreter.get_input_details()[0][\"index\"]\n", "output_index = interpreter.get_output_details()[0][\"index\"]\n", "\n", "interpreter.set_tensor(input_index, test_image)\n", "interpreter.invoke()\n", "predictions = interpreter.get_tensor(output_index)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XZClM2vo3_bm" }, "outputs": [], "source": [ "import matplotlib.pylab as plt\n", "\n", "plt.imshow(test_images[0])\n", "template = \"True:{true}, predicted:{predict}\"\n", "_ = plt.title(template.format(true= str(test_labels[0]),\n", " predict=str(np.argmax(predictions[0]))))\n", "plt.grid(False)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3gwhv4lKbYZ4" }, "outputs": [], "source": [ "test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32)\n", "\n", "input_index = interpreter_fp16.get_input_details()[0][\"index\"]\n", "output_index = interpreter_fp16.get_output_details()[0][\"index\"]\n", "\n", "interpreter_fp16.set_tensor(input_index, test_image)\n", "interpreter_fp16.invoke()\n", "predictions = interpreter_fp16.get_tensor(output_index)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "CIH7G_MwbY2x" }, "outputs": [], "source": [ "plt.imshow(test_images[0])\n", "template = \"True:{true}, predicted:{predict}\"\n", "_ = plt.title(template.format(true= str(test_labels[0]),\n", " predict=str(np.argmax(predictions[0]))))\n", "plt.grid(False)" ] }, { "cell_type": "markdown", "metadata": { "id": "LwN7uIdCd8Gw" }, "source": [ "### モデルを評価する" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "05aeAuWjvjPx" }, "outputs": [], "source": [ "# A helper function to evaluate the TF Lite model using \"test\" dataset.\n", "def evaluate_model(interpreter):\n", " input_index = interpreter.get_input_details()[0][\"index\"]\n", " output_index = interpreter.get_output_details()[0][\"index\"]\n", "\n", " # Run predictions on every image in the \"test\" dataset.\n", " prediction_digits = []\n", " for test_image in test_images:\n", " # Pre-processing: add batch dimension and convert to float32 to match with\n", " # the model's input data format.\n", " test_image = np.expand_dims(test_image, axis=0).astype(np.float32)\n", " interpreter.set_tensor(input_index, test_image)\n", "\n", " # Run inference.\n", " interpreter.invoke()\n", "\n", " # Post-processing: remove batch dimension and find the digit with highest\n", " # probability.\n", " output = interpreter.tensor(output_index)\n", " digit = np.argmax(output()[0])\n", " prediction_digits.append(digit)\n", "\n", " # Compare prediction results with ground truth labels to calculate accuracy.\n", " accurate_count = 0\n", " for index in range(len(prediction_digits)):\n", " if prediction_digits[index] == test_labels[index]:\n", " accurate_count += 1\n", " accuracy = accurate_count * 1.0 / len(prediction_digits)\n", "\n", " return accuracy" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "T5mWkSbMcU5z" }, "outputs": [], "source": [ "print(evaluate_model(interpreter))" ] }, { "cell_type": "markdown", "metadata": { "id": "Km3cY9ry8ZlG" }, "source": [ "Float16 量子化モデルの評価を繰り返して以下を取得する" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "-9cnwiPp6EGm" }, "outputs": [], "source": [ "# NOTE: Colab runs on server CPUs. At the time of writing this, TensorFlow Lite\n", "# doesn't have super optimized server CPU kernels. For this reason this may be\n", "# slower than the above float interpreter. But for mobile CPUs, considerable\n", "# speedup can be observed.\n", "print(evaluate_model(interpreter_fp16))" ] }, { "cell_type": "markdown", "metadata": { "id": "L7lfxkor8pgv" }, "source": [ "この例では、モデルの精度を低下させることなく float16 に量子化しました。\n", "\n", "また、GPU で float16 量子化モデルを評価することもできます。低下された精度ですべての演算を実行するには、次のように、アプリに`TfLiteGPUDelegateOptions`構造体を作成し、`precision_loss_allowed`を`1`に設定します。\n", "\n", "```\n", "//Prepare GPU delegate.\n", "const TfLiteGpuDelegateOptions options = {\n", " .metadata = NULL,\n", " .compile_options = {\n", " .precision_loss_allowed = 1, // FP16\n", " .preferred_gl_object_type = TFLITE_GL_OBJECT_TYPE_FASTEST,\n", " .dynamic_batch_enabled = 0, // Not fully functional yet\n", " },\n", "};\n", "```\n", "\n", "TFLite GPU デリゲートの詳細なドキュメントとアプリでの使用方法については、[こちら](https://www.tensorflow.org/lite/performance/gpu_advanced?source=post_page---------------------------)をご覧ください" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "post_training_float16_quant.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }