On-Device LLM Deployment: From Integration Pitfalls to Stable Local Inference

    This article shares practical engineering lessons from integrating a local large language model into a privacy-sensitive mobile knowledge management app. It covers runtime selection, a layered abstraction architecture, native API integration, model loading and memory management, inference scheduling under multi-agent concurrency, and future optimization directions, with the goal of helping similar projects move from a working model to stable production inference.

    In recent years, demand for deploying open-source large models on edge devices has grown rapidly. For mobile applications focused on privacy-sensitive scenarios, fully offline local inference not only eliminates network latency but also fundamentally avoids the risk of data leaving the device. However, moving from “the model runs” to “stable operation in production” involves a large number of engineering challenges. This article is based on a real-world experience of integrating a local large model into a personal knowledge management application. It systematically reviews key technical decisions and pitfalls to provide a reusable reference path for similar projects.

    1. Runtime Selection for Local Inference

    At the beginning of the project, the technical team faced a primary question: how can a model with several GB of parameters run efficiently on resource-constrained mobile devices? The mainstream approaches in the industry fall into two categories. One is to wrap the underlying inference engine with a cross-platform framework and expose capabilities to the application layer through a unified API. The other is to directly call the native runtime interfaces provided by chip vendors or operating systems.

    The former has a lower barrier to entry and less code intrusion, making it suitable for rapid prototyping. The latter offers a higher performance ceiling and better system compatibility, but requires developers to have solid low-level engineering skills. This is essentially a trade-off between development efficiency and runtime stability. For a product whose core selling point is “data never leaves the device,” stability clearly has higher priority.

    2. Overall Architecture: Layered Decoupling and Transparent Switching

    To balance development efficiency and long-term maintainability, we established a three-layer architecture principle: business layer, abstraction layer, and implementation layer. The multi-agent collaboration system in the business layer is programmed entirely against abstract interfaces and does not know the specific source of the underlying model. The abstraction layer defines a unified session interaction protocol covering basic operations such as message sending, streaming reception, and generation cancellation. The implementation layer dynamically binds to either a cloud API client or a local inference engine depending on the runtime mode.

    1. // Abstract protocol definition
    2. interface LocalInferenceClient {
    3. suspend fun sendMessage(content: String): Flow<String>
    4. fun resetSession()
    5. fun release()
    6. }

    The direct benefit of this design is that business-layer code requires zero changes when switching model providers or inference backends. To add a new local inference implementation, we only need to write the corresponding adapter and register it in the configuration. In actual testing, switching all agents’ model targets from cloud to local required changing only one configuration file, and the whole process took less than five minutes.

    3. Breaking Out of the Stability Trap of Black-Box Wrappers

    3.1 System-Level Crashes Caused by a Cross-Platform Framework

    Initially, we tried to accelerate integration with an existing plugin from the cross-platform ecosystem. The plugin did provide a concise declarative interface, and model loading and dialogue generation could be completed with just a few lines of code. However, stress testing on real devices revealed a very serious defect: after multiple consecutive inferences, the entire operating system would occasionally restart, not just the process crash.

    Further investigation showed that the plugin wrapper had flaws in its memory allocation and release strategy. When the application layer quickly created and destroyed inference sessions, the GPU buffers held by the underlying engine were not reclaimed in time, eventually triggering the system-level memory protection mechanism. At the same time, because the framework’s thread scheduling competed with the inference engine’s internal thread pool, certain timing sequences could trigger low-level exceptions that could not be caught.

    3.2 Returning to Native Interfaces: A Fundamental Guarantee for Stability

    Given these lessons, we decided to abandon the indirect wrapper layer and directly call the native inference API through a platform channel. This required maintaining some glue code on both the host side and the application side: the host side was responsible for modeling the engine lifecycle, session management, and tensor data transfer, while the application side communicated with the host through an asynchronous message channel.

    The new architecture strictly follows the principle of “singleton engine, dynamic sessions.” The model resides in memory as a singleton and is loaded only once. Each conversation creates an independent lightweight session object, which is destroyed immediately after use. This pattern has three advantages:

    • Controllable memory usage: keeping the engine resident avoids fragmentation caused by repeated loading and unloading;
    • Clear lifecycle: session creation and release are explicitly managed by the caller, preventing implicit leaks;
    • Stable inference speed: GPU context reuse significantly reduces cold-start latency.
    1. // Engine singleton initialization flow
    2. val engineConfig = EngineConfig(
    3. modelPath = localPath,
    4. backend = Backend.GPU(),
    5. maxSequenceLength = 4096,
    6. workingDir = context.cacheDir.absolutePath
    7. )
    8. engine = Engine.create(engineConfig).apply { initialize() }
    9. // Lightweight session usage pattern
    10. engine.newSession().use { session ->
    11. session.respondAsync(prompt).collect { token ->
    12. emit(token)
    13. }
    14. }

    After the refactor, long-duration stress tests no longer produced system restarts or process crashes. This confirmed a key conclusion: trading performance for convenience is often a losing proposition in low-level scenarios.

    4. Key Details of Model Loading and Memory Management

    4.1 Loading Time and Memory Watermark

    On a flagship test device, cold-start loading of a quantized model of about 2.6 GB took between several hundred milliseconds and several seconds, depending on flash read speed and GPU memory capacity. We adopted a “preload at startup” strategy, moving model initialization forward to the application welcome screen display stage to hide the loading cost. We also recommend enabling memory compression or a lower-load fallback on low-end devices to avoid inference failures caused by insufficient GPU memory.

    4.2 Session Lifecycle Management

    In actual development, illegal reuse of session objects must be prevented. When an agent needs multiple rounds of tool calls, it should maintain a dedicated long-lived session. For one-shot question-answering tasks, short sessions should be used and released promptly. In our practice, we maintain an independent session collection for each agent and use reference counting to automatically reclaim idle resources.

    5. Inference Scheduling Under Multi-Agent Concurrency

    5.1 The Necessity of a Global Lock

    When multiple agents process different types of tasks in parallel in the background, multiple inference requests arriving at the underlying engine at the same time will cause resource contention. Although some native runtimes claim to support concurrent inference, their thread-safety boundaries are often not sufficiently verified. In initial concurrency tests, we did encounter occasional deadlocks and disordered token generation.

    The final solution was to introduce a global mutex at the inference executor layer to ensure that only one inference task occupies the GPU at a time. Combined with a priority queue, core interactive tasks can receive higher scheduling priority.

    1. class InferenceGate {
    2. private val mutex = Mutex()
    3. suspend fun <T> execute(block: suspend () -> T): T =
    4. mutex.withLock { block() }
    5. }

    5.2 Quantifying the Latency-Throughput Balance

    Some colleagues questioned whether a global lock would reduce throughput. In fact, on edge devices, the throughput bottleneck is usually the model’s decoding speed rather than lock contention. In comparison, avoiding concurrent GPU access that causes thermal throttling is more effective in ensuring stable inference speed over long periods. Log analysis showed that after enabling the global lock, the waiting time for a single task increased by less than 5%, but overall system uncertainty was significantly reduced.

    6. Future Optimization Directions

    The current implementation already meets the requirements of a fully offline product, but the following areas still have room for evolution:

    • Model shard loading: For very large models, load Transformer layer submodules on demand to balance memory usage and loading latency;
    • Heterogeneous compute scheduling: Dynamically switch between GPU and NPU/CPU backends based on task characteristics, such as using low-power units like CPU for short-text tasks;
    • Streaming parsing optimization: A streaming parsing pipeline decoupled from inference to improve parallelism between token rendering and UI updates.

    From the initial “out-of-the-box” approach to the final “deep in-house implementation,” this technical path once again confirms a simple principle: in on-device AI engineering, flexibility always has more long-term value than convenience. Understanding the underlying runtime mechanism and conducting sufficient stability testing are what allow local large models to become reliable product capabilities.