LiteRT: running your own models

Run your own LiteRT models on Android with Kotlin: CompiledModel, accelerator fallback, off-main-thread inference, and model lifecycle management. About 25 minutes.

Why it matters

  • LiteRT runs any compatible model you train or convert yourself, beyond the fixed features of ML Kit and the task pipelines of MediaPipe Tasks.
  • Senior interviews probe accelerator selection, fallback chains, and native memory management; these are the parts that separate a copy-paste dev from one who owns the pipeline.
  • Getting the lifecycle wrong causes ANRs, native memory leaks, or silent crashes on specific chip vendors in production.
  • LiteRT is the runtime under MediaPipe Tasks and LiteRT-LM (on-device LLMs), so the ideas you learn here carry across the Google AI Edge stack.

The simple explanation

  • LiteRT is a universal adapter for your phone's processors: NPU, GPU, CPU.
  • NPU is the fast lane, GPU the medium lane, CPU the slow but always-available lane.
  • The fallback chain is a GPS that reroutes when a road is closed.
  • Loading is like warming up an engine before a race: do it once, before the user is waiting.
  • Calling close() is turning off the engine; skip it and fuel (native memory) keeps leaking.

LiteRT is the new name for TensorFlow Lite. Its modern entry point is CompiledModel. You pass the accelerators you want in CompiledModel.Options, for example Options(Accelerator.GPU, Accelerator.CPU), which means GPU with CPU fallback if GPU is unavailable. The older Interpreter API with delegates still exists, and you will meet it in existing code.

ConceptOld TFLiteLiteRT
Load modelInterpreter(modelBuffer, options)CompiledModel.create(context.assets, name, options)
Acceleratoradd a delegate (e.g. GpuDelegate) to Interpreter.OptionsCompiledModel.Options(Accelerator.GPU, Accelerator.CPU)
Runinterpreter.run(input, output)write to createInputBuffers(), run(inputs, outputs), read outputs
Cleanupinterpreter.close()close buffers, then model.close()

GPU needs the extra litert-gpu dependency. NPU depends on the chip vendor and device and needs extra setup from the LiteRT NPU guide; check the current docs for supported devices. Always include a GPU or CPU fallback so the app does not crash on unsupported hardware.

Create the model off the main thread: CompiledModel.create prepares the model for the chosen accelerator and is the slow step. Create input and output buffers once and reuse them. An optional dummy run after loading absorbs any remaining first-run cost. Run all inference on Dispatchers.Default or a dedicated thread.

Large models (tens to hundreds of MB) must not be bundled in the base APK. Use Play Asset Delivery, Play for On-device AI, or your own WorkManager download. LiteRT is also available through Google Play services, so the runtime does not have to ship inside your app.

For on-device LLMs, LiteRT-LM with .litertlm model files replaces the deprecated MediaPipe LLM Inference API. ML Kit GenAI and MediaPipe Tasks cover ready-made and vision/text/audio tasks; LiteRT is where you bring your own model.

Notes

  • LiteRT is the new name for TensorFlow Lite; CompiledModel is the modern API. The Interpreter + delegates API still exists for older code.
  • CompiledModel.Options(Accelerator.GPU, Accelerator.CPU) lists accelerators in order; later ones are the fallback. GPU needs the litert-gpu dependency.
  • NPU support depends on the chip vendor and device and needs extra setup; always list a GPU or CPU fallback after NPU.
  • Create the model off the main thread (Dispatchers.Default or a dedicated thread); it is the slow step. Reuse the input and output buffers.
  • Call close() on the tensor buffers and the CompiledModel to free native memory. Do not rely on the GC for native memory.
  • Large models must not be bundled in the base APK. Use Play Asset Delivery, Play for On-device AI, or a WorkManager download after install.
  • LiteRT is available through Google Play services (you get an Environment from LiteRt.initialize) as well as a direct dependency.
  • For on-device LLMs, LiteRT-LM with .litertlm files replaces the deprecated MediaPipe LLM Inference API (tasks-genai).
  • Measure on real low-end devices. A model that runs fine on a flagship phone may be unusable on a budget device with limited RAM.
  • Check the current docs for supported models, devices, and accelerator availability; these lists change frequently.

Code example

This shows a production-style wrapper around CompiledModel that asks for GPU with CPU fallback, loads on a background thread, reuses buffers, and frees native memory on release.

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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
 
/** Wraps a LiteRT CompiledModel. Use it from one thread at a time. */
class OnDeviceInference(private val context: Context) {
 
    private var model: CompiledModel? = null
    private var inputs: List<TensorBuffer> = emptyList()
    private var outputs: List<TensorBuffer> = emptyList()
 
    /** Load once, off the main thread, e.g. from a ViewModel. */
    suspend fun load(assetName: String) = withContext(Dispatchers.Default) {
        val m = try {
            // GPU first; LiteRT falls back to CPU if GPU is unavailable
            CompiledModel.create(
                context.assets,
                assetName,
                CompiledModel.Options(Accelerator.GPU, Accelerator.CPU)
            )
        } catch (e: Exception) {
            // Last resort: plain CPU (log e so you can see which devices hit this)
            CompiledModel.create(context.assets, assetName, CompiledModel.Options(Accelerator.CPU))
        }
        inputs = m.createInputBuffers()   // allocate once, reuse every call
        outputs = m.createOutputBuffers()
        model = m
    }
 
    /** Must be called off the main thread. Input size must match the model. */
    fun infer(input: FloatArray): FloatArray {
        val m = model ?: error("Model not loaded")
        inputs[0].writeFloat(input)
        m.run(inputs, outputs)
        return outputs[0].readFloat()
    }
 
    /** Free native memory. Call in ViewModel.onCleared(). */
    fun release() {
        inputs.forEach { it.close() }
        outputs.forEach { it.close() }
        model?.close()
        model = null
    }
}
  • The accelerator choice is made once, at create time, so the cost is paid once, not per inference. The catch is a belt-and-braces retry on plain CPU.
  • Buffers are created once and reused. Creating them per call wastes time and memory.
  • release() closes buffers and the model, which hold native memory; model = null prevents accidental reuse after release. To use NPU, add Accelerator.NPU first and follow the NPU setup guide.

Run the idea in plain Kotlin

enum class Accelerator { NPU, GPU, CPU }

class AcceleratorSelector {
  private val available = mutableSetOf<Accelerator>()
  fun register(a: Accelerator) { available.add(a) }
  fun select(preferred: List<Accelerator>): Accelerator {
      for (a in preferred) {
          if (available.contains(a)) return a
      }
      return Accelerator.CPU
  }
}

class InferencePipeline {
  private var accel: Accelerator = Accelerator.CPU
  private var loaded = false
  private var count = 0

  fun init(available: Set<Accelerator>, preferred: List<Accelerator>) {
      val sel = AcceleratorSelector()
      for (a in available) sel.register(a)
      accel = sel.select(preferred)
      loaded = false
      count = 0
  }

  fun load() {
      loaded = true
      count++
  }

  fun infer(inputSize: Int): Int {
      if (!loaded) throw IllegalStateException("Must load before inference")
      count++
      return inputSize * 2
  }

  fun release() {
      loaded = false
      count = 0
      accel = Accelerator.CPU
  }

  fun status(): String {
      return "accel=" + accel.name + " count=" + count + " loaded=" + loaded
  }
}

fun main() {
  val preferred = listOf(Accelerator.NPU, Accelerator.GPU, Accelerator.CPU)

  // Device with NPU available
  val p1 = InferencePipeline()
  p1.init(setOf(Accelerator.NPU, Accelerator.GPU, Accelerator.CPU), preferred)
  p1.load()
  val r1 = p1.infer(128)
  println("NPU device: " + p1.status() + " output=" + r1)

  // CPU-only device: fallback kicks in
  val p2 = InferencePipeline()
  p2.init(setOf(Accelerator.CPU), preferred)
  p2.load()
  val r2 = p2.infer(64)
  println("CPU device: " + p2.status() + " output=" + r2)

  // Error path: inference before load
  val p3 = InferencePipeline()
  p3.init(setOf(Accelerator.CPU), preferred)
  try {
      p3.infer(32)
  } catch (e: IllegalStateException) {
      println("Caught expected error: " + e.message)
  }

  // Release frees the pipeline
  p1.release()
  println("After release: " + p1.status())
}

In production

NPU crash on a single chip vendor
  • Users on one phone model reported a high crash rate during image classification; the rest of the user base was unaffected.
  • Crash logs showed a native crash inside the vendor driver, not in Kotlin code.
  • The model was loaded with NPU as the only accelerator and no fallback.
  • The issue was specific to one chip vendor's NPU driver and did not reproduce on other vendors.
The fix
  • Added GPU and CPU fallback to the accelerator chain so the model loads on any device.
  • Wrapped CompiledModel.create in a try-catch that logs the failure and retries on CPU (a try-catch cannot catch a hard native crash, which is why the fallback list and remote flag matter).
  • Added a remote-config flag to disable NPU for the affected chip vendor without a new release.
  • Verified the fix on multiple low-end devices from different chip vendors.
APK rejected for size
  • Play Console rejected the upload because the base module was over the size limit.
  • A large model was bundled in assets/.
  • Even before the limit, install size had grown for every user, including those who never used the feature.
The fix
  • Moved the model to Play Asset Delivery (fast-follow) so it downloads after first launch.
  • Added a WorkManager fallback for devices where Play Asset Delivery is unavailable.
  • Added a download progress bar and a retry with exponential backoff.
  • Reduced the model size further with post-training quantization to bring the on-disk footprint down.

Common mistakes

  • Running inference on the main thread. A single inference can take significant time on a low-end device, triggering an ANR. Always dispatch to Dispatchers.Default or a dedicated thread and post results back to the main thread.
  • Not calling close() on CompiledModel and its buffers. They hold native memory. Skipping close() leaks memory that grows over the app session and can get the process killed. Pair close() with setting the reference to null.
  • Bundling a large model in the base APK. Large models push the APK past Play Store limits and slow every install. Use Play Asset Delivery, Play for On-device AI, or a WorkManager download after install.
  • No accelerator fallback. If NPU is the only option and the device does not support it, CompiledModel.create fails and the feature is dead. Always list a GPU or CPU fallback so the app degrades gracefully.
  • Loading the model when the user taps. CompiledModel.create is slow. Load it earlier (screen entry or a ViewModel init) so the user does not wait on the first interaction.
  • Starting new code on the Interpreter API. The Interpreter + delegate path still works, but new work should use CompiledModel with Accelerator options, which is where hardware acceleration is being developed.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How does LiteRT accelerator selection and fallback work?”

“How do you manage the lifecycle of a CompiledModel in an Android app?”

“How do you distribute a large model to users without bloating the APK?”

“How do you verify that on-device inference is performant enough for your use case?”

Quiz

In the modern LiteRT CompiledModel API, how do you choose hardware acceleration?

What should you do right after creating a CompiledModel?

Where should you run CompiledModel.run() in an Android app?

What happens if you never call close() on a CompiledModel?

0 of 4 answered

Mini task

15-minute exercise: wire a LiteRT model into a Compose screen

  1. Create a new Android project (Kotlin, Jetpack Compose). Add com.google.ai.edge.litert:litert and litert-gpu (check the current docs for the latest version).
  2. Place a small .tflite model in src/main/assets/ (or download it with WorkManager if it is larger than a few MB).
  3. Create an OnDeviceInference class that mirrors the example: CompiledModel.Options(Accelerator.GPU, Accelerator.CPU), a load() suspend function that creates the model and buffers, an infer() function, and a release() that closes buffers and the model.
  4. In a ViewModel, call inference.load("my_model.tflite") in an init block. Expose a StateFlow for the result.
  5. In the Compose screen, add a button that calls a ViewModel method; that method runs inference.infer(sampleInput) inside viewModelScope.launch(Dispatchers.Default) and puts the result in the StateFlow.
  6. Call inference.release() in the ViewModel.onCleared() override.
  7. Done condition: the app loads the model, the button produces a result without ANR, and closing the screen does not leak native memory (verify with adb shell dumpsys meminfo <pid> before and after).
Next: GPU and NPU acceleration