訓練後動態範圍量化

在 TensorFlow.org 上檢視 在 Google Colab 中執行 在 GitHub 上檢視原始碼 下載筆記本 查看 TF Hub 模型

總覽

TensorFlow Lite 現在支援將權重轉換為 8 位元精確度,作為將 tensorflow graphdef 模型轉換為 TensorFlow Lite 的平面緩衝區格式的一部分。動態範圍量化可將模型大小縮減 4 倍。此外,TFLite 支援啟動的即時量化和反量化,以便

  1. 在可用的情況下,使用量化核心以加快實作速度。
  2. 將浮點核心與量化核心混合,以用於圖表的不同部分。

啟動一律以浮點格式儲存。對於支援量化核心的運算,啟動會在處理前動態量化為 8 位元精確度,並在處理後反量化為浮點精確度。視轉換的模型而定,這樣做可提升速度,勝過單純的浮點運算。

量化感知訓練相反,權重會在訓練後量化,而啟動會在此方法中於推論時動態量化。因此,模型權重不會重新訓練,以補償量化造成的誤差。務必檢查量化模型的準確度,確保效能降低程度可接受。

本教學課程從頭開始訓練 MNIST 模型、在 TensorFlow 中檢查其準確度,然後使用動態範圍量化將模型轉換為 Tensorflow Lite 平面緩衝區。最後,本教學課程會檢查轉換模型的準確度,並將其與原始浮點模型進行比較。

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

在本範例中,由於您只將模型訓練一個週期,因此只訓練到約 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 Interpreter 執行 TensorFlow Lite 模型。

將模型載入至 Interpreter

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

在單一圖片上測試模型

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。可以使用為TFLite 準確度評估提供的指令碼來評估此模型在 imagenet 上的準確度。

最佳化模型的 top-1 準確度為 76.8,與浮點模型相同。