Skip to content

About

Production-grade, 100% on-device AI inference engine for Android (llama.cpp GGUF, LiteRT NPU/GPU, Gemini Nano AICore).

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

android-inference-engine: High-Performance On-Device AI Runtime for Android

Maven Central Website Google Play GitHub License API Kotlin Build Status

The enterprise-grade, standalone on-device AI inference runtime for Android edge computing. Unifies llama.cpp GGUF execution, Google LiteRT NPU acceleration, and Google Gemini Nano AICore behind a high-performance Kotlin Coroutines API.

android-inference-engine is an open-source, production-proven neural inference framework engineered specifically for mobile devices. It bridges the gap between raw mobile silicon (Arm CPU clusters, Qualcomm Adreno, ARM Mali GPUs, and mobile NPUs) and on-device Large Language Models (LLMs)—such as DeepSeek-R1, Llama 3.2, Gemma 2, and Qwen 2.5—with zero cloud dependencies and absolute user privacy.

By providing automated hardware silicon profiling, Arm KleidiAI micro-kernel acceleration, self-calibrating tokens-per-second (TPS) prediction, and Multi-Token Prediction (MTP) speculative decoding, android-inference-engine delivers maximum throughput while strictly safeguarding device thermal ceilings and battery longevity.


📱 Powered by Local AI

android-inference-engine serves as the official neural runtime powering the consumer flagship app Local AI on Android. To experience local AI models and autonomous on-device agents running natively on your smartphone:


Table of Contents


Why On-Device AI Inference on Android?

Traditional AI applications route user conversations, voice transcripts, and sensitive personal context through remote cloud servers. This introduces latency, recurring API costs, connectivity requirements, and significant privacy vulnerabilities.

android-inference-engine reimagines mobile intelligence:

  1. 100% Privacy & Data Sovereignty: All weight loading, tokenization, and generation occur within the local Android application process. No prompts or telemetry ever leave the handset.
  2. Deterministic Offline Availability: Functions seamlessly in airplane mode, remote field environments, or during network outages.
  3. Zero Marginal Infrastructure Cost: Eliminates recurring cloud LLM token fees and backend GPU hosting expenses by leveraging the user's existing mobile chipset.
  4. Hardware-Native Performance: Exploits cutting-edge mobile silicon capabilities, including Arm NEON vectorization, Arm KleidiAI DotProd/I8MM instructions, Vulkan compute shaders, and dedicated Neural Processing Units (NPUs).

Key Features

  • Tri-Engine Unified Architecture:
    • llama.cpp Engine: Universal quantized GGUF execution (Q4_K_M, Q8_0) with ARM NEON vectorization and Vulkan GPU acceleration.
    • Google LiteRT Engine: Official Google Play Services unbundled runtime with 3-tier fallback (NPU -> GPU -> CPU) and Multi-Token Prediction.
    • Android AICore Engine: Zero-byte APK footprint binding directly to Android 14+ on-device Gemini Nano system models.
  • Hardware Silicon Profiler (HardwareProfiler):
    • Dynamically inspects /proc/cpuinfo for ARM instructions (dotprod, i8mm, neon, fp16, sve).
    • Automatically identifies and activates Arm KleidiAI optimized micro-kernels.
    • Parses CPU cluster topology (big.LITTLE) to bind compute threads to high-performance cores.
    • Detects Qualcomm Adreno (OpenCL/Vulkan) and ARM Mali GPUs to optimize layer offloading.
  • Speculative Decoding & Multi-Token Prediction (MTP):
    • Accelerates generation throughput by $1.5\times$ to $3\times$ using concurrent speculative token verification.
  • Multi-Family Tokenizer Chat Engine (ChatTemplateEngine):
    • Built-in formatting for 6 model families: Llama 3, ChatML (Qwen, DeepSeek, SmolLM), Gemma, Phi, Mistral/Llama-2, and Generic.
    • Automatic <think>...</think> scratchpad stripping for reasoning models like DeepSeek-R1.
    • Dynamic token budgeting, context sliding-window eviction, and system prompt retention pinning.
  • Comprehensive Hardware Guardrails:
    • Dynamic Thermal Throttling (DeviceThermalMonitor): Reduces CPU thread allocations and sheds GPU layers under thermal stress.
    • Battery Power Gating (DevicePowerMonitor): Restricts high-intensity workloads when battery drops below 15% (unplugged) or Battery Saver is active.
    • Low-Memory Killer (LMK) Protection (MemoryLimiterKillGuard): Intercepts memory trim signals to reclaim caches before OS termination.
    • Model Hibernation Watchdog (ModelHibernationManager): Automatically frees inactive native memory contexts after 5 minutes of idle time.

System Architecture

The following diagram illustrates how applications interface with mobile silicon through the unified runtime:

flowchart TD
    subgraph ClientLayer ["Client & Application Layer"]
        LocalAIApp["Local AI Flagship App<br/>(Google Play: dev.shanaka.localai)"]
        CustomApp["Custom Android Application / Service"]
    end

    subgraph FacadeAPI ["Unified API Facade (io.github.localai.inference.api)"]
        LocalInference["LocalInference Facade"]
        EngineRouter["InferenceEngineRouter<br/>(Magic Byte & Model ID Auto-Routing)"]
    end

    subgraph TriEngine ["Tri-Engine Execution Backends"]
        LlamaEngine["LlamaCppEngine<br/>• GGUF Universal Format<br/>• ARM NEON / Vulkan GPU<br/>• 32-bit RAM Guard (1.1GB)"]
        LiteRTEngine["LiteRTEngine<br/>• Play Services Unbundled<br/>• 3-Tier Fallback (NPU→GPU→CPU)<br/>• MTP Speculative Decoding"]
        AiCoreEngine["AiCoreEngine<br/>• Android 14+ AICore (Gemini Nano)<br/>• Zero APK Bloat (0 MB)<br/>• Specialized Agent & Task APIs"]
    end

    subgraph SiliconProfiling ["Hardware Intelligence & Profiler"]
        Profiler["HardwareProfiler<br/>(big.LITTLE Cores, Adreno/Mali GPU, Memory Tiers)"]
        KleidiAI["Arm KleidiAI Engine<br/>(NEON, DotProd, I8MM Instruction Detection)"]
        TpsPredictor["TpsPredictionEngine<br/>(Self-Calibrating Benchmark & TPS Forecaster)"]
    end

    subgraph TelemetryGuardrails ["Hardware Guardrails & Context Manager"]
        ContextMgr["ChatTemplateEngine & ContextWindowManager<br/>(6 Model Families, Think-Stripping, Budget Pinning)"]
        Thermal["DeviceThermalMonitor<br/>(Dynamic Thread Scaling)"]
        Power["DevicePowerMonitor<br/>(Battery Saver & <15% Power Gating)"]
        MemoryGuard["MemoryLimiterKillGuard & ModelHibernationManager<br/>(LMK Interception & 5-Min Idle Eviction)"]
    end

    LocalAIApp --> LocalInference
    CustomApp --> LocalInference
    LocalInference --> EngineRouter
    EngineRouter --> LlamaEngine
    EngineRouter --> LiteRTEngine
    EngineRouter --> AiCoreEngine

    LlamaEngine --> SiliconProfiling
    LiteRTEngine --> SiliconProfiling
    AiCoreEngine --> SiliconProfiling

    LlamaEngine --> TelemetryGuardrails
    LiteRTEngine --> TelemetryGuardrails
    AiCoreEngine --> TelemetryGuardrails
Loading

How It Works

1. Tri-Engine Runtime & Auto-Routing

Rather than locking your application into a single inference backend, android-inference-engine provides a polymorphically dispatched tri-engine layer:

  • LlamaCppEngine: Designed for universal GGUF model execution. It utilizes native C++ bindings optimized for ARM64 and 32-bit architectures, automatically applying a 1.1GB memory ceiling guard on 32-bit processes.
  • LiteRTEngine: Bridges to Google's official on-device runtime distributed through Google Play Services. It provides an automated 3-tier delegate fallback strategy (System NPU -> System GPU -> Bundled CPU), guaranteeing execution across diverse Android device tiers.
  • AiCoreEngine: Integrates with Android 14+ system-level AICore. It requires 0 MB added to your APK download size, communicating directly with on-device system models like Gemini Nano for turn-key summarization, rewriting, and proofreading.
  • Automatic Routing: The InferenceEngineRouter inspects model files and identifiers. If a local file begins with the GGUF magic bytes, it routes to LlamaCppEngine; if it begins with TFL3, it routes to LiteRTEngine; if an AICore model ID is provided, it seamlessly delegates to AiCoreEngine.

2. Silicon Profiling & Arm KleidiAI

Hardware capabilities vary wildly across Android devices. HardwareProfiler automatically detects and adapts to the host silicon:

  • Instruction Set Architecture: Reads /proc/cpuinfo to detect ARM features including dotprod, i8mm, fp16, and sve. When available, it activates specialized Arm KleidiAI micro-kernels that drastically reduce matrix multiplication overhead.
  • Core Allocation: Identifies the big.LITTLE core topology, determining the exact number of high-performance cores (perfCores). It pins compute threads to performance cores while keeping efficiency cores free to handle UI rendering and background OS tasks.
  • GPU Profiling: Identifies Qualcomm Adreno and ARM Mali GPUs to compute the optimal number of transformer layers to offload into VRAM without triggering device out-of-memory errors.

3. Multi-Token Prediction & Speculative Decoding

In traditional autoregressive generation, each token requires a full sequential forward pass through the entire neural network. android-inference-engine supports Multi-Token Prediction (MTP) and speculative decoding:

  • A compact draft model or speculative head generates candidate token sequences rapidly.
  • The primary base model validates all candidate tokens simultaneously in a single matrix evaluation.
  • This results in a measured throughput gain of $1.5\times$ to $3\times$ tokens per second on supported mobile chipsets without degrading output quality.

4. Multi-Family Chat Templating & Think-Stripping

Proper tokenizer prompt formatting is critical for local models to generate high-quality responses:

  • 6 Supported Model Families: ChatTemplateEngine automatically formats conversations according to the official specifications for Llama 3, ChatML (Qwen, DeepSeek), Gemma, Phi, Mistral/Llama-2, and Generic.
  • Reasoning Models & Think-Stripping: When executing reasoning models (such as DeepSeek-R1 Distill), intermediate reasoning tokens wrapped in <think>...</think> tags are isolated or stripped automatically according to application preference.
  • Context Window Management: ContextWindowManager dynamically calculates token budgets. When a conversation nears the model's context ceiling, it applies sliding-window trimming while pinning system instructions and vital reference documents.

5. Enterprise Guardrails & Hardware Protection

Unconstrained LLM inference can quickly overheat mobile chipsets or drain batteries. android-inference-engine introduces proactive system protection:

  • Thermal Throttling: Listens to Android system thermal status. As thermal load rises, the engine dynamically downscales active thread counts and shedding GPU layers to keep device temperatures safe.
  • Power Gating: Monitors battery state via DevicePowerMonitor. Inference is gracefully halted or throttled if battery reserves fall below 15% (unplugged) or when the user enables Android Battery Saver.
  • Low-Memory Killer Prevention: Intercepts ComponentCallbacks2.onTrimMemory events via MemoryLimiterKillGuard, releasing context caches before the OS invokes the Low-Memory Killer.
  • Idle Hibernation: Automatically releases native model contexts after 5 minutes of inactivity, freeing hundreds of megabytes of RAM while preserving rapid wake-up capabilities.

Getting Started

Adding the Dependency

Add android-inference-engine to your module's build.gradle.kts:

dependencies {
    implementation("io.github.localai:android-inference-engine:1.0.0")
}

Ensure your project targets minSdk = 26 (Android 8.0+) or higher and uses Java 17 compatibility.


Quickstart: Initialize & Stream Inference

Thanks to the unified LocalInference facade, initializing hardware detection, loading a model, and streaming generated tokens requires only a few lines of Kotlin:

// 1. Resolve engine and load model weights with GPU acceleration
val engine = LocalInference.createEngine(context, EngineType.LLAMA_CPP)
val isLoaded = engine.loadModel(
    modelPath = "/sdcard/Download/Llama-3.2-1B-Instruct-Q4_K_M.gguf",
    modelId = "meta-llama/Llama-3.2-1B-Instruct",
    options = EngineOptions(useGpu = true, threadCount = 4)
)

// 2. Stream generated response tokens via Kotlin Coroutines Flow
if (isLoaded) {
    val prompt = LocalInference.formatChatPrompt("meta-llama/Llama-3.2-1B-Instruct", null, messages)
    engine.generateResponses(prompt).collect { token ->
        print(token)
    }
    engine.unloadModel()
}

On-Device Model Compatibility Matrix

Model Family Target Sizes Format & Quantization Engine Backend Acceleration Delegates Context Window Mobile Capabilities
Llama 3.2 1B, 3B GGUF (Q4_K_M, Q8_0) LlamaCppEngine Vulkan GPU, ARM NEON Up to 128K High-throughput mobile chat, autonomous agent routing
Gemma 2 2B, 9B GGUF, LiteRT (.litertlm) LiteRTEngine / LlamaCppEngine Mobile NPU (Hexagon/APU), GPU 8K sliding Multi-Token Prediction (MTP) speculative decoding
Qwen 2.5 0.5B, 1.5B, 3B, 7B GGUF (Q4_K_M, Q5_K_M) LlamaCppEngine ARM KleidiAI, Vulkan 32K Multilingual chat, structured JSON, tool-use calls
DeepSeek-R1 1.5B, 7B (Distill) GGUF (Q4_K_M) LlamaCppEngine ARM DotProd / I8MM 16K Chain-of-thought <think> tags with auto-stripping
Gemini Nano System-managed OS unbundled package AiCoreEngine Android AICore / NPU OS Budgeted Turnkey zero-MB APK summarization, rewrite, proofreading

Engine Configuration Options

The EngineOptions data class configures hardware acceleration and sampling behavior:

Option Type Default Description
useNpu Boolean true Enables NPU hardware acceleration delegates when supported by the device.
useGpu Boolean true Enables GPU acceleration (Qualcomm Adreno OpenCL or ARM Mali Vulkan).
threadCount Int 4 Number of compute threads dedicated to matrix multiplication.
temperature Float 0.7f Sampling temperature controlling randomness of generation.
topK Int 40 Top-K sampling cutoff restricting next-token candidates.
topP Float 0.95f Nucleus sampling probability mass threshold.
repeatPenalty Float 1.1f Penalty factor applied to discourage repetitive token loops.
useMtp Boolean false Enables Multi-Token Prediction speculative decoding on supported models.
maxTokens Int 1024 Maximum token budget for the completion response.

Sample Application

A demonstration Android application is included in the sample directory. It showcases:

  1. Detecting mobile silicon capabilities, ARM extensions, and KleidiAI compatibility.
  2. Computing the optimal hardware tier, recommended GPU layers, and performance core thread counts.
  3. Formatting multi-turn conversations into model-specific chat templates.
  4. Rendering hardware telemetry and prompt previews in real-time.

To build and run the sample application on a connected device or emulator:

./gradlew :sample:installDebug

SEO & Keywords

android-on-device-ai, mobile-llm-inference, llama-cpp-android, litert-npu-acceleration, gemini-nano-aicore, arm-kleidiai-android, gguf-android, edge-ai-runtime, on-device-deepseek, speculative-decoding-android, mobile-neural-engine, local-ai-mobile, android-hardware-profiler, quantized-models-android, zero-cloud-llm


Contributing & Security

We welcome community contributions, hardware delegate optimizations, and model family templates!

  • Contributing: Please review CONTRIBUTING.md for environment setup, architecture standards, and contribution guidelines.
  • Security Policy: For vulnerability disclosures, please review SECURITY.md and contact us directly at security@shanaka.dev.

Contact & Support


License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Copyright 2026 Local AI Mobile (https://github.com/local-ai-mobile)
Part of the Local AI Project (https://localai.shanaka.dev/)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

About

Production-grade, 100% on-device AI inference engine for Android (llama.cpp GGUF, LiteRT NPU/GPU, Gemini Nano AICore).

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages