![]() |
![]() |
![]() |
![]() |
![]() |
概要
TensorFlow Lite では、TensorFlow グラフ定義から TensorFlow Lite フラットバッファ形式へのモデル変換の一部として、重みを 8 ビット精度に変換できるようになりました。ダイナミックレンジ量子化は、モデルサイズを 4 分の 1 に削減します。さらに、TFLite は、アクティベーションのオンザフライの量子化および逆量子化をサポートし、以下を可能にします。
- 可能な場合、より高速な実装のために量子化されたカーネルを使用する。
- グラフの異なる部分に浮動小数点カーネルと量子化カーネルを使用する。
アクティベーションは常に浮動小数点で保存されます。量子化カーネルをサポートする演算の場合、アクティベーションは処理の前に動的に 8 ビットの精度に量子化され、処理後に浮動小数点精度に逆量子化されます。変換されるモデルによって異なりますが、純粋な浮動小数点の計算より高速になる可能性があります。
量子化認識トレーニングとは対照的に、この方法では、重みはトレーニング後に量子化され、アクティベーションは推論時に動的に量子化されます。したがって、モデルの重みは再量子化されず、量子化による誤差が補正されません。量子化モデルの精度をチェックして、精度低下が許容範囲内であることを確認することが重要です。
このチュートリアルでは、MNIST モデルを新規にトレーニングし、TensorFlow でその精度を確認してから、モデルをダイナミックレンジ量子化を使用した Tensorflow Lite フラットバッファに変換します。最後に、変換されたモデルの精度を確認し、元の float モデルと比較します。
MNIST モデルの構築
セットアップ
import logging
logging.getLogger("tensorflow").setLevel(logging.DEBUG)
import tensorflow as tf
from tensorflow import keras
import numpy as np
import pathlib
2022-08-04 20:18:33.593283: E tensorflow/stream_executor/cuda/cuda_blas.cc:2981] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered 2022-08-04 20:18:34.394980: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvrtc.so.11.1: cannot open shared object file: No such file or directory 2022-08-04 20:18:34.395264: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvrtc.so.11.1: cannot open shared object file: No such file or directory 2022-08-04 20:18:34.395278: 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.
TensorFlow モデルのトレーニング
# Load MNIST dataset
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize the input image so that each pixel value is between 0 to 1.
train_images = train_images / 255.0
test_images = test_images / 255.0
# Define the model architecture
model = keras.Sequential([
keras.layers.InputLayer(input_shape=(28, 28)),
keras.layers.Reshape(target_shape=(28, 28, 1)),
keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation=tf.nn.relu),
keras.layers.MaxPooling2D(pool_size=(2, 2)),
keras.layers.Flatten(),
keras.layers.Dense(10)
])
# Train the digit classification model
model.compile(optimizer='adam',
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(
train_images,
train_labels,
epochs=1,
validation_data=(test_images, test_labels)
)
1875/1875 [==============================] - 7s 3ms/step - loss: 0.2676 - accuracy: 0.9262 - val_loss: 0.1242 - val_accuracy: 0.9627 <keras.callbacks.History at 0x7fa67c5f95e0>
この例では、モデルを 1 エポックでトレーニングしたので、トレーニングの精度は 96% 以下になります。
TensorFlow Lite モデルに変換する
Python TFLiteConverter を使用して、トレーニング済みモデルを TensorFlow Lite モデルに変換できるようになりました。
次に、TFLiteConverter
を使用してモデルを読み込みます。
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
WARNING:absl:Found untraced functions such as _jit_compiled_convolution_op while saving (showing 1 of 1). These functions will not be directly callable after loading. INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp9b571u0c/assets INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp9b571u0c/assets 2022-08-04 20:18:47.473469: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:362] Ignored output_format. 2022-08-04 20:18:47.473513: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:365] Ignored drop_control_dependency.
tflite ファイルに書き込みます。
tflite_models_dir = pathlib.Path("/tmp/mnist_tflite_models/")
tflite_models_dir.mkdir(exist_ok=True, parents=True)
tflite_model_file = tflite_models_dir/"mnist_model.tflite"
tflite_model_file.write_bytes(tflite_model)
84824
エクスポート時にモデルを量子化するには、optimizations
フラグを設定してサイズを最適化します。
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_quant_model = converter.convert()
tflite_model_quant_file = tflite_models_dir/"mnist_model_quant.tflite"
tflite_model_quant_file.write_bytes(tflite_quant_model)
WARNING:absl:Found untraced functions such as _jit_compiled_convolution_op while saving (showing 1 of 1). These functions will not be directly callable after loading. INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpcu1wkllb/assets INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpcu1wkllb/assets 2022-08-04 20:18:48.621375: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:362] Ignored output_format. 2022-08-04 20:18:48.621418: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:365] Ignored drop_control_dependency. 24072
生成されるファイルのサイズが約1/4
であることに注意してください。
ls -lh {tflite_models_dir}
total 152K -rw-rw-r-- 1 kbuilder kbuilder 83K Aug 4 20:18 mnist_model.tflite -rw-rw-r-- 1 kbuilder kbuilder 24K Aug 4 20:18 mnist_model_quant.tflite -rw-rw-r-- 1 kbuilder kbuilder 44K Aug 4 20:16 mnist_model_quant_f16.tflite
TFLite モデルを実行する
Python TensorFlow Lite インタープリタを使用して TensorFlow Lite モデルを実行します。
モデルをインタープリタに読み込む
interpreter = tf.lite.Interpreter(model_path=str(tflite_model_file))
interpreter.allocate_tensors()
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
interpreter_quant = tf.lite.Interpreter(model_path=str(tflite_model_quant_file))
interpreter_quant.allocate_tensors()
1 つの画像でモデルをテストする
test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32)
input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]
interpreter.set_tensor(input_index, test_image)
interpreter.invoke()
predictions = interpreter.get_tensor(output_index)
import matplotlib.pylab as plt
plt.imshow(test_images[0])
template = "True:{true}, predicted:{predict}"
_ = plt.title(template.format(true= str(test_labels[0]),
predict=str(np.argmax(predictions[0]))))
plt.grid(False)
モデルを評価する
# A helper function to evaluate the TF Lite model using "test" dataset.
def evaluate_model(interpreter):
input_index = interpreter.get_input_details()[0]["index"]
output_index = interpreter.get_output_details()[0]["index"]
# Run predictions on every image in the "test" dataset.
prediction_digits = []
for test_image in test_images:
# Pre-processing: add batch dimension and convert to float32 to match with
# the model's input data format.
test_image = np.expand_dims(test_image, axis=0).astype(np.float32)
interpreter.set_tensor(input_index, test_image)
# Run inference.
interpreter.invoke()
# Post-processing: remove batch dimension and find the digit with highest
# probability.
output = interpreter.tensor(output_index)
digit = np.argmax(output()[0])
prediction_digits.append(digit)
# Compare prediction results with ground truth labels to calculate accuracy.
accurate_count = 0
for index in range(len(prediction_digits)):
if prediction_digits[index] == test_labels[index]:
accurate_count += 1
accuracy = accurate_count * 1.0 / len(prediction_digits)
return accuracy
print(evaluate_model(interpreter))
0.9627
ダイナミックレンジ量子化モデルの評価を繰り返して、以下を取得する
print(evaluate_model(interpreter_quant))
0.9624
この例では、圧縮されたモデルの精度は同じです。
既存のモデルの最適化
事前アクティべーレイヤーを備えた Resnet (Resnet-v2) は、ビジョンアプリケーションで広く使用されています。resnet-v2-101 の事前トレーニング済み凍結グラフは、Tensorflow Hub で入手できます。
次の方法で、量子化された凍結グラフを TensorFLow Lite フラットバッファに変換できます。
import tensorflow_hub as hub
resnet_v2_101 = tf.keras.Sequential([
keras.layers.InputLayer(input_shape=(224, 224, 3)),
hub.KerasLayer("https://tfhub.dev/google/imagenet/resnet_v2_101/classification/4")
])
converter = tf.lite.TFLiteConverter.from_keras_model(resnet_v2_101)
WARNING:tensorflow:Please fix your imports. Module tensorflow.python.training.tracking.data_structures has been moved to tensorflow.python.trackable.data_structures. The old module will be deleted in version 2.11. WARNING:tensorflow:Please fix your imports. Module tensorflow.python.training.tracking.data_structures has been moved to tensorflow.python.trackable.data_structures. The old module will be deleted in version 2.11.
# Convert to TF Lite without quantization
resnet_tflite_file = tflite_models_dir/"resnet_v2_101.tflite"
resnet_tflite_file.write_bytes(converter.convert())
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpwx1sjn2j/assets INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpwx1sjn2j/assets 2022-08-04 20:19:22.654549: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:362] Ignored output_format. 2022-08-04 20:19:22.654604: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:365] Ignored drop_control_dependency. 178422332
# Convert to TF Lite with quantization
converter.optimizations = [tf.lite.Optimize.DEFAULT]
resnet_quantized_tflite_file = tflite_models_dir/"resnet_v2_101_quantized.tflite"
resnet_quantized_tflite_file.write_bytes(converter.convert())
INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpw03lze8q/assets INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpw03lze8q/assets 2022-08-04 20:19:52.380063: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:362] Ignored output_format. 2022-08-04 20:19:52.380119: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:365] Ignored drop_control_dependency. 45733976
ls -lh {tflite_models_dir}/*.tflite
-rw-rw-r-- 1 kbuilder kbuilder 83K Aug 4 20:18 /tmp/mnist_tflite_models/mnist_model.tflite -rw-rw-r-- 1 kbuilder kbuilder 24K Aug 4 20:18 /tmp/mnist_tflite_models/mnist_model_quant.tflite -rw-rw-r-- 1 kbuilder kbuilder 44K Aug 4 20:16 /tmp/mnist_tflite_models/mnist_model_quant_f16.tflite -rw-rw-r-- 1 kbuilder kbuilder 171M Aug 4 20:19 /tmp/mnist_tflite_models/resnet_v2_101.tflite -rw-rw-r-- 1 kbuilder kbuilder 44M Aug 4 20:20 /tmp/mnist_tflite_models/resnet_v2_101_quantized.tflite
モデルサイズが 171 MB から 43 MB に削減されます。imagenet でのこのモデルの精度は、TFLite 精度測定用に提供されているスクリプトを使用して評価できます。
最適化されたモデルの top-1 精度は、浮動小数点のモデルと同じく 76.8 です。