Home / Market / litert runtime

litert runtime

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, Bitmap preprocessing, AndroidViewModel GPU-to-CPU fallback with warm-up on a single-thread dispatcher, migrating from legacy org.tensorflow.lite.Interpreter or GpuDelegate, and latency benchmarking. Don't use for runn

skill★ 10844739 dlskills.shApache-2.0Install in CosmosUpstream Source

Documentation & Preview

--- name: litert-runtime description: 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, Bitmap preprocessing, AndroidViewModel GPU-to-CPU fallback with warm-up on a single-thread dispatcher, migrating from legacy org.tensorflow.lite.Interpreter or GpuDelegate, and latency benchmarking. Don't use for running generative text LLMs with .litertlm files or for Python model conversion. license: Complete terms in LICENSE.txt metadata: author: Google LLC last-updated: '2026-10-20' keywords:

---

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. Don't use the deprecated org.tensorflow.lite.Interpreter API. For open text language models using .litertlm files, suggest the litert-lm skill.

Prerequisites

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.

Critical mandates

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. Configure minSdk and add the LiteRT runtime and GPU accelerator dependencies in app/build.gradle.kts:

android { defaultConfig { minSdk = 24 } }

dependencies { implementation("com.google.ai.edge.litert:litert:2.3.0") implementation("com.google.ai.edge.litert:litert-gpu:2.3.0") }

Place bundled models at app/src/main/assets/model.tflite (AGP stores .tflite files uncompressed by default). Deliver a model that exceeds the base APK size limit through Play for On-Device AI as an AI pack, or download it into context.filesDir (bundletool --local-testing installs AI packs locally without Google Play). Read an install-time AI pack through AssetManager. Load a fast-follow or on-demand AI pack or a downloaded file from its on-disk filePath using CompiledModel.create(filePath, CompiledModel.Options(accelerator), environment) in place of the asset call in Step 2. Obtain the pack's directory from the AI Delivery library (com.google.android.play:ai-delivery) using AiPackManagerFactory.getInstance(context).getPackLocation(name)?.assetsPath(), which returns null until the pack has finished downloading.

With 2.3.0, nothing is added to gradle.properties: litert 2.3.0 declares the namespace com.google.ai.edge.litert.impl and its dependency litert-api 2.3.0 declares com.google.ai.edge.litert, so AGP 9.x builds the project. With 2.2.0 or 2.1.6, both libraries declare com.google.ai.edge.litert, and AGP 9.x stops at processDebugMainManifest (AGP 8.x reports it as a warning and builds); for those two versions, add android.uniquePackageNames=false to gradle.properties, and remove it when moving to 2.3.0 because it also hides the same clash between any other two libraries. Excluding litert-api instead doesn't work: CompiledModel and Accelerator are in litert-api, and the build then fails at compileDebugKotlin.

Step 2: Implement the inference helper class

Isolate CompiledModel and its TensorBuffer instances in a dedicated AutoCloseable helper class free of Android UI types:

import android.content.Context import com.google.ai.edge.litert.Accelerator import com.google.ai.edge.litert.CompiledModel import com.google.ai.edge.litert.Environment import com.google.ai.edge.litert.TensorBuffer

const val INPUT_SIZE = 224 * 224 * 3 private val environment by lazy { Environment.create() }

class Classifier(context: Context, accelerator: Accelerator) : AutoCloseable { private val model = CompiledModel.create( context.assets, "model.tflite", CompiledModel.Options(accelerator), environment ) private val inputs = mutableListOf<TensorBuffer>() private val outputs = mutableListOf<TensorBuffer>()

init { try { inputs += model.createInputBuffers() outputs += model.createOutputBuffers() infer(FloatArray(INPUT_SIZE)) } catch (e: Exception) { close() throw e } }

fun infer(input: FloatArray): FloatArray { inputs[0].writeFloat(input) model.run(inputs, outputs) return outputs[0].readFloat() }

override fun close() { (inputs + outputs).forEach { it.close() } model.close() } }

Accelerator.CPU requires nothing from the device. Accelerator.GPU compiles the graph for the GPU; when the GPU can't execute the model, the constructor throws LiteRtException (from create for an operator the GPU doesn't support, and on the Android emulator from create or from buffer allocation). A missing asset or a file that isn't a valid model also throws LiteRtException from create.

The buffers are created once with the model, reused for every inference, and closed before the model. One Environment serves every model in the process and stays open, so LiteRT loads the GPU accelerator library once rather than on every create call. The constructor ends with one warm-up inference (the first GPU run includes shader compilation) and closes the model and its buffers if any step in init throws. INPUT_SIZE is the model's input element count: writeFloat throws on a longer array and writes a shorter one without an error, so a wrong size produces an incorrect result. For int8 or uint8 tensors, use writeInt8 and readInt8 on TensorBuffer instead of writeFloat and readFloat.

Step 3: Wire the ViewModel and Compose screen

Drive the helper from a single-thread executor inside an AndroidViewModel, fall back to Accelerator.CPU when GPU compilation fails, and expose immutable state to the Compose UI:

import android.app.Application import androidx.lifecycle.AndroidViewModel import com.google.ai.edge.litert.Accelerator import com.google.ai.edge.litert.LiteRtException import java.util.concurrent.Executors import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch

data class UiState( val ready: Boolean = false, val accelerator: Accelerator = Accelerator.CPU, val result: List<Float>? = null, val error: String? = null )

class MainViewModel(app: Application) : AndroidViewModel(app) { private val executor = Executors.newSingleThreadExecutor() private val scope = CoroutineScope( SupervisorJob() + executor.asCoroutineDispatcher() ) private var classifier: Classifier? = null private val _uiState = MutableStateFlow(UiState()) val uiState: StateFlow<UiState> = _uiState.asStateFlow()

fun load(preferred: Accelerator = Accelerator.GPU) { scope.launch { if (classifier != null) return@launch val appContext = getApplication<Application>() val selected = try { classifier = Classifier(appContext, preferred) preferred } catch (e: LiteRtException) { if (preferred != Accelerator.CPU) { try { classifier = Classifier(appContext, Accelerator.CPU) Accelerator.CPU } catch (cpuError: LiteRtException) { _uiState.value = UiState(error = cpuError.message) return@launch } } else { _uiState.value = UiState(error = e.message) return@launch } } _uiState.value = UiState(ready = true, accelerator = selected) } }

fun classify(input: FloatArray) { scope.launch { try { classifier?.infer(input)?.let { result -> _uiState.update { it.copy(result = result.toList(), error = null) } } } catch (e: LiteRtException) { _uiState.update { it.copy(error = e.message) } } } }

override fun onCleared() { scope.launch { classifier?.close() }.invokeOnCompletion { scope.cancel() } executor.shutdown() } }

One single-thread executor owns the model: creation, inference, and closing execute only on it, never on the main thread. The ViewModel keeps its own