How to Run Open-Source LLMs on Mobile: An Offline Inference Implementation and Pitfall Log

    This article describes how a team added fully offline LLM inference to a local-first AI life-logging and knowledge-management app. It explains the move away from user-configured cloud API keys, the OS-level reboot issue caused by a cross-platform plugin wrapper, and the rebuilt architecture using Platform Channel, a native engine singleton, short-lived sessions, streaming tokens, and a global lock for multi-Agent concurrency. It concludes with practical lessons for production on-device inference.

    1. Background: Why Run LLMs on Mobile

    Our team is building a fully local AI personal life-logging and knowledge-management app. All user data is stored on the device and never passes through any cloud. In the previous architecture, the app’s LLM capability depended on users configuring API keys for cloud services themselves and choosing among several general-purpose LLM providers.

    This model had two clear problems:

    1. Privacy and offline availability: once users are in a no-network environment, or do not want to send any data to the cloud, core features fail completely.
    2. Barrier to use: users needed to apply for and manage API keys. For a product positioning that emphasizes “data never leaves the device,” cloud dependency itself was an architectural compromise.

    We therefore decided to add a fully offline inference option: the model is packaged or downloaded directly to the device, and inference runs entirely on the phone without any cloud service. In recent years, small open-source models in the 1B–5B range have become capable enough on device hardware for tasks such as summarization, extraction, classification, and lightweight Agent orchestration. That made our approach feasible.

    2. First Attempt: A Cross-Platform Plugin Wrapper Caused Full-Device Reboots

    To save development effort, we first chose a community-maintained plugin for our cross-platform framework. It wrapped the low-level capabilities of an on-device inference engine, and its API was simple: a demo could run in a few dozen lines of code.

    After real-device integration, however, a serious problem appeared: during inference, the phone would occasionally go black and reboot. This was not an app crash; it was an operating-system-level reboot.

    We ran simple control tests:

    • On the same device with the same model file, the official native sample app ran completely stably.
    • Only the path wrapped by the cross-platform plugin triggered the reboot.

    The difference was the call chain. The official sample used platform-native APIs to drive the inference engine directly, while the plugin added a cross-platform bridge layer. In that bridge, memory allocation and release, thread ownership, and ownership of GPU resources could all change. On-device inference engines rely heavily on low-level GPU and NPU capabilities. If the bridge released a GPU context on the wrong thread, or native memory was incorrectly reclaimed by the cross-language runtime, a system-level resource anomaly could occur and trigger a full-device shutdown and reboot.

    The conclusion was clear: the stability risk was unacceptable. We had to bypass that wrapper and integrate directly with the official native engine interface.

    3. The Right Approach: Platform Channel Directly to the Native Inference Engine

    3.1 Architecture Design

    The main mobile app is built on a cross-platform framework, but the inference engine must run natively. We therefore used Platform Channel as the bridge. The overall chain is:

    1. Dart layer (Agent business logic)
    2. ↓ MethodChannel
    3. Native plugin layer (lifecycle management, engine ownership)
    4. ↓
    5. On-device inference engine (GPU acceleration, model loading, token streaming output)

    3.2 Core: Engine Singleton + Sessions Created on Demand

    The native plugin design follows one principle: globally reuse expensive resources, and create lightweight sessions on demand.

    1. // Initialize the Engine only once: load about 2.6GB of model weights into GPU memory
    2. val engine = Engine(
    3. EngineConfig(
    4. modelPath = modelPath,
    5. backend = Backend.GPU(),
    6. maxNumTokens = 10000,
    7. cacheDir = context.cacheDir.absolutePath,
    8. )
    9. )
    10. engine.initialize()
    11. // Create a new conversation (lightweight object) for each inference and release it after use
    12. engine.createConversation(config).use { conversation ->
    13. conversation.sendMessageAsync(userText).collect { token ->
    14. // Stream tokens back to the Dart layer
    15. }
    16. }

    Key design points:

    • Engine singleton: Model loading is the most expensive operation in the entire chain. Reading GB-scale weights into GPU memory takes seconds or longer and consumes a large amount of memory. The engine must be initialized only once during the app lifecycle and must never be created and destroyed per request. Otherwise, latency becomes unacceptable, and frequent GPU memory allocation and release can easily reproduce the system anomalies described above.
    • Short session lifecycle: Session objects such as Conversation hold dialogue context and KV Cache, and they are cheap to create. Create a new session for each request and close it immediately after the request. This avoids context contamination across requests and keeps the memory reclamation path clear and controllable.
    • Streaming output: On-device generation speed is limited, so tokens must be streamed to the upper layer for rendering. Otherwise, the user-perceived waiting time is multiplied.
    • Explicit cache directory: Point the engine’s temporary files to the app cache directory. This complies with platform storage conventions and makes it easy to reclaim them when users clear the cache.

    3.3 An Abstraction Fully Transparent to Upper Layers

    On the Dart side, we implemented a GemmaLocalClient (local inference client) that implements the same LLMClient interface as cloud providers. This design brings significant benefits:

    • Upper-layer Agent orchestration logic is completely unaware of whether inference is local or in the cloud.
    • Switching between local and cloud requires only a one-line configuration change.
    • Local inference can serve as an automatic fallback path when cloud services are unavailable.

    This is also the architecture pattern we strongly recommend: abstract the inference backend behind a unified interface, and make “where inference runs” a deployment configuration rather than a code branch.

    4. Multi-Agent Concurrency: Why a Global Lock Is Necessary

    Our app has multiple Agents working in parallel: a Card Organization Agent handles structured information, a Knowledge Base Agent maintains the personal knowledge system, and an Asset Analysis Agent handles images and audio. After switching to local inference, a new problem surfaced: what happens when multiple Agents send requests to the same local engine at the same time?

    Cloud inference can scale horizontally and naturally supports high concurrency. A device has only one GPU and one loaded set of model weights, so its inference capacity is fixed. We ultimately chose the most conservative and reliable option: a global mutex lock.

    • Only one Agent may occupy the inference engine at a time; other requests wait in a queue.
    • For queueing, priority goes to the main interactive path the user is using, while background batch tasks yield.
    • Each request limits maximum generation length through maxNumTokens, preventing long tasks from occupying the engine for extended periods.

    This choice sacrifices some throughput but provides two important guarantees: predictable GPU memory usage, with no OOM caused by stacked concurrency, and predictable latency, so interactive response times are not crushed by background tasks. In on-device scenarios, predictability matters far more than theoretical throughput.

    5. Pitfalls and Best Practices

    The entire integration took several days. We captured the following lessons:

    1. Prefer official native interfaces for on-device inference. Community cross-platform wrappers are suitable for quick validation, but production environments must evaluate whether their low-level resource management is reliable. For GPU/NPU scenarios in particular, run long-duration stress tests on real devices.
    2. Engine singleton plus short-lived sessions is the most stable resource model. Do not make sessions global and long-lived just for convenience.
    3. Design concurrency around the reality of one GPU and one model. A global lock plus priority queueing is a simple and reliable starting point.
    4. A unified inference abstraction layer lets local and cloud backends be swapped, leaving room for fallback, canary rollout, and cost optimization.
    5. Real devices are the only source of truth. Simulators and high-spec development machines cannot expose memory pressure or system resource conflicts. Long-duration stability testing must be done on mainstream devices used by target users.

    6. Final Thoughts

    This practice confirmed that the combination of small open-source models and on-device inference engines is already sufficient to support a real local Agent product. The current solution meets release-level standards for stability, privacy compliance, and offline availability. The cost is that concurrency and per-request limits are constrained by hardware, but this is exactly the engineering tradeoff that local-first products need to accept. Next, we plan to go deeper into model quantization version selection, first-token latency optimization, and multi-model hot switching. We also welcome exchanges with teams facing similar scenarios.