Перейти к содержанию
Skillpedia
Мобильные приложения10k · #11912

litert-runtime

Что он делает

Этот скилл направляет добавление машинного обучения на устройстве в Android-приложение с моделью .tflite, используя API LiteRT CompiledModel. Он нужен Android-разработчикам, которые решают на телефоне задачи с изображениями, аудио или эмбеддингами.

Когда использовать

  • ✓Когда вы хотите, чтобы модель классификации изображений или другая модель зрения работала внутри Android-приложения.
  • ✓Когда нужно настроить LiteRT в Gradle, выбирая между средой Play services и встроенной средой.
  • ✓Когда вы хотите запускать модель .tflite на GPU с откатом на CPU.

Ссылка на скилл

https://github.com/android/skills/blob/main/device-ai/litert/litert-runtime/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/android/skills/blob/main/device-ai/litert/litert-runtime/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Добавь классификацию изображений с моделью .tflite в мое Android-приложение с LiteRT на GPU.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл помогает выбрать среду выполнения, добавить зависимости Gradle и подготовить изображения для модели. Затем он показывает, как запускать модель на GPU и при необходимости переключаться на CPU.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

This skill provides step-by-step guidance for building an Android app that runs a .tflite model with the LiteRT CompiledModel API (com.google.ai.edge.litert:litert 2.x; source repository) on the CPU or the GPU, with the runtime bundled in the APK or from Google Play services. Don't use the deprecated org.tensorflow.lite.Interpreter API. For open text language models using .litertlm files, suggest the litert-lm skill.

Prerequisites

  • A Kotlin Android project (minSdk must be 24 or higher, as declared by the LiteRT 2.3.0 AARs).
  • The runtime that Step 1 picks: the Google Play services runtime (com.google.android.gms:play-services-litert, the default; see LiteRT in Google Play services), or the bundled runtime (implementation("com.google.ai.edge.litert:litert:2.3.0") and implementation("com.google.ai.edge.litert:litert-gpu:2.3.0") from Google Maven). For the bundled runtime, from 2.3.0 the GPU accelerator is the second artifact: with litert alone the app builds, and CompiledModel.create with CompiledModel.Options(Accelerator.GPU) throws LiteRtException because the APK has no GPU accelerator library. With CompiledModel.Options(Accelerator.GPU, Accelerator.CPU) it doesn't throw: the model runs on the CPU while the app reports the GPU, and only Logcat shows it (GPU accelerator could not be loaded and registered). No manifest entry is needed: litert-api, which litert depends on, declares the OpenCL driver libraries (uses-native-library) in its own manifest.
  • A verified .tflite model and its input contract (input dimensions, mean, standard deviation, channel order, and tensor layout). For models with a verified recipe, inspect the LiteRT model recipes.

Critical mandates

  • Single-thread confinement : One single-thread executor or confined coroutine dispatcher must own the CompiledModel instance. Creation, inference, and closing must execute on that same background thread, never on the main thread.
  • Buffer lifecycle : Allocate TensorBuffer instances once using createInputBuffers and createOutputBuffers, reuse them across inferences, and close all input and output buffers before closing the CompiledModel.
  • Synchronous timing : model.run enqueues work on the GPU and returns before GPU execution completes. Always measure model.run and output buffer readback (outputs[0].readFloat) together.
  • Warm-up and exception safety : Execute one warm-up inference inside the helper constructor's init block so first-run GPU shader compilation doesn't block the first user interaction, and call close in catch before rethrowing so neither CompiledModel nor TensorBuffer handles leak if buffer allocation or warm-up throws.
  • Runtime choice : Before Step 1, you must read LiteRT in Google Play services and choose the runtime. Use the Google Play services runtime unless the app needs the NPU, custom operators, or a Support library class that this skill can't replace (such as MetadataExtractor), or also targets devices without Google Play services. Never put both runtimes in the same build variant.
  • Migration : When the app already uses org.tensorflow.lite code, you must read the "Migrating from legacy TFLite Interpreter" section in full before you edit any file. Migrated code must not import any org.tensorflow.lite class (including DataType), every legacy GPU choice (GpuDelegate, or the Support library's Model.Device.GPU) becomes CompiledModel.Options(Accelerator.GPU, Accelerator.CPU), and an NNAPI choice maps to that same GPU option.

Detailed steps

Step 1: Configure Gradle and place the model file

Search the project for libs.versions.toml, gradle.properties, app/build.gradle.kts, and any existing org.tensorflow.lite imports before editing build files. Then pick the runtime:

  • Google Play services runtime (default) : Use it unless one of the bundled runtime cases applies, also when the request doesn't name a runtime. You must read LiteRT in Google Play services now: its dependencies replace the ones in this step, and its Environment replaces the environment property of Step 2. Use version 17.0.0 exactly, and run `./gradlew assembleD
Частые вопросы

Какую среду выполнения использовать?

Скилл просит выбрать между средой Google Play services, которая используется по умолчанию, и встроенной средой.

Какая минимальная версия Android нужна?

Значение minSdk проекта должно быть 24 или выше, так как этого требуют библиотеки LiteRT.

Использует ли он старый TensorFlow Lite Interpreter?

Нет. Скилл советует не использовать этот устаревший API и применяет CompiledModel.

Подробности

Оригинальное описание автора

Configures and implements LiteRT (.tflite) on-device inference on Android in Kotlin using the CompiledModel API on CPU and GPU. Use this skill for any Android LiteRT or .tflite task, including Gradle setup, image classification or vision/audio/embedding helpers, TensorBuffer reuse, CPU memory optimization, Bitmap preprocessing, AndroidViewModel GPU-to-CPU fallback with warm-up on a single-thread dispatcher, LiteRT in Google Play services (play-services-litert), migrating from legacy org.tensorflow.lite.Interpreter, GpuDelegate, or play-services-tflite, and latency benchmarking. Don't use for r

repo: android/skills

Популярность

Звёзды на GitHub
10k
Место в рейтинге
#11912
Лицензия
Apache-2.0
Обновлён
29.10.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы