Litert Runtime
Android (Google)OfficialCreated by Google LLCDistributed by Android (Google)
- Skill
- Tool integration
- Software development
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive guide for integrating LiteRT (.tflite) models into Android applications using the modern CompiledModel API. It covers project configuration, efficient inference implementation on CPU and GPU, memory management, and migration from legacy TensorFlow Lite Interpreter code. The skill emphasizes performance best practices, such as single-thread confinement, buffer reuse, and proper warm-up procedures to ensure smooth on-device execution.
What it does
- Configures Gradle dependencies for LiteRT bundled or Google Play services runtimes.
- Implements a thread-safe, AutoCloseable inference helper class.
- Provides patterns for GPU acceleration with automatic CPU fallback.
- Optimizes memory usage through TensorBuffer reuse and weight caching.
- Guides the migration process from legacy org.tensorflow.lite.Interpreter APIs.
- Includes preprocessing logic to convert Bitmaps into model-compatible input tensors.
When to use it
- When building new Android applications requiring on-device ML inference.
- When migrating existing apps from legacy TensorFlow Lite Interpreter to LiteRT.
- When optimizing model inference latency and memory footprint on Android.
- When needing to support GPU-accelerated inference with robust fallback mechanisms.
Advantages
- Uses the modern, performant CompiledModel API for efficient execution.
- Ensures thread safety by enforcing single-thread confinement for model operations.
- Provides clear migration paths for legacy TFLite implementations.
- Supports flexible runtime choices between bundled and Google Play services.
Usage examples
- “How do I set up my Android project to use LiteRT with GPU acceleration?”
- The skill provides the necessary Gradle dependencies for the bundled runtime and instructions for configuring CompiledModel.Options to enable the GPU accelerator.
- “I need to migrate my existing TFLite Interpreter code to LiteRT. Where do I start?”
- The skill outlines a seven-step migration process, including capturing golden outputs, swapping dependencies, and replacing legacy delegates with the CompiledModel API.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/android/litert-runtime/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip litert-runtime.zip -d .agents/skills
Documentation by Google LLC
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 (
minSdkmust be24or 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")andimplementation("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: withlitertalone the app builds, andCompiledModel.createwithCompiledModel.Options(Accelerator.GPU)throwsLiteRtExceptionbecause the APK has no GPU accelerator library. WithCompiledModel.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, whichlitertdepends on, declares the OpenCL driver libraries (uses-native-library) in its own manifest.A verified
.tflitemodel 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
CompiledModelinstance. Creation, inference, and closing must execute on that same background thread, never on the main thread.Buffer lifecycle : Allocate
TensorBufferinstances once usingcreateInputBuffersandcreateOutputBuffers, reuse them across inferences, and close all input and output buffers before closing theCompiledModel.Synchronous timing :
model.runenqueues work on the GPU and returns before GPU execution completes. Always measuremodel.runand output buffer readback (outputs[0].readFloat) together.Warm-up and exception safety : Execute one warm-up inference inside the helper constructor's
initblock so first-run GPU shader compilation doesn't block the first user interaction, and callcloseincatchbefore rethrowing so neitherCompiledModelnorTensorBufferhandles 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.litecode, you must read the "Migrating from legacy TFLite Interpreter" section in full before you edit any file. Migrated code must not import anyorg.tensorflow.liteclass (includingDataType), every legacy GPU choice (GpuDelegate, or the Support library'sModel.Device.GPU) becomesCompiledModel.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
Environmentreplaces theenvironmentproperty of Step 2. Use version17.0.0exactly, and run./gradlew assembleDebug(not--dry-run) after you add it. Switch to the bundled runtime only when that build reportsCould not find com.google.android.gms:play-services-litert:17.0.0, and tell the user, also when the user asked for Google Play services. Never leave the build broken.Bundled runtime : Use it only when the app needs the NPU, custom operators, or a Support library class that this skill can't replace (such as
MetadataExtractor), when the app also targets devices without Google Play services, or when the user asks for it.FileUtil,ImageProcessor,TensorImage, andTensorLabeldon't count: replace them as LiteRT in Google Play services describes. For the bundled runtime, configureminSdkand add the LiteRT runtime and GPU accelerator dependencies inapp/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.
When memory matters, use the following options:
Load from a path :
create(context.assets, ...)keeps a copy of the asset's bytes in the native heap while the model is open. Copy the asset once intocontext.noBackupFilesDir(a downloaded or AI pack file is already on disk) and callcreate(filePath, ...)so the file is mapped and reclaimable. Version the staged filename, bump the version when the bundled model changes, and delete the previous version's file. Copy to a temporary file and rename it so a copy interrupted by process death is never loaded:import android.content.Context import com.google.ai.edge.litert.Accelerator import com.google.ai.edge.litert.CompiledModel import java.io.File
fun stageModelAsset( context: Context, assetName: String = "model.tflite", version: String = "v1" ): File = File(context.noBackupFilesDir, "$version-$assetName").also { file -> if (!file.isFile) { context.noBackupFilesDir.listFiles()?.forEach { if (it.name.endsWith("-$assetName")) it.delete() } val tmp = File("${file.path}.tmp") context.assets.open(assetName).use { input -> tmp.outputStream().use { output -> input.copyTo(output) } } check(tmp.renameTo(file)) } }
fun memoryOptions( context: Context, accelerator: Accelerator = Accelerator.CPU, assetName: String = "model.tflite", version: String = "v1" ): CompiledModel.Options = CompiledModel.Options(accelerator).apply { val prefix = "$assetName-" val cache = File(context.codeCacheDir, "$prefix$version.xnnpack_cache") context.codeCacheDir.listFiles()?.forEach { if (it.name.startsWith(prefix) && it.name.endsWith(".xnnpack_cache") && it != cache) { it.delete() } } cpuOptions = CompiledModel.CpuOptions( numThreads = 4, xnnPackFlags = 0x23, xnnPackWeightCachePath = cache.path ) }
Weight cache (
xnnPackWeightCachePath): Written on the first load (~1x an FP32 or ~2x an FP16 model's file size) and mapped on later loads, moving packed FP32 weights off the heap. Version the cache filename and delete outdated caches.Transient indirection buffer (
xnnPackFlags = 0x23) : Default0x3plus flag0x20, replacing per-operator convolution pointer tables with one shared buffer (byte-identical outputs, ~1% latency overhead at 4 threads, ~3% single-threaded). Because the value replaces the default,0x20alone leavesint8anduint8operators to fallback kernels.cpuOptionsis ignored on the GPU.Close after a task: Closing frees the runtime workspace; recreating with a warm cache takes ~20 ms, whereas the first inference after any load pays a full warm-up run, so close when the next use isn't imminent.
Step 3: Wire the ViewModel and Compose screen
Drive the helper from a single-thread executor inside an AndroidViewModel, and
fall back to Accelerator.CPU when GPU compilation fails:
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
scope because viewModelScope is canceled before onCleared runs, so a close
launched there wouldn't run; onCleared cancels scope once close completes.
load is a no-op when a model is already loaded across configuration changes; a
failed load leaves classifier null. classify reports any
LiteRtException (in package com.google.ai.edge.litert) in error and keeps
the model.
The following Compose screen takes the picture (bitmap) from the photo picker
or CameraX and runs preprocess in the click handler (a few milliseconds for
224x224; move preprocess onto the executor for images exceeding 224x224).
viewModel and collectAsStateWithLifecycle come from
androidx.lifecycle:lifecycle-viewmodel-compose and
androidx.lifecycle:lifecycle-runtime-compose:
import android.graphics.Bitmap
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.ai.edge.litert.Accelerator
@Composable
fun MainScreen(
bitmap: Bitmap,
viewModel: MainViewModel = viewModel()
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
LaunchedEffect(Unit) { viewModel.load(Accelerator.GPU) }
Column {
state.error?.let { Text(it) }
Button(
onClick = { viewModel.classify(preprocess(bitmap)) },
enabled = state.ready
) {
Text("Run (${state.accelerator})")
}
state.result?.let { scores ->
Text("Top class: ${scores.indices.maxBy { i -> scores[i] }}")
}
}
}Step 4: Preprocess inputs to match the model contract
Convert the Bitmap into the model's input with preprocess. Match the
model's exact input dimensions, normalization mean and standard deviation,
channel order, and memory layout (this example uses NHWC, RGB, scaled to
-1.0..1.0). Mismatched mean or std values produce corrupted predictions
that look like a broken model:
import android.graphics.Bitmap
fun preprocess(
bitmap: Bitmap,
size: Int = 224,
mean: Float = 127.5f,
std: Float = 127.5f
): FloatArray {
val scaled = checkNotNull(
Bitmap.createScaledBitmap(bitmap, size, size, true)
.copy(Bitmap.Config.ARGB_8888, false)
)
val pixels = IntArray(size * size).also {
scaled.getPixels(it, 0, size, 0, 0, size, size)
}
val out = FloatArray(size * size * 3)
pixels.forEachIndexed { i, p ->
out[i * 3] = ((p shr 16 and 0xFF) - mean) / std
out[i * 3 + 1] = ((p shr 8 and 0xFF) - mean) / std
out[i * 3 + 2] = ((p and 0xFF) - mean) / std
}
return out
}The scaled bitmap is copied to Bitmap.Config.ARGB_8888 because ImageDecoder
returns Bitmap.Config.HARDWARE bitmaps by default on Android 9 and higher
(including from a photo picker Uri), scaling preserves that config, and
getPixels can't read HARDWARE bitmaps; the copy is of the 224x224 scaled
bitmap rather than the full image. Scaling doesn't preserve the aspect ratio;
crop first if the model requires center cropping. An audio or embedding model
replaces preprocess with its own input encoding and keeps the inference class.
Step 5: Verify output on a physical device
Run the app on a physical device that runs Android from Android Studio. Compare
the app's output with the model's reference output for one fixed input on
Accelerator.CPU first and then on Accelerator.GPU; when verifying model
outputs on a physical device, you must follow device verification.
Migrating from legacy TFLite Interpreter
An existing app on org.tensorflow.lite.Interpreter (from
org.tensorflow:tensorflow-lite* or from com.google.ai.edge.litert:litert
1.x) moves to the CompiledModel code of Steps 1 to 5 in seven steps, in this
order. Before you change any file of an
existing app, you must read migration, which gives the commands and code
for each step. An app on the Interpreter API in Google Play services
(play-services-tflite-java) follows LiteRT in Google Play services
instead:
Find the runtime: Read the build files and the resolved dependencies, and note the delegate, the thread count, and the Support library classes that the app uses.
Capture a golden output first : While the legacy runtime is still in the project, record the app's output for one fixed input on the CPU. This step needs a device or an emulator. Run the capture test with
am instrument, notconnectedDebugAndroidTest, which uninstalls the app and deletes the file.Swap the dependencies : Delete every legacy artifact line (never leave it commented out) and add the dependencies of the runtime that Step 1 picks: by default those of LiteRT in Google Play services, with the same fallback to the bundled runtime when Gradle can't find
play-services-litert. On the Play services runtime, replace the Support library classes as LiteRT in Google Play services describes. On the bundled runtime, an app keeps them withcom.google.ai.edge.litert:litert-support:2.3.0, with the packageorg.tensorflow.lite.supportrenamed tocom.google.ai.edge.litert.support(LiteRT Support migration guide).Replace the delegates :
GpuDelegatebecomesCompiledModel.Options(Accelerator.GPU, Accelerator.CPU), so the CPU runs the operators that the GPU doesn't support. An NNAPI choice in the app maps to the same GPU option, not toAccelerator.CPUalone or to an NPU accelerator.setNumThreads(n)becomes new CPU options withcpuOptions = CompiledModel.CpuOptions(numThreads = n).Rewrite the inference code : Replace
InterpreterandFileUtil.loadMappedFilewith theClassifierhelper of Step 2, created and run only on the single-thread executor of Step 3, never in a constructor that the main thread calls. When no caller retries on the CPU as in Step 3, create the helper's GPU option with the CPU as a second accelerator (CompiledModel.Options(Accelerator.GPU, Accelerator.CPU)). Aninterpreter.runSignature(inputs, outputs, key)call becomes the helper's buffers andruncall with the signature key, as follows. This form runs on both runtimes, also after the app changes runtime or upgrades LiteRT; when the signature has more than one input or output, you must follow the signature rules in migration:inputs += model.createInputBuffers("serving_default") outputs += model.createOutputBuffers("serving_default") model.run(inputs, outputs, "serving_default")Verify in two stages: The build passes and the searches for legacy references print nothing; then the migrated output matches the golden output on a device.
Report what changed and what didn't migrate : When the app used NNAPI, tell the user that it now runs on the GPU with the CPU as a second accelerator, which changes the speed and the numerical results of a quantized model that ran on a DSP or an NPU before; point them to NPU acceleration with LiteRT for the NPU. Tell the user about the TensorFlow Lite Task Library, C++ modules, and Select TensorFlow operators, which this skill doesn't migrate.
Migration mandates that apply to every migrated app:
No
org.tensorflow.liteimports : Migrated code must not import anyorg.tensorflow.liteclass, includingorg.tensorflow.lite.DataType; the LiteRT artifacts keep these classes only for backward compatibility. Replace Support calls that needDataType(TensorImage(DataType.FLOAT32),TensorBuffer.createFixedSize, andTensorLabel) withpreprocessof Step 4, theCompiledModelbuffers, and labels paired with the output scores. Remove every existingorg.tensorflow.liteimport line, not only the ones that you add.
Antipatterns
Never create, run, or close
CompiledModelon the Android main thread.Never allocate new
TensorBufferinstances on every inference call; failing to close per-frameTensorBufferobjects leaks C++ heap memory.Never benchmark
model.runwithout including output buffer readback (outputs[0].readFloat).Never mix
org.tensorflow:tensorflow-lite*artifacts (such asorg.tensorflow:tensorflow-lite-support) withcom.google.ai.edge.litert:*artifacts; both ship theorg.tensorflow.lite.*classes and cause duplicate class build failures.Never use
Accelerator.GPUon LiteRT 2.3.0 without adding thecom.google.ai.edge.litert:litert-gpu:2.3.0dependency alongsidecom.google.ai.edge.litert:litert:2.3.0; with the CPU as a second accelerator, the model silently runs on the CPU.Never set
xnnPackFlags = 0x20on its own to get the transient indirection buffer; the value replaces the runtime's default0x3, so pass0x23.
Checklist
[ ] Is
minSdkset to24or higher and are bothcom.google.ai.edge.litert:litert:2.3.0andcom.google.ai.edge.litert:litert-gpu:2.3.0added inapp/build.gradle.kts?[ ] Are all legacy
org.tensorflow:tensorflow-lite*dependencies andorg.tensorflow.lite.*imports removed?[ ] Do
CompiledModel.create,model.run, andcloseall execute on the same single-thread background dispatcher?[ ] Are
TensorBufferinstances allocated once, reused across calls, and closed beforemodel.close, including wheninitor warm-up throws?[ ] Does
loadexecute one warm-up inference and fall back toAccelerator.CPUifAccelerator.GPUthrowsLiteRtException?[ ] Does the project compile with
./gradlew assembleDebug?[ ] If memory matters, is the model created from a path with a versioned weight cache and
xnnPackFlags = 0x23on the CPU, and closed after a task when the next use isn't imminent?
Files
- ATTRIBUTION.mdAdded by AutoGineer973 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md27.0 KiB
- references/android/google/play/on-device-ai.md36.8 KiB
- references/migration.md18.9 KiB
- references/play-services.md10.8 KiB
- references/verify.md2.4 KiB
references/migration.md
This file gives the commands and code for each step of the migration summary in
the skill. The migrated app ends with the code of Steps 1 to 5 of the skill: the
Classifier helper of Step 2, the executor and CPU fallback of Step 3, and
preprocess of Step 4.
The code in this file uses these imports:
import android.content.Context
import com.google.ai.edge.litert.Accelerator
import com.google.ai.edge.litert.CompiledModel
import com.google.ai.edge.litert.TensorBuffer
import com.google.ai.edge.litert.support.image.TensorImage
import com.google.ai.edge.litert.support.tensorbuffer.TensorBufferFloat
import java.io.File
import kotlin.math.abs1. Find the runtime
Read app/build.gradle.kts (or app/build.gradle),
gradle/libs.versions.toml, and the output of ./gradlew :app:dependencies,
which also shows what other libraries pull in. A legacy app gets the Interpreter
runtime from one of these:
TensorFlow Lite :
org.tensorflow:tensorflow-liteand the otherorg.tensorflow:tensorflow-lite*artifacts.LiteRT 1.x :
com.google.ai.edge.litert:litert,litert-gpu,litert-support, orlitert-metadataat a 1.x version.
When the app depends on the Interpreter API in Google Play services
(com.google.android.gms:play-services-tflite-java, -gpu, or -support, with
TfLite.initialize in the code), follow LiteRT in Google Play services
instead. When it depends on the TensorFlow Lite Task Library
(org.tensorflow:tensorflow-lite-task-vision, -text, or -audio), stop and
tell the user: this skill doesn't migrate it.
Then find the code that the later steps change:
grep -rnE 'org\.tensorflow\.lite\.|Interpreter|GpuDelegate|CompatibilityList|NnApiDelegate|NNAPI|[nN]umThreads|FlexDelegate|TfLite' --include='*.kt' --include='*.java' app/srcNote which accelerator each code path uses (the GPU delegate, NNAPI, or the CPU
with a thread count), and whether the app uses the TensorFlow Lite Support
Library (ImageProcessor, TensorImage, TensorLabel, MetadataExtractor).
2. Capture a golden output first
The golden output is the legacy app's output for one fixed input, recorded before any dependency changes. Step 6 compares the migrated app with it. Pick one path:
Path A (device or emulator connected) : Write an instrumented test with the project's existing test setup. The test feeds one deterministic input through the app's own inference class and preprocessing on the CPU, without the GPU or NNAPI delegate. Use a bitmap of another size than the model input, never a camera frame. Write the output with
writeGoldenOutputto a file inInstrumentationRegistry.getInstrumentation().targetContext.filesDir. When the model has signatures, also log the legacyinterpreter.getSignatureInputs(key)andgetSignatureOutputs(key): the migrated by-name calls need these names (Step 5). When the model has no signatures, loginterpreter.getInputTensor(i).name()andgetOutputTensor(i).name()instead. Don't run the capture test with./gradlew connectedDebugAndroidTest: it uninstalls the app when the test ends, which deletes the file. Install both APKs, run the test witham instrument, and copy the file out of the debuggable app:./gradlew installDebug installDebugAndroidTest adb shell pm list instrumentation # shows <test package>/<runner> for the app adb shell am instrument -w -e class <capture test class> <test package>/<runner> mkdir -p app/src/androidTest/assets/golden adb shell run-as <application ID> cat files/golden.txt > app/src/androidTest/assets/golden/output.txtPath B (no device): Don't capture. Report the capture and the device comparison of Step 6 to the user as post-implementation steps.
// Before the dependency swap: record the legacy app's output for one fixed // input, one value per line. fun writeGoldenOutput(file: File, output: FloatArray) { file.writeText(output.joinToString("\n")) }
// After the migration: compare the migrated output with the recorded one. // A difference smaller than 1e-3 passes for outputs of order 1. fun maxAbsDifference(golden: FloatArray, migrated: FloatArray): Float { check(golden.size == migrated.size) { "Size ${migrated.size} != ${golden.size}" } return golden.indices.maxOf { abs(golden[it] - migrated[it]) } }
// The golden file is an asset of the test APK: pass // InstrumentationRegistry.getInstrumentation().context, not targetContext, // whose assets throw FileNotFoundException for it. fun readGoldenOutput(testContext: Context, path: String = "golden/output.txt"): FloatArray = testContext.assets.open(path).bufferedReader().use { reader -> reader.readLines().filter { it.isNotBlank() }.map { it.toFloat() }.toFloatArray() }
3. Swap the dependencies
Remove every legacy artifact, also when another library pulls it in. The LiteRT
artifacts carry the org.tensorflow.lite runtime classes under their original
names, so a build that mixes old and new artifacts fails with duplicate classes.
Then add the dependencies of the runtime that Step 1 of the skill picks, with
minSdk 24 or higher:
Google Play services runtime (default) : You must read LiteRT in Google Play services before you edit the build file. Add
com.google.android.gms:play-services-litert:17.0.0andorg.jetbrains.kotlinx:kotlinx-coroutines-play-services, and follow its fallback to the bundled runtime when Gradle can't findplay-services-litert:17.0.0.Bundled runtime : Add
litert:2.3.0andlitert-gpu:2.3.0.
Support library
On the Google Play services runtime, replace the Support library classes as
the Play services reference of the skill describes: FileUtil with asset
reads, ImageProcessor and TensorImage with preprocess of Step 4 of the
skill, and TensorLabel with labels paired with the output scores. On the
bundled runtime, an app on the TensorFlow Lite Support Library keeps it. The
library ships as LiteRT Support, with the same classes and behavior. When the
app uses ImageProcessor, TensorImage, TensorLabel, or MetadataExtractor,
you must read the LiteRT Support migration guide before swapping the
coordinates:
org.tensorflow:tensorflow-lite-supportorlitert-support1.x becomescom.google.ai.edge.litert:litert-support:2.3.0.org.tensorflow:tensorflow-lite-support-apiorlitert-support-api1.x becomeslitert-support-api:2.3.0, next tolitert:2.3.0.tensorflow-lite-metadataorlitert-metadata1.x becomeslitert-metadata:2.3.0. It depends oncom.google.flatbuffers:flatbuffers-java:25.2.10; when the app pins an olderflatbuffers-java, upgrade it.
Keep litert:2.3.0 in the build file. Then rename the package in the sources,
the R8 and ProGuard rules, and any reflection strings:
grep -rl 'org\.tensorflow\.lite\.support' --include='*.java' --include='*.kt' --include='*.pro' app/ \
| xargs sed -i 's/org\.tensorflow\.lite\.support/com.google.ai.edge.litert.support/g'An app that never used the Support library doesn't add it. Without the Support library, load labels from assets:
// Replaces FileUtil.loadLabels in an app that drops the Support library.
fun loadLabels(context: Context, name: String = "labels.txt"): List<String> =
context.assets.open(name).bufferedReader().use { it.readLines() }Toolchain
The 2.3.0 artifacts need JDK 17 or later for the Gradle build, compileSdk
35, AGP 8.6.0 or later, and the Kotlin plugin 2.3 or later. Their classes carry
Kotlin 2.4 metadata. Ask the user before editing gradle/libs.versions.toml or
the root build.gradle.kts:
Kotlin 2.2 stops with
The binary version of its metadata is 2.4.0. A project that stays on Kotlin 2.2 addsfreeCompilerArgs += "-Xskip-metadata-version-check".With Kotlin 2.x, a Compose app applies the
org.jetbrains.kotlin.plugin.composeplugin in place ofcomposeOptions.Hilt 2.59.2 stops at
hiltJavaCompileDebugwithProvided Metadata instance has version 2.4.0. Raise Hilt to 2.60.1 or later.
4. Replace the delegates
GPU delegate (
GpuDelegate,GpuDelegateFactory): Create the GPU option of the Step 2 helper with the CPU as a second accelerator.CompatibilityListhas no counterpart; the CPU fallback of Step 3 covers a device whose GPU can't run the model.NNAPI (
NnApiDelegate,setUseNNAPI(true)): NNAPI is deprecated from Android 15, and theCompiledModelAPI has no NNAPI accelerator. Remove the delegate, and map an NNAPI choice in the app to the GPU option. You must tell the user about this change in the final report, because the speed and the numerical results of a quantized model that ran on a DSP or an NPU through NNAPI change on the GPU. NPU acceleration is a separate topic that this skill doesn't cover (NPU acceleration with LiteRT).Select TensorFlow operators (
FlexDelegate): No LiteRT 2.x artifact contains the Flex delegate. This skill doesn't cover it. Tell the user that the model needs to be exported again without Select TensorFlow operators.// Replaces GpuDelegate: the CPU runs the operators that the GPU doesn't // support, as it did with the delegate. Keep the CPU fallback of Step 3 for a // model that the GPU can't compile at all. val gpuWithCpuFallback = CompiledModel.Options(Accelerator.GPU, Accelerator.CPU)
5. Rewrite the inference code
Never search and replace Interpreter. Move the model into the Classifier
helper of Step 2 of the skill, owned by the single-thread executor of Step 3.
Keep the app's own classes and their public functions as the callers.
Model loading :
InterpreterfromFileUtil.loadMappedFile, and the SupportModel.createModel, becomeCompiledModel.createin the helper. No overload takes aByteBuffer.Inference :
runonByteBufferobjects becomeswriteFloat,run, andreadFloaton buffers that the helper creates once. UsewriteInt8andreadInt8for int8 and uint8 tensors.Thread count :
setNumThreadsbecomesCpuOptions(numThreads = n)on new CPU options; combinenumThreadswithxnnPackFlags = 0x23andxnnPackWeightCachePathin the sameCpuOptionswhen memory also matters.Tensor shapes :
getInputTensorand itsshapebecome a lookup by name.getInputTensorTypethrowsLiteRtExceptionforuint8tensors; for the size, usegetInputBufferRequirements(name, signature).bufferSize, which is in bytes for every element type.resizeInputhas no counterpart in 2.3.0.Signatures :
runSignature(inputs, outputs, key)becomesrun(inputs, outputs, key)on the lists thatcreateInputBuffers(key)andcreateOutputBuffers(key)return, created once with the model. Use this List overload by default on both runtimes, and always on the Google Play services runtime: withlitert-api2.3.0, theMap<String, TensorBuffer>overload ofrunaborts the process on that runtime, and the List overload doesn't, so code that uses it keeps running when the app changes runtime or upgrades LiteRT. The lists follow the order of the signature's inputs and outputs in the model, so a signature with one input and one output needs no names. For a signature with more than one input or output on the bundled runtime, create each buffer by name withcreateInputBuffer(name, key)andcreateOutputBuffer(name, key), and pass maps from those names torun(inputs, outputs, key); on the Google Play services runtime, keep the lists and check each position against the golden output. Every by-name call (createInputBuffer,createOutputBuffer,runwith maps,getInputTensorType,getInputBufferRequirements) takes the names in the signature, such asxorargs_0andoutput_0, not the graph tensor names such asserving_default_x:0. When the model has no signatures, the names are its input and output tensor names (such asimagesandSoftmax).CompiledModelhas no call that lists them, so take them from the legacy code (Step 2). A missing or wrong name in an output map crashes the process (JNI abort) instead of throwing, so check the names before the firstrun.Closing : Closing the interpreter becomes the helper's
close.// Replaces Interpreter.Options.setNumThreads. Create new options; never change // the shared CompiledModel.Options.CPU. fun cpuOptionsWithThreads(numThreads: Int): CompiledModel.Options = CompiledModel.Options(Accelerator.CPU).apply { cpuOptions = CompiledModel.CpuOptions(numThreads = numThreads) }
// Replaces interpreter.getInputTensor(0).shape() for float tensors. Look the // tensor up by its signature name; this throws for uint8 tensors. fun inputShape(model: CompiledModel, inputName: String): List<Int>? = model.getInputTensorType(inputName).layout?.dimensions
// Replaces interpreter.getInputTensor(0).numBytes() for any element type. fun inputSizeBytes(model: CompiledModel, inputName: String, signature: String): Int = model.getInputBufferRequirements(inputName, signature).bufferSize
// Replaces interpreter.runSignature(mapOf("args_0" to input), // mapOf("output_0" to output), "serving_default") for a signature with one // input and one output, on both runtimes. The Classifier helper of Step 2 of // the skill creates its buffers once in init with // model.createInputBuffers(signature) and model.createOutputBuffers(signature), // and calls this from infer. fun runSignature( model: CompiledModel, signature: String, inputs: List<TensorBuffer>, outputs: List<TensorBuffer>, input: FloatArray ): FloatArray { inputs[0].writeFloat(input) model.run(inputs, outputs, signature) return outputs[0].readFloat() }
// Bundled runtime only, for a signature with more than one input or output: // create each buffer by its signature name, once. Never use the map overload // of run on the Google Play services runtime, where it aborts with litert-api // 2.3.0; change it to the List overload when the app moves to that runtime. fun createSignatureBuffers( model: CompiledModel, signature: String, inputNames: List<String>, outputNames: List<String> ): Pair<Map<String, TensorBuffer>, Map<String, TensorBuffer>> = inputNames.associateWith { model.createInputBuffer(it, signature) } to outputNames.associateWith { model.createOutputBuffer(it, signature) }
// Then, for every call: model.run(inputs, outputs, signature)
With the Support library
Migrated code must not import any org.tensorflow.lite class, including
org.tensorflow.lite.DataType. The LiteRT artifacts keep these classes only for
backward compatibility. Apply these rules to the Support code:
ImageProcessor,TensorImage, andFileUtilstay undercom.google.ai.edge.litert.supportwhen the calls don't needDataType.The Support
Modelclass runs on the Interpreter API. Replace it with theClassifierhelper of Step 2 of the skill.Replace a Support call that needs
DataType, such asTensorImage(DataType.FLOAT32),TensorBuffer.createFixedSize, orTensorLabel, withpreprocessof Step 4 or with theCompiledModelbuffers.
The following code writes a processed image into the helper's buffers and pairs
the output scores with the labels, without DataType:
// Replaces the Support library's Model class. ImageProcessor and TensorImage
// stay; the processed image goes into the CompiledModel buffers directly, and
// the scores pair with the labels without TensorLabel.
fun runWithSupportImage(
model: CompiledModel,
inputs: List<TensorBuffer>,
outputs: List<TensorBuffer>,
image: TensorImage,
inputElementCount: Int,
labels: List<String>
): Map<String, Float> {
// A uint8 image (one that skipped NormalizeOp) in a float input yields NaN.
val pixels = (image.tensorBuffer as? TensorBufferFloat)?.floatArray
?: error("Normalize the image to float first")
// writeFloat accepts a shorter array without an error.
check(pixels.size == inputElementCount) { "Input size ${pixels.size}" }
inputs[0].writeFloat(pixels)
model.run(inputs, outputs)
return labels.zip(outputs[0].readFloat().toList()).toMap()
}Without the Support library
preprocess of Step 4 of the skill replaces the code that filled the input
ByteBuffer. Give it the model's input size and the legacy normalization: the
mean and std of a legacy NormalizeOp(mean, std), or the app's own formula,
in the same channel order and layout.
6. Verify in two stages
Stage 1, on the workstation : ./gradlew assembleDebug passes, and neither
of the following commands prints anything. The build alone doesn't reveal
leftover Interpreter code, because the litert 2.3.0 artifact still contains
org.tensorflow.lite.Interpreter:
grep -rnE 'org\.tensorflow\.lite\.|GpuDelegate|NnApiDelegate|FlexDelegate|support\.model\.Model|org\.tensorflow:tensorflow-lite' --include='*.kt' --include='*.java' --include='*.kts' --include='*.gradle' --include='*.toml' --include='*.pro' --exclude-dir=build --exclude-dir=.gradle .
./gradlew :app:dependencies --configuration releaseRuntimeClasspath | grep -E 'org\.tensorflow:tensorflow-lite|com\.google\.ai\.edge\.litert:litert[a-z-]*:1\.'Stage 2, on a device: Pick one path:
Path A (golden output captured in Step 2) : Extend the instrumented test of Step 2. Run the same input through the migrated preprocessing and the helper on
Accelerator.CPU, and read the golden file withreadGoldenOutput(InstrumentationRegistry.getInstrumentation().context). The test must fail whenmaxAbsDifferenceis 1e-3 or more. When the golden file holds only one value, the top-1 index must match; a wrong normalization often still passes this check. Then compare the CPU and the GPU as in Step 5 of the skill; on the bundled runtime, first check that Logcat showsDynamically loaded GPU acceleratorand notGPU accelerator could not be loaded, because the GPU and CPU option runs on the CPU without an error whenlitert-gpuis missing.Path B (no device): Run Stage 1 only, and report that Stage 2 didn't run.
Out of scope
This skill doesn't migrate the
TensorFlow Lite Task Library (tensorflow-lite-task-vision, -text, or
-audio), which has no LiteRT release.
This skill doesn't migrate C++ code. When the app has CMakeLists.txt,
Android.mk, or .cpp files that link tensorflowlite_jni, tell the user that
the C++ module moves to the LiteRT C++ SDK, and point them to
Use prebuilt C++ library from LiteRT Maven.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Google LLC
- Publisher
- Android (Google) (Official)
- Distributed by
- Android (Google)
- Source
- android/skills · device-ai/litert/litert-runtime · commit bf68e2d
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.txt)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Google LLC or Android (Google).
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download litert-runtime.zip