On-Device LLM Deployment in Practice: Architecture Design and Lessons Learned for Mobile Local Agents

    This article explains how to deploy large language models on mobile devices for local AI agents. It examines why on-device inference matters, how extra abstraction layers can lead to device-level failures, how to integrate official native inference APIs directly, how to manage long-lived engines and short-lived conversations, how to coordinate concurrent agents, and which engineering practices help deliver stable on-device AI.

    1. Why On-Device LLMs Are Worth Investing In

    Over the past year, the focus of large language model deployment has gradually shifted from the cloud to end devices. For teams building mobile AI assistants, local knowledge-management tools, or privacy-sensitive products, running models on the device means three practical benefits: data never leaves the device, offline availability when the network is unreliable or unavailable, and better long-term economics by avoiding cloud inference costs. As a result, lightweight on-device models—often differentiated by parameter size and quantization precision—have become the core foundation for local agent products.

    However, “getting a model onto a phone” and “running the model smoothly and reliably on the phone” are two very different problems. The first is mostly copying files; the second involves memory management, compute scheduling, lifecycle control, and concurrency coordination. This article reviews the lessons learned from the second problem, and the findings are relevant to most teams attempting on-device deployment.

    2. First Detour: System-Level Instability Introduced by a Wrapper

    At first, the team prioritized development speed and used a community-maintained cross-platform plugin package. Such plugins aim to wrap native inference engines behind a simpler unified API, allowing application developers to avoid dealing with platform-specific details. The API was clean, but runtime behavior was alarming: the app did not merely crash occasionally; the entire phone would sometimes go black and reboot.

    This distinction is important. A normal application crash is usually contained within a process boundary, and the operating system can catch and recover from it. A full-device reboot suggests that the problem has penetrated to the operating system kernel or hardware-resource layer. Such failures are often caused by native memory corruption, invalid memory access, or serious exceptions in the GPU driver layer.

    The debugging approach was straightforward. On the same device and with the same model file, the team ran an official reference application provided by the engine vendor. It remained stable. That isolated the issue to the extra wrapper layer. A reasonable conclusion was that the community plugin maintained an additional bridge and state-conversion layer between the cross-platform runtime and the native engine. That layer likely had edge cases around large model memory, asynchronous callbacks, or compute-backend switching that were not fully covered.

    The lesson is clear: in on-device AI scenarios that are highly sensitive to memory and hardware, abstraction layers should not be made excessively thin, nor should they be made overly complex. Third-party wrappers often hide many assumptions for the sake of generality. If those assumptions do not match the target device, model size, or concurrency model, the cost can be a system-level failure.

    3. Correct Approach: Call Official Native Inference Interfaces Directly

    After dropping the intermediate plugin, the team wrote its own native bridge and called the official native inference library provided by the engine vendor. The architecture became clearly layered:

    1. Cross-platform UI layer (business/interaction)
    2. │ Platform channel (method calls + event stream)
    3. ▼
    4. Native inference plugin (in-house, thin wrapper)
    5. ▼
    6. Official on-device inference engine (model loading and operator scheduling)

    Here, the platform channel is the cross-platform framework’s general native bridging mechanism. The UI layer sends instructions through method calls, while the inference engine streams tokens back to the UI layer through an event stream. The key point is that the in-house bridge performs only the most necessary pass-through work and avoids extra state management and memory copies. Stability and memory control are returned to the official engine.

    After the switch, two problems disappeared at once: inference speed returned to normal, and full-device reboots no longer occurred. This also confirmed the earlier judgment: the root cause was not the model or the hardware, but the overly wrapped bridge logic.

    4. Core Design: Singleton Inference Engine with On-Demand Conversations

    Once inference worked reliably, resource management became the next priority. The first principle of on-device deployment is: expensive initialization should happen only once, while lightweight calls should be created on demand.

    Loading a model is an expensive operation. It requires reading weight files of one or more gigabytes into memory and moving them to accelerators such as GPUs or NPUs. This process takes time and consumes memory. Therefore, the inference engine should exist as a process-level singleton and be initialized only once during its lifecycle. Each individual conversation can be represented by a lightweight conversation object that is released immediately after use. This separation avoids repeated loading overhead and prevents conversation state from accumulating over a long-lived process.

    The example code below uses generic interface names:

    1. // Inference engine: process-wide singleton; expensive initialization runs only once
    2. object LocalInferenceEngine {
    3. lateinit var engine: InferenceEngine
    4. fun init(modelPath: String, maxTokens: Int, cacheDir: String) {
    5. // Load the model into device memory or accelerator; do this only once
    6. engine = InferenceEngine(
    7. modelPath = modelPath,
    8. backend = Backend.GPU(), // Compute backend can be GPU, NPU, or CPU
    9. maxNumTokens = maxTokens,
    10. cacheDir = cacheDir
    11. )
    12. engine.initialize()
    13. }
    14. // Create a lightweight conversation on demand for each inference task and close it when done
    15. fun newConversation(cfg: ConversationConfig) = engine.createConversation(cfg)
    16. }
    1. // Call site: release the conversation immediately after creation
    2. engine.newConversation(cfg).use { conversation ->
    3. conversation.sendMessageAsync(userText).collect { token ->
    4. // Stream tokens back to the UI layer through the platform channel
    5. }
    6. }

    What is even more valuable than “singleton engine plus on-demand conversations” is an abstraction that is fully transparent to the application layer. The team defined a unified client interface for local implementations that matched the cloud provider interface exactly:

    1. interface LLMClient {
    2. fun streamChat(messages: List<Message>): Flow<String>
    3. }
    4. class LocalLLMClient : LLMClient { /* On-device implementation */ }
    5. class CloudLLMClient : LLMClient { /* Cloud implementation */ }

    This way, upper-layer agents do not need to know whether the model runs locally or in the cloud. Switching requires changing only one configuration field. This “program against an interface and switch through configuration” design is the engineering foundation of a hybrid edge-cloud architecture: local deployment handles privacy and offline use, the cloud handles fallback and complex tasks, and business code remains unified.

    5. Multi-Agent Concurrency: Global Lock and Scheduling Strategy

    The real complexity appears during concurrency. A mature local assistant often runs multiple agents at the same time: one processing card information, one maintaining a knowledge base, and another analyzing images or audio. They all need to call the same inference engine, but there is only one engine instance and limited memory or GPU memory.

    If multiple agents call the engine concurrently without control, the lighter outcome is a memory peak that triggers system reclamation; the more serious outcome is a return to the earlier full-device reboot problem. The safest fallback is to introduce a global mutex lock and serialize inference requests:

    1. val engineLock = Mutex()
    2. suspend fun runAgent(task: AgentTask) = engineLock.withLock {
    3. engine.newConversation(task.cfg).use { conversation ->
    4. conversation.sendMessageAsync(task.prompt).collect { token ->
    5. // Process streaming output
    6. }
    7. }
    8. }

    The global lock sacrifices concurrency but provides determinism and stability. In on-device scenarios, this trade-off is usually worthwhile. If higher throughput is required, this approach can evolve into a priority-based request queue. Foreground interactive agents can use high priority, while background batch agents use low priority, with a scheduler managing the queue rather than a single lock blocking all requests. In either case, the core idea is to accept that on-device compute is limited and to make concurrency control explicit instead of hoping the engine will handle it automatically.

    6. Lessons Learned

    Looking back at the whole process, several principles apply broadly to on-device LLM deployment:

    • Be wary of excessive wrapping: For low-level capabilities that are sensitive to memory and hardware, call the official native interfaces directly and keep stability in your own control.
    • Use official reference implementations for controlled experiments: When a crash is hard to locate, use the minimum-variable method—same device, same model, different implementation—to identify the root cause quickly.
    • Make expensive initialization a singleton and create lightweight conversations on demand: This is the basic pattern for on-device resource management.
    • Decouple local and cloud through a unified interface: Let the business layer switch transparently, balancing privacy, offline use, and cloud fallback.
    • Concurrency must be explicitly controlled: A global lock is a stable starting point, while a priority queue is an advanced direction.

    For complex tasks that require cloud capabilities as a fallback, the architecture can reserve a channel to connect to cloud large model services. Cloud platforms such as Baidu AI Cloud can provide general-purpose cloud capabilities such as model services, object storage, and logging/monitoring as a supplement to on-device solutions. The device handles real-time, private, and offline basic experiences, while the cloud handles heavy computation and knowledge augmentation on demand. This edge-cloud collaboration is becoming the mainstream form of local agent products.

    On-device large models are no longer just lab demonstrations; they can be stable engineering solutions. Every pitfall encountered ultimately becomes reusable architectural experience—and that is the main value this article wants to convey.