此页面由 Cloud Translation API 翻译。
Switch to English

培训后的动态范围的量化

查看上TensorFlow.org 在谷歌Colab运行 GitHub上查看源代码 下载笔记本

概观

TensorFlow精简版现在支持转换权重以8位精度从tensorflow graphdefs模型转换到TensorFlow精简版的扁平缓冲格式的一部分。动态范围的量化实现了模型尺寸4倍缩小。此外,TFLite支持上飞量化和激活允许的量化:

  1. 使用量化内核更快的执行时可用。
  2. 浮点内核与用于图形的不同部分进行量化的内核混合。

该激活总是存储在浮点运算。对于OPS这种支持量化内核中,被激活以处理量化为精度8位动态之前和被去量化处理后的float精度。根据该模型被转换,这可以给在纯浮点运算的加速。

与此相反,以量化知道训练中,权重进行量化岗位培训和激活在这个方法的推理动态量化。因此,模型权重不是再培训,以弥补量化引起的误差。检查量化模型的准确性,确保退化是可以接受的是很重要的。

这个教程列车从头MNIST模型,检查其精度在TensorFlow,然后转换模型转换为Tensorflow精简版flatbuffer与动态范围量化。最后,它检查转换的模型的准确度,并比较它原来的浮动模型。

建立一个模型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)
)
 
1875/1875 [==============================] - 10s 5ms/step - loss: 0.2787 - accuracy: 0.9203 - val_loss: 0.1323 - val_accuracy: 0.9624

<tensorflow.python.keras.callbacks.History at 0x7f6443480e80>

对于这个例子,因为你训练只是一个单一的划时代的模型,所以它只火车〜96%的准确率。

转换为TensorFlow精简版模型

使用Python TFLiteConverter ,你可以训练的模型,现在转换成TensorFlow精简版模型。

现在使用加载模型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)
 
84452

为了量化对出口的模式,建立了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)
 
23840

注意生成的文件怎么样,大约1/4的大小。

ls -lh {tflite_models_dir}
total 214M
-rw-rw-r-- 1 colaboratory-playground 50844828  44K Jun 23 06:04 mnist_model_quant_f16.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828  24K Jun 23 06:12 mnist_model_quant.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828  83K Jun 23 06:12 mnist_model.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828  44M Jun 23 06:10 resnet_v2_101_quantized.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828 171M Jun 23 06:09 resnet_v2_101.tflite

运行TFLite模型

运行使用Python TensorFlow精简版解释器TensorFlow精简版机型。

加载模型到一个解释

 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)
 

PNG

评估模型

 # 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.9624

重复的动态范围,量化模型的评估,以获得:

 print(evaluate_model(interpreter_quant))
 
0.9626

在这个例子中,压缩模型的准确性没有区别。

优化现有的模型

具有预激活层(RESNET-V2)Resnets被广泛用于视觉应用。预先训练冷冻图形为RESNET-v2-101可以用Tensorflow枢纽

您可以冻结图形转换为TensorFLow精简版flatbuffer与量化:

 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())
 
178509092
 # 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())
 
45182656
ls -lh {tflite_models_dir}/*.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828  44K Jun 23 06:04 /tmp/mnist_tflite_models/mnist_model_quant_f16.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828  24K Jun 23 06:12 /tmp/mnist_tflite_models/mnist_model_quant.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828  83K Jun 23 06:12 /tmp/mnist_tflite_models/mnist_model.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828  44M Jun 23 06:13 /tmp/mnist_tflite_models/resnet_v2_101_quantized.tflite
-rw-rw-r-- 1 colaboratory-playground 50844828 171M Jun 23 06:12 /tmp/mnist_tflite_models/resnet_v2_101.tflite

模型大小减少了从171 MB至43 MB。上imagenet该模型的精度可以使用规定的脚本来评价TFLite精度测量

优化模型顶部-1精度76.8,同样为浮点模型。