使用元数据生成模型接口

借助 LiteRT 元数据,开发者可以生成封装容器代码,以便在 Android 上实现集成。对于大多数开发者来说,Android Studio ML Model Binding 的图形界面最易于使用。如果您需要更多自定义选项或使用命令行工具,还可以使用 LiteRT Codegen

使用 Android Studio 机器学习模型绑定

对于通过元数据增强的 LiteRT 模型,开发者可以使用 Android Studio ML Model Binding 根据模型元数据自动配置项目设置并生成封装容器类。封装容器代码无需直接与 ByteBuffer 互动。不过,开发者可以使用 BitmapRect 等类型化对象与 LiteRT 模型进行交互。

在 Android Studio 中导入 LiteRT 模型

  1. 右键点击要使用 TFLite 模型的模块或点击 File,然后依次点击 New > Other > LiteRT Model

  2. 选择 TFLite 文件的位置。请注意,该工具将通过机器学习模型绑定代表您配置模块的依赖项,并且所有依赖项都会自动插入到 Android 模块的 build.gradle 文件中。

    可选:如果您想使用 GPU 加速,请选中第二个复选框以导入 TensorFlow GPU。

  3. 点击 Finish

  4. 成功导入后,系统会显示以下界面。如需开始使用该模型,请选择 Kotlin 或 Java,然后复制并粘贴 Sample Code 部分下的代码。您可以双击 Android Studio 中 ml 目录下的 TFLite 模型,返回此界面。

加速模型推理

借助机器学习模型绑定,开发者可以通过使用委托和线程数来加速代码运行。

第 1 步:检查模块 build.gradle 文件,确认其中包含以下依赖项:

    dependencies {
        ...
        // For the LiteRT GPU delegate, we need
        // 'com.google.ai.edge.litert:litert-gpu' version 1.*.
        implementation 'com.google.ai.edge.litert:litert-gpu:1.4.1'
    }

第 2 步:检测设备上运行的 GPU 是否与 TensorFlow GPU 委托兼容,如果不兼容,则使用多个 CPU 线程运行模型:

Kotlin

    import org.tensorflow.lite.gpu.CompatibilityList
    import org.tensorflow.lite.gpu.GpuDelegate

    val compatList = CompatibilityList()

    val options = if(compatList.isDelegateSupportedOnThisDevice) {
        // if the device has a supported GPU, add the GPU delegate
        Model.Options.Builder().setDevice(Model.Device.GPU).build()
    } else {
        // if the GPU is not supported, run on 4 threads
        Model.Options.Builder().setNumThreads(4).build()
    }

    // Initialize the model as usual feeding in the options object
    val myModel = MyModel.newInstance(context, options)

    // Run inference per sample code
      

Java

    import org.tensorflow.lite.support.model.Model
    import org.tensorflow.lite.gpu.CompatibilityList;
    import org.tensorflow.lite.gpu.GpuDelegate;

    // Initialize interpreter with GPU delegate
    Model.Options options;
    CompatibilityList compatList = CompatibilityList();

    if(compatList.isDelegateSupportedOnThisDevice()){
        // if the device has a supported GPU, add the GPU delegate
        options = Model.Options.Builder().setDevice(Model.Device.GPU).build();
    } else {
        // if the GPU is not supported, run on 4 threads
        options = Model.Options.Builder().setNumThreads(4).build();
    }

    MyModel myModel = new MyModel.newInstance(context, options);

    // Run inference per sample code
      

使用 LiteRT 代码生成器生成模型接口

对于通过元数据增强的 LiteRT 模型,开发者可以使用 LiteRT Android 封装容器代码生成器来创建平台专用封装容器代码。封装容器代码无需直接与 ByteBuffer 互动。开发者可以使用 BitmapRect 等类型化对象与 TensorFlow Lite 模型进行交互。

代码生成器的实用性取决于 LiteRT 模型的元数据条目的完整性。请参阅 metadata_schema.fbs 中相关字段下的 <Codegen usage> 部分,了解代码生成工具如何解析每个字段。

生成封装容器代码

您需要在终端中安装以下工具:

pip install tflite-support

完成后,可以使用以下语法来使用代码生成器:

tflite_codegen --model=./model_with_metadata/mobilenet_v1_0.75_160_quantized.tflite \
    --package_name=org.tensorflow.lite.classify \
    --model_class_name=MyClassifierModel \
    --destination=./classify_wrapper

生成的代码将位于目标目录中。如果您使用的是 Google Colab 或其他远程环境,则可能更轻松地将结果压缩到 ZIP 归档中,然后将其下载到 Android Studio 项目中:

# Zip up the generated code
!zip -r classify_wrapper.zip classify_wrapper/

# Download the archive
from google.colab import files
files.download('classify_wrapper.zip')

使用生成的代码

第 1 步:导入生成的代码

如有必要,将生成的代码解压缩到目录结构中。生成的代码的根被假定为 SRC_ROOT

打开您想要使用 LiteRT 模型的 Android Studio 项目,然后通过以下方式导入生成的模块:依次选择 File -> New -> Import Module -> 选择 SRC_ROOT

使用上述示例,导入的目录和模块将称为 classify_wrapper

第 2 步:更新应用的 build.gradle 文件

在将使用生成的库模块的应用模块中:

在 android 部分下,添加以下内容:

aaptOptions {
   noCompress "tflite"
}

在“dependencies”部分下,添加以下内容:

implementation project(":classify_wrapper")

第 3 步:使用模型

// 1. Initialize the model
MyClassifierModel myImageClassifier = null;

try {
    myImageClassifier = new MyClassifierModel(this);
} catch (IOException io){
    // Error reading the model
}

if(null != myImageClassifier) {

    // 2. Set the input with a Bitmap called inputBitmap
    MyClassifierModel.Inputs inputs = myImageClassifier.createInputs();
    inputs.loadImage(inputBitmap));

    // 3. Run the model
    MyClassifierModel.Outputs outputs = myImageClassifier.run(inputs);

    // 4. Retrieve the result
    Map<String, Float> labeledProbability = outputs.getProbability();
}

加速模型推理

生成的代码可让开发者通过使用委托和线程数来加速代码。这些参数可在初始化模型对象时设置,因为该对象需要三个参数:

  • Context:来自 Android Activity 或 Service 的上下文
  • (可选)Device:TFLite 加速委托。例如:GPUDelegate
  • (可选)numThreads:用于运行模型的线程数 - 默认值为 1。

例如,如需使用 GPU 委托和最多三个线程,您可以按如下方式初始化模型:

try {
    myImageClassifier = new MyClassifierModel(this, Model.Device.GPU, 3);
} catch (IOException io){
    // Error reading the model
}

问题排查

如果您收到“java.io.FileNotFoundException: This file can not be opened as a file descriptor; it is probably compressed”错误,请在将使用库模块的应用模块的 android 部分下插入以下行:

aaptOptions {
   noCompress "tflite"
}