開箱即用的 RNN 轉換
現在,我們支持將 Keras LSTM 和 Keras 雙向 LSTM 轉換為複合 TensorFlow 算子。如要獲取基於 RNN 的模型以利用 TensorFlow Lite 中的高效 LSTM 融合算子,這是最簡單的方式。請參閱此 Colab,了解如何通過 TensorFlow Lite 解釋器進行端到端 Keras LSTM 到 TensorFlow Lite 的轉換和執行。
Keras LSTM
https://tensorflow.google.cn/api_docs/python/tf/keras/layers/LSTM
Keras 雙向 LSTM
https://tensorflow.google.cn/api_docs/python/tf/keras/layers/Bidirectional
此 Colab
https://colab.sandbox.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/experimental_new_converter/Keras_LSTM_fusion_Codelab.ipynb
此外,我們通過提供連接至基礎架構轉換的便捷接口,實現了到其他任意 TensorFlow RNN 實現的轉換。您也可查看此功能與使用 lingvo 的 LSTMCellSimple 和 LayerNormalizedLSTMCellSimple RNN 實現相關的數個示例。
lingvo
https://github.com/tensorflow/lingvo
LSTMCellSimple
https://github.com/tensorflow/tensorflow/blob/82abf0dbf316526cd718ae8cd7b11cfcb805805e/tensorflow/compiler/mlir/lite/transforms/prepare_composite_functions_tf.cc#L130
LayerNormalizedLSTMCellSimple
https://github.com/tensorflow/tensorflow/blob/c11d5d8881fd927165eeb09fd524a80ebaf009f2/tensorflow/compiler/mlir/lite/transforms/prepare_composite_functions_tf.cc#L137
如需獲取更多信息,請查看我們的 RNN 轉換文檔。
註:目前,我們致力於對 TensorFlow Lite 的 LSTM 算子添加量化支持。我們將在未來推出相關成果。
擴展至其他複合算子
我們擴展了 TensorFlow Lite 轉換器,以便將其他複合 TensorFlow 算子轉換為現有或自定義的 TensorFlow Lite 算子。
要實現 TensorFlow 算子融合至 TensorFlow Lite,需執行以下步驟:將複合算子打包至 tf.function 中。在 TensorFlow 模型原始碼中,使用 experimental_implements 函數注釋標識複合算子並將其抽象為 tf.function。編寫轉換代碼。從概念上看,轉換代碼用已融合算子替換了此接口的複合實現。在 prepare-composite-functions 傳遞中,插入轉換代碼。調用 TensorFlow Lite 轉換器。使用 TFLiteConverter.from_saved_model API 轉換為 TensorFlow Lite。
experimental_implements轉換代碼
https://github.com/tensorflow/tensorflow/blob/c11d5d8881fd927165eeb09fd524a80ebaf009f2/tensorflow/compiler/mlir/lite/transforms/prepare_composite_functions_tf.cc#L115
TFLiteConverter.from_saved_model
https://tensorflow.google.cn/api_docs/python/tf/lite/TFLiteConverter#from_saved_model
有關此基礎架構的整體架構,請參閱此處[1]。有關代碼示例的詳細步驟,請參閱此處[2]。如需了解後臺中的算子融合工作方式,請參閱詳細文檔。
此處[1]
https://tensorflow.google.cn/lite/convert/operation_fusion#converting_from_composite_to_fused_operation
此處[2]
https://tensorflow.google.cn/lite/convert/operation_fusion#wrap_the_composite_operation_in_a_tffunction
詳細文檔
https://tensorflow.google.cn/lite/convert/operation_fusion#under_the_hood