トレーニング後のダイナミックレンジ量子化

TensorFlow.org で表示 Google Colab で実行 GitHub でソースを表示 ノートブックをダウンロード TF Hub モデルを参照

概要

TensorFlow Lite では、TensorFlow グラフ定義から TensorFlow Lite フラットバッファ形式へのモデル変換の一部として、重みを 8 ビット精度に変換できるようになりました。ダイナミックレンジ量子化は、モデルサイズを 4 分の 1 に削減します。さらに、TFLite は、アクティベーションのオンザフライの量子化および逆量子化をサポートし、以下を可能にします。

  1. 可能な場合、より高速な実装のために量子化されたカーネルを使用する。
  2. グラフの異なる部分に浮動小数点カーネルと量子化カーネルを使用する。

アクティベーションは常に浮動小数点で保存されます。量子化カーネルをサポートする演算の場合、アクティベーションは処理の前に動的に 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

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)
)

この例では、モデルを 1 エポックでトレーニングしたので、トレーニングの精度は 96% 以下になります。

TensorFlow Lite モデルに変換する

TensorFlow Lite Converter を使用して、トレーニング済みモデルを TensorFlow Lite モデルに変換できるようになりました。

次に、TFLiteConverterを使用してモデルを読み込みます。

converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

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)

エクスポート時にモデルを量子化するには、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)

生成されるファイルのサイズが約1/4であることに注意してください。

ls -lh {tflite_models_dir}

TFLite モデルを実行する

Python TensorFlow Lite インタープリタを使用して TensorFlow Lite モデルを実行します。

モデルをインタープリタに読み込む

interpreter = tf.lite.Interpreter(model_path=str(tflite_model_file))
interpreter.allocate_tensors()
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))

ダイナミックレンジ量子化モデルの評価を繰り返して、以下を取得する

print(evaluate_model(interpreter_quant))

この例では、圧縮されたモデルの精度は同じです。

既存のモデルの最適化

事前アクティべーレイヤーを備えた 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)
# Convert to TF Lite without quantization
resnet_tflite_file = tflite_models_dir/"resnet_v2_101.tflite"
resnet_tflite_file.write_bytes(converter.convert())
# 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())
ls -lh {tflite_models_dir}/*.tflite

モデルサイズが 171 MB から 43 MB に削減されます。imagenet でのこのモデルの精度は、TFLite 精度測定用に提供されているスクリプトを使用して評価できます。

最適化されたモデルの top-1 精度は、浮動小数点のモデルと同じく 76.8 です。