GPU and NPU acceleration
Why it matters
- On-device AI (ML Kit, MediaPipe Tasks, LiteRT, on-device LLMs) only feels fast when inference runs on a GPU or NPU instead of the CPU. Choosing the wrong accelerator or skipping the fallback is a primary cause of ANRs and crashes in AI features.
- Interviewers at product companies ask how you pick an accelerator, what you do when NPU is missing, and how you verify the model is actually offloaded. Getting the fallback chain and threading wrong is a red flag.
- NPU support is vendor-specific and changes with chip generations. A hard-coded NPU path fails on many devices in your install base. You need a runtime fallback and a remote kill-switch.
- Large models (on-device LLMs, vision transformers) must be downloaded after install, not bundled. Pairing that download with the right accelerator at load time is a senior-level concern.
The simple explanation
- Think of a kitchen: the CPU is one chef, the GPU is a team of line cooks, the NPU is a dedicated pastry machine.
- You ask for the pastry machine first (fastest for its job).
- If it is missing, you use the line-cook team.
- If that is also unavailable, the single chef handles it (slow but always present).
- You set up the pastry machine before service, not while customers wait (load the model early, off the main thread).
- You test the kitchen on a small restaurant, not just the flagship hotel.
Android devices expose three compute units for ML inference: CPU, GPU, and NPU. The CPU is always present but slowest for matrix-heavy tensor work. The GPU handles parallel tensor operations well and is available on most modern devices. The NPU (from chip vendors such as Qualcomm and MediaTek) is a dedicated AI coprocessor that can be the fastest and most power-efficient option, but it is vendor-specific, absent on many devices, and needs extra setup.
LiteRT (the new name for TensorFlow Lite) exposes this through CompiledModel.Options, which takes accelerators in order of preference: CompiledModel.Options(Accelerator.NPU, Accelerator.GPU) means NPU, falling back to GPU if NPU is unavailable. GPU needs the litert-gpu dependency. NPU needs vendor runtime libraries and sometimes a model compiled ahead of time for that chip; follow the LiteRT NPU guide. On top of that you keep an app-level fallback: if create still fails, retry with CPU only.
| Accelerator | Availability | Best for | Fallback |
|---|---|---|---|
| NPU | Vendor-specific, not all devices | Large models, sustained inference | GPU |
| GPU | Most modern Android devices | Medium models, image tasks | CPU |
| CPU | All devices | Small models, guaranteed fallback | None |
Three rules prevent the most common bugs: (1) always load and run the model off the main thread (Dispatchers.Default or a dedicated thread); (2) load it before the user needs it, because creating a CompiledModel for GPU or NPU is the slow step; (3) measure on a real low-end device, not just a flagship. NPU support changes with each chip generation, so check the current LiteRT docs for supported models and devices. Large models should be downloaded after install (Play Asset Delivery or Play for On-device AI), not bundled in the base APK. ML Kit and AICore pick hardware for you, MediaPipe Tasks let you choose CPU or GPU, and LiteRT gives you the full list including NPU.
Notes
- LiteRT's
CompiledModel.Optionstakes accelerators in order (Accelerator.NPU,Accelerator.GPU,Accelerator.CPU); later entries are fallbacks. The olderInterpreter+ delegate pattern still exists in legacy code. - Always have a fallback: NPU → GPU → CPU. NPU is vendor-specific and absent on many devices. An NPU-only path fails to load, or worse crashes in a native driver, on unsupported hardware.
- Run inference off the main thread. Use
Dispatchers.Defaultor a dedicatedCoroutineDispatcher. Callingrun()on the main thread blocks the UI and triggers an ANR after 5 seconds. - Load the model and create its buffers before the user needs them. Model creation prepares it for the accelerator and is slow; an optional dummy run absorbs any remaining first-run cost.
- NPU support depends on the chip vendor and device model, not on the Android version. Check the current LiteRT docs for supported models and devices; do not hard-code a device list.
- Large models (on-device LLMs, vision transformers) should be downloaded after install via Play Asset Delivery, Play for On-device AI, or your own
WorkManagerdownload. Bundling them in the base module can exceed Play size limits. - Close buffers and the model (
close()) when you are done. LiteRT holds native memory for weights and buffers; leaking them gets the app killed after repeated load cycles. - Measure on a real low-end device. A flagship NPU hides problems that appear on mid-range or older hardware. Add a remote feature flag to disable NPU if a specific chip revision misbehaves.
- Do not put an API key in app code or
BuildConfigfor any cloud-assisted path. Keys must stay on a server. On-device inference needs no key, but hybrid flows do. - The MediaPipe LLM Inference API (
tasks-genai) is deprecated; its replacement for on-device LLMs is LiteRT-LM with.litertlmmodel files. Use LiteRT-LM for new work.
Code example
This Kotlin function shows the accelerator fallback pattern with the real LiteRT CompiledModel API: try NPU (with GPU and CPU as listed fallbacks), then GPU, then plain CPU, all off the main thread, with a remote switch to skip NPU.
import android.content.Context
import android.util.Log
import com.google.ai.edge.litert.Accelerator
import com.google.ai.edge.litert.CompiledModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
private const val TAG = "OnDeviceInference"
// Best option first. Each Options lists its own fallbacks inside LiteRT.
private fun attempts(allowNpu: Boolean) = buildList {
if (allowNpu) add("NPU" to CompiledModel.Options(Accelerator.NPU, Accelerator.GPU, Accelerator.CPU))
add("GPU" to CompiledModel.Options(Accelerator.GPU, Accelerator.CPU))
add("CPU" to CompiledModel.Options(Accelerator.CPU))
}
// Call once, early, from a ViewModel. allowNpu comes from remote config (kill-switch).
suspend fun loadWithFallback(
context: Context,
assetName: String,
allowNpu: Boolean
): CompiledModel = withContext(Dispatchers.Default) {
for ((label, options) in attempts(allowNpu)) {
try {
val model = CompiledModel.create(context.assets, assetName, options)
Log.i(TAG, "Loaded with options starting at " + label)
return@withContext model
} catch (e: Exception) {
Log.w(TAG, label + " setup failed, trying next", e)
}
}
error("Could not load " + assetName + " on any accelerator")
}- The loop tries the NPU options first, then GPU, then CPU. The first
createthat succeeds wins; the rest are skipped. allowNpucomes from remote config, so you can switch NPU off for a bad chip or driver without a release. A hard native crash cannot be caught bytry, which is why the switch matters.withContext(Dispatchers.Default)keeps the slow model creation off the main thread, even if the caller is in a ComposeLaunchedEffect. Run inference the same way.- The log records which option list succeeded. Inside a list LiteRT may still fall back, so also log inference time per device to spot models that quietly ended up on CPU.
Run the idea in plain Kotlin
enum class Accelerator { NPU, GPU, CPU }
class AcceleratorFallback {
private val available = mutableSetOf<Accelerator>()
private val priority = listOf(Accelerator.NPU, Accelerator.GPU, Accelerator.CPU)
fun register(acc: Accelerator) {
available.add(acc)
}
fun select(): Accelerator {
return priority.firstOrNull { it in available } ?: Accelerator.CPU
}
fun describe(): String {
val chosen = select()
val fallbacks = priority.filter { it in available && it != chosen }
return "Selected: " + chosen + ", fallbacks: " + fallbacks.joinToString(", ")
}
}
fun main() {
val flagship = AcceleratorFallback()
flagship.register(Accelerator.NPU)
flagship.register(Accelerator.GPU)
flagship.register(Accelerator.CPU)
println("Flagship device: " + flagship.describe())
val midRange = AcceleratorFallback()
midRange.register(Accelerator.GPU)
midRange.register(Accelerator.CPU)
println("Mid-range device: " + midRange.describe())
val lowEnd = AcceleratorFallback()
lowEnd.register(Accelerator.CPU)
println("Low-end device: " + lowEnd.describe())
val noAccel = AcceleratorFallback()
println("No accelerators: " + noAccel.describe())
}In production
- Users reported the app freezing for 5+ seconds when opening the camera screen.
- ANR traces showed the main thread blocked inside a native inference call.
- The team had called the LiteRT
run()method directly inside a ComposeLaunchedEffectwithout dispatching to a background thread.
- Wrapped the inference call in
withContext(Dispatchers.Default)so it runs off the main thread. - Added a loading indicator that shows until the first result arrives.
- Loaded the model when the screen opens, not on the first tap, so the slow setup is hidden behind the camera start-up.
- After switching to NPU acceleration, model loading failed or crashed natively on devices without NPU support.
- Crash analytics showed the failure concentrated on specific chip vendors and older device models.
- No fallback was implemented; the code asked for NPU only and treated a load failure as fatal.
- Listed GPU and CPU after NPU in the options and added an app-level retry on CPU, so the app degrades gracefully.
- Tested on a device matrix that included low-end and mid-range hardware, not just flagships.
- Added a remote feature flag to disable NPU for a specific chip revision if a future regression appears.
Common mistakes
- Running inference on the main thread. The UI thread blocks for hundreds of milliseconds, triggering an ANR after 5 seconds and a force-close. Always dispatch to
Dispatchers.Defaultor a dedicated thread before callingrun(). - No fallback when NPU is unavailable. An NPU-only path fails on devices without a supported NPU. List GPU and CPU after NPU and keep an app-level CPU retry.
- Loading the model on the first tap. Creating a
CompiledModelfor GPU or NPU takes time. Load it early (screen entry or ViewModel init) so the user's first real request is smooth. - Bundling a large model in the base APK. Models above a few hundred MB push the APK past Play size limits and slow every install. Download after install with Play Asset Delivery, Play for On-device AI, or
WorkManager. - Not closing models and buffers. LiteRT holds native memory for weights and buffers. Failing to call
close()leaks that memory, and long-running apps get killed after repeated load cycles. - Testing only on a flagship device. A flagship NPU hides problems that appear on mid-range or older hardware. Measure on a real low-end device and add a remote kill-switch for NPU if a chip revision misbehaves.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What hardware accelerators are available for ML inference on Android, and how do you select them?”
“How do you handle the case where the NPU is not available on a user's device?”
“What is the difference between GPU and NPU acceleration for ML workloads?”
“How do you verify in production that your model is actually running on the accelerator you requested?”
Quiz
What is the correct fallback order for LiteRT accelerators?
What happens if you call model inference on the main thread?
NPU availability on Android depends on what?
What should you do before the user's first real inference request?
0 of 4 answered
Mini task
Add a LiteRT accelerator fallback to your app (15 min)
-
Add the LiteRT dependencies. In your
app/build.gradle.kts, addcom.google.ai.edge.litert:litertandlitert-gpu. Check the current docs for the latest version. -
Create
InferenceEngine.kt. CopyloadWithFallbackfrom the example. Use a small.tflitemodel bundled inassets/for testing, and keepallowNpu = falseunless you have done the NPU setup. -
Load early. In a
ViewModelinitblock, callloadWithFallbackinsideviewModelScope.launch, then create the input and output buffers. Close them and the model inonCleared(). -
Add a timing log. Around
model.run(inputs, outputs), recordSystem.nanoTime()before and after. Log the elapsed time and which option list loaded. This lets you confirm the fallback worked and measure real latency. -
Test the fallback. Run on a real device, then temporarily throw an exception for the NPU and GPU attempts inside the loop and confirm the log shows the CPU path loading. Confirm no ANR appears when you trigger inference from a Compose
LaunchedEffect.
Done when: the log shows which option list loaded, the CPU fallback works, inference runs off the main thread, and the first request after loading has no visible jank.