LiteRT dành cho Android

Các API thời gian chạy LiteRT sau đây có sẵn để phát triển trên Android:

  • API CompiledModel: Tiêu chuẩn hiện đại cho hoạt động suy luận hiệu suất cao, tinh giản khả năng tăng tốc phần cứng trên CPU/GPU/NPU. Tìm hiểu thêm về lý do nên chọn CompiledModel API.
  • API Interpreter: API suy luận cơ bản, được duy trì để tương thích ngược.

Bắt đầu sử dụng CompiledModel API

Các phiên bản và API Android được hỗ trợ

Phiên bản LiteRT Trạng thái API được hỗ trợ Cấp độ SDK tối thiểu Phiên bản NDK tối thiểu (nếu có) Ngày phát hành
v2.1.0 ✅ Mới nhất CompiledModel
Interpreter(chỉ CPU)
23 (Android 6 Marshmallow) r26a 19/12/2025
v2.0.3 ⚠️ Cũ CompiledModel 26 (Android 8 Oreo) r26a 08/11/2025
v1.4.1 ✅ Mới nhất Interpreter 21 (Android 5 Lollipop) r26a 07/11/2025
v1.4.0 ⚠️ Cũ Interpreter 26 (Android 8 Oreo) r26a 25/06/2025
v1.3.0 ⚠️ Cũ Interpreter 21 (Android 5 Lollipop) r26a 19/05/2025
v1.2.0 ⚠️ Cũ Interpreter 21 (Android 5 Lollipop) r26a 13/03/2025

Lưu ý quan trọng: Luôn cập nhật các phần phụ thuộc để đảm bảo khả năng tương thích với các tính năng mới nhất và bản cập nhật bảo mật.

Hướng dẫn nhanh về CompiledModel API

Thêm gói LiteRT Maven vào dự án Android của bạn:

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

Tích hợp mô hình .tflite với API CompiledModel. Đoạn mã sau đây cho thấy cách triển khai cơ bản trong Kotlin và 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));