簡體   English   中英

用於量化感知訓練的 TF Lite 的 Toco 轉換器參數說明

[英]Description of TF Lite's Toco converter args for quantization aware training

這些天,我試圖追蹤有關部署支持 TPU 的 TF 模型的錯誤。

我可以得到一個沒有運行 TPU 支持的模型,但是一旦我啟用量化,我就會迷路。

我處於以下情況:

  1. 創建模型並訓練它
  2. 創建模型的評估圖
  3. 凍結模型並將結果保存為協議緩沖區
  4. 在沒有 TPU 支持的情況下成功轉換和部署

最后一點,我使用了 TFLiteConverter 的 Python API。 生成功能性 tflite 模型的腳本是

import tensorflow as tf

graph_def_file = 'frozen_model.pb'
inputs = ['dense_input']
outputs = ['dense/BiasAdd']

converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, inputs, outputs)
converter.inference_type = tf.lite.constants.FLOAT
input_arrays = converter.get_input_arrays()

converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]

tflite_model = converter.convert()

open('model.tflite', 'wb').write(tflite_model)

這告訴我,到目前為止,我的方法似乎沒問題。 現在,如果我想使用 Coral TPU 棒,我必須量化我的模型(我在訓練期間考慮到了這一點)。 我所要做的就是修改我的轉換器腳本。 我想我必須把它改成

import tensorflow as tf

graph_def_file = 'frozen_model.pb'
inputs = ['dense_input']
outputs = ['dense/BiasAdd']

converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, inputs, outputs)
converter.inference_type = tf.lite.constants.QUANTIZED_UINT8      ## Indicates TPU compatibility
input_arrays = converter.get_input_arrays()

converter.quantized_input_stats = {input_arrays[0]: (0., 1.)}     ## mean, std_dev
converter.default_ranges_stats = (-128, 127)                      ## min, max values for quantization (?)
converter.allow_custom_ops = True                                 ## not sure if this is needed

## REMOVED THE OPTIMIZATIONS ALTOGETHER TO MAKE IT WORK

tflite_model = converter.convert()

open('model.tflite', 'wb').write(tflite_model)

這個 tflite 模型在加載解釋器的 Python API 時會產生結果,但我無法理解它們的含義。 此外,沒有(或者如果有,它隱藏得很好)關於如何選擇均值、std_dev 和最小/最大范圍的文檔。 此外,在使用 edgetpu_compiler 編譯並部署它(使用 C++ API 加載它)后,我收到一個錯誤:

INFO: Initialized TensorFlow Lite runtime.
ERROR: Failed to prepare for TPU. generic::failed_precondition: Custom op already assigned to a different TPU.
ERROR: Node number 0 (edgetpu-custom-op) failed to prepare.

Segmentation fault

我想我在轉換過程中錯過了一個標志或其他東西。 但由於這里也缺乏文檔,我不能肯定地說。

簡而言之:

  1. params 是什么意思,std_dev,min/max 是什么意思,它們是如何交互的?
  2. 轉換過程中我做錯了什么?

我很感激任何幫助或指導!

編輯:我用完整的測試代碼打開了一個github 問題 隨意玩這個。

您永遠不需要手動設置量化統計信息。

您是否嘗試過訓練后量化教程?

https://www.tensorflow.org/lite/performance/post_training_integer_quant

基本上他們設置量化選項:

converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8

然后他們將一個“代表性數據集”傳遞給轉換器,以便轉換器可以運行幾批模型來收集必要的統計信息:

def representative_data_gen():
  for input_value in mnist_ds.take(100):
    yield [input_value]

converter.representative_dataset = representative_data_gen

雖然有量化訓練的選項,但進行訓練后量化總是更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM