LiteRT Next API 与 LiteRT API 不兼容,因此使用 LiteRT 的应用必须完全迁移到 LiteRT Next,才能使用新 API 提供的功能。应用无法将 TF Lite 解释器 API 和已编译的模型 API 互换使用。
LiteRT Next 为 Kotlin 和 C++ 提供了 API。使用其他语言的 LiteRT SDK 的应用应继续使用 LiteRT。
Android 依赖项
如需使用 LiteRT 迁移 Android 应用,请将依赖项从 com.google.ai.edge.litert
替换为 com.google.ai.edge.litert:litert:2.0.0-alpha
。
在 LiteRT 中,GPU 加速器可作为代理在单独的库 (com.google.ai.edge.litert:litert-gpu
) 中使用。在 LiteRT Next 中,GPU 加速器包含在 LiteRT Next 软件包中。如需了解详情,请参阅搭配使用 LiteRT Next 的 GPU。
您可以将 LiteRT Next 软件包添加到 build.gradle
依赖项:
dependencies {
...
implementation `com.google.ai.edge.litert:litert:2.0.0-alpha`
}
代码更改
使用 LiteRT 的应用必须将使用 TFLite Interpreter API 的代码替换为使用 Compiled Model API 的代码。下文介绍了迁移到 LiteRT Next 所需进行的主要更改。如需了解详情,请参阅 LiteRT Next API 参考文档。
C++ 中的代码更改
如需使用 C++ 迁移应用,请替换以下关键代码段:
LiteRT(TFLite 解释器) | LiteRT Next (CompiledModel ) |
|
---|---|---|
加载模型 | FlatBufferModel::BuildFromFile() InterpreterBuilder(...) |
Model::CreateFromFile("mymodel.tflite") 注意:无单独的构建器步骤 |
初始化运行时 | builder(&interpreter), interpreter->AllocateTensors() |
CompiledModel::Create(env, model, kLiteRtHwAcceleratorCpu) 注意:无需手动执行内存分配步骤 |
使用加速器 | interpreter->ModifyGraphWithDelegate(...) |
CompiledModel::Create(env, model, kLiteRtHwAcceleratorGpu) |
运行模型 | interpreter->Invoke() |
compiled_model->Run(inputs, outputs) |
Kotlin 中的代码更改
如需使用 Kotlin 迁移应用,请按以下关键步骤操作:
设置模型和运行时
使用 LiteRT,您可以分步加载模型、设置加速和初始化运行时:
// Load the model
val modelBuffer: MappedByteBuffer =
FileUtil.loadMappedFile(appContext, "model.tflite")
// Initialize runtime
val options = Interpreter.Options()
val interpreter = Interpreter(modelBuffer, options)
interpreter.allocateTensors()
// Use accelerators
aval gpuDelegate = GpuDelegate()
options.addDelegate(gpuDelegate)
使用 LiteRT Next,您可以同时加载模型、指定加速度并初始化运行时:
val model =
CompiledModel.create(
context.assets,
"model.tflite",
CompiledModel.Options(Accelerator.GPU)
)
运行推断
如需使用 LiteRT 运行模型,请执行以下操作:
val input = FloatBuffer.allocate(data_size)
val output = FloatBuffer.allocate(data_size)
interpreter.run(input, output)
如需使用 LiteRT Next 运行模型,请执行以下操作:
val inputBuffers = model.createInputBuffers()
val outputBuffers = model.createOutputBuffers()
model.run(inputBuffers, outputBuffers)
其他图书馆
LiteRT Next API 仅提供 Kotlin 和 C++ 版本。使用其他语言的 LiteRT SDK 的应用无法迁移到 LiteRT Next。
在 Play 服务运行时中使用 LiteRT 的应用无法迁移到 LiteRT Next,而应继续使用 play-services-tflite
运行时。Task 库和 Model Maker 库无法迁移到 LiteRT Next,应继续使用 TensorFlow Lite API。