Android 版 LiteRT

以下 LiteRT 运行时 API 可用于 Android 开发:

  • CompiledModel API:高性能推理的现代标准,可简化 CPU/GPU/NPU 之间的硬件加速。详细了解为何选择 CompiledModel API
  • Interpreter API:基本推理 API,用于保持向后兼容性。

CompiledModel API 使用入门

支持的 Android 版本和 API

LiteRT 版本 状态 支持的 API 最低 SDK 级别 最低 NDK 版本(如果使用) 发行日期
v2.1.0 ✅ 最新版 CompiledModel
Interpreter(仅支持 CPU)
23(Android 6 Marshmallow) r26a 2025-12-19
v2.0.3 ⚠️ 旧版 CompiledModel 26 (Android 8 Oreo) r26a 2025-11-08
v1.4.1 ✅ 最新版 Interpreter 21 (Android 5 Lollipop) r26a 2025-11-07
v1.4.0 ⚠️ 旧版 Interpreter 26 (Android 8 Oreo) r26a 2025-06-25
v1.3.0 ⚠️ 旧版 Interpreter 21 (Android 5 Lollipop) r26a 2025-05-19
v1.2.0 ⚠️ 旧版 Interpreter 21 (Android 5 Lollipop) r26a 2025-03-13

重要提示请及时更新依赖项,以确保与最新功能和安全更新保持兼容。

CompiledModel API 快速入门

将 LiteRT Maven 软件包添加到您的 Android 项目中:

dependencies {
  ...
  implementation `com.google.ai.edge.litert:litert:2.1.0`
}

.tflite 模型与 CompiledModel API 集成。以下代码段展示了 Kotlin 和 C++ 中的基本实现。

Kotlin

// Load model and initialize runtime
val compiledModel = CompiledModel.create(
    "/path/to/mymodel.tflite",
    CompiledModel.Options(Accelerator.CPU))

// Preallocate input/output buffers
val inputBuffers = compiledModel.createInputBuffers()
val outputBuffers = compiledModel.createOutputBuffers()

// Fill the input buffer
inputBuffers.get(0).writeFloat(input0)
inputBuffers.get(1).writeFloat(input1)

// Invoke
compiledModel.run(inputBuffers, outputBuffers)

// Read the output
val output = outputBuffers.get(0).readFloat()

C++

// Load model and initialize runtime
LITERT_ASSIGN_OR_RETURN(auto env, GetEnvironment());
LITERT_ASSIGN_OR_RETURN(auto options, GetOptions());
LITERT_ASSIGN_OR_RETURN(
    auto compiled_model,
    CompiledModel::Create(env, "/path/to/mymodel.tflite", options));

// Preallocate input/output buffers
LITERT_ASSIGN_OR_RETURN(auto input_buffers,compiled_model.CreateInputBuffers(signature_index));
LITERT_ASSIGN_OR_RETURN(auto output_buffers,compiled_model.CreateOutputBuffers(signature_index));

// Fill the input buffer
LITERT_ABORT_IF_ERROR(input_buffers[0].Write(input0));
LITERT_ABORT_IF_ERROR(input_buffers[1].Write(input1));

// Invoke
LITERT_ABORT_IF_ERROR(compiled_model.Run(signature_index, input_buffers, output_buffers));

// Read the output
LITERT_ABORT_IF_ERROR(output_buffers[0].Read(output0));