搭配 TensorFlow Lite 使用 JAX 模型

本頁提供路徑,適用於想要使用 JAX 訓練模型的使用者,並部署至行動裝置以進行推論 (範例 Colab)。

本指南中的方法會產生 tflite_model,可直接與 TFLite 解譯器程式碼範例使用,或儲存至 TFLite FlatBuffer 檔案。

修課條件

建議使用最新的 TensorFlow 夜間 Python 套件試用這項功能。

pip install tf-nightly --upgrade

我們會使用 Orbax Export 程式庫來匯出 JAX 模型。確認 JAX 至少為 0.4.20 以上版本。

pip install jax --upgrade
pip install orbax-export --upgrade

將 JAX 模型轉換為 TensorFlow Lite

我們使用 TensorFlow SavedModel 做為 JAX 和 TensorFlow Lite 之間的中繼格式。有 SavedModel 之後,即可使用現有的 TensorFlow Lite API 完成轉換程序。

# This code snippet converts a JAX model to TFLite through TF SavedModel.
from orbax.export import ExportManager
from orbax.export import JaxModule
from orbax.export import ServingConfig
import tensorflow as tf
import jax.numpy as jnp

def model_fn(_, x):
  return jnp.sin(jnp.cos(x))

jax_module = JaxModule({}, model_fn, input_polymorphic_shape='b, ...')

# Option 1: Simply save the model via `tf.saved_model.save` if no need for pre/post
# processing.
tf.saved_model.save(
    jax_module,
    '/some/directory',
    signatures=jax_module.methods[JaxModule.DEFAULT_METHOD_KEY].get_concrete_function(
        tf.TensorSpec(shape=(None,), dtype=tf.float32, name="input")
    ),
    options=tf.saved_model.SaveOptions(experimental_custom_gradients=True),
)
converter = tf.lite.TFLiteConverter.from_saved_model('/some/directory')
tflite_model = converter.convert()

# Option 2: Define pre/post processing TF functions (e.g. (de)?tokenize).
serving_config = ServingConfig(
    'Serving_default',
    # Corresponds to the input signature of `tf_preprocessor`
    input_signature=[tf.TensorSpec(shape=(None,), dtype=tf.float32, name='input')],
    tf_preprocessor=lambda x: x,
    tf_postprocessor=lambda out: {'output': out}
)
export_mgr = ExportManager(jax_module, [serving_config])
export_mgr.save('/some/directory')
converter = tf.lite.TFLiteConverter.from_saved_model('/some/directory')
tflite_model = converter.convert()

# Option 3: Convert from TF concrete function directly
converter = tf.lite.TFLiteConverter.from_concrete_functions(
    [
        jax_module.methods[JaxModule.DEFAULT_METHOD_KEY].get_concrete_function(
            tf.TensorSpec(shape=(None,), dtype=tf.float32, name="input")
        )
    ]
)
tflite_model = converter.convert()

檢查轉換後的 TFLite 模型

將模型轉換為 TFLite 後,即可執行 TFLite 解譯器 API 來檢查模型輸出。

# Run the model with TensorFlow Lite
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors() input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
interpreter.set_tensor(input_details[0]["index"], input_data)
interpreter.invoke()
result = interpreter.get_tensor(output_details[0]["index"])