Mobile On-Device LLM Deployment: From Inference Wrappers to Concurrency Scheduling
Deploying large language models (LLMs) on mobile devices presents unique challenges in resource management and stability. This article details practical strategies for on-device LLM deployment, covering layered architecture design, trade-offs between inference wrappers and native APIs, model lifecycle management, unified client abstraction, and concurrency scheduling for multi-agent systems.
1. Background: Why Run LLMs on Mobile Devices?
Cloud-based inference has three inherent issues: network dependency, the requirement to upload user data, and usage-based billing. Moving inference to terminal devices allows sensitive data such as personal notes, images, and recordings to remain local. These scenarios demand high offline availability; for example, in environments without network access, applications should still be able to organize diaries and retrieve local knowledge bases.
The constraints of mobile devices are equally clear. Memory capacity is limited, storage space is tight, the CPU, GPU, and NPU share the same power and thermal budget, and the operating system will reclaim resources in the background. Therefore, the core challenge of on-device solutions is not whether the model can run, but whether it can run long-term, stably, and controllably.
2. Overall Architecture: Layered Design
It is recommended to split on-device inference into four layers, with each layer taking on a single category of responsibility:
Business Layer (Agent scheduling, prompt assembly, result parsing)│ Unified LLMClient InterfaceLocal Client Adapter Layer (Parameter conversion, session management, timeout and cancellation)│ Cross-language message channelNative Inference Layer (Model loading, hardware backend selection, Token generation)│Device Hardware (CPU / GPU / NPU)
The Business Layer only cares about “giving the model an input and getting an output” and should not know the model file path or hardware backend. The Adapter Layer is responsible for translating business requests into parameters for the inference engine and managing the creation and release of sessions. The Native Inference Layer directly calls the inference library provided by the device platform, which is the most resource-intensive and error-prone part. The differences in the Hardware Layer are shielded by the inference library, and the upper layers do not need to perceive them.
The benefit of layering is replaceability. Cloud services and local models can share the business layer code; switching only requires changing the implementation and configuration of the adapter layer.
3. Trade-offs: Wrapper Layer vs. Native Interface
Cross-platform UI frameworks typically offer various plugins that wrap native inference libraries into simpler interfaces. A wrapper layer improves development efficiency, but every added layer introduces new uncertainties regarding object lifecycle, memory references, and thread switching.
In practice, we encountered a typical issue: when calling local inference through the wrapper layer, the device occasionally rebooted entirely, though the application itself did not crash. Running the same model file on the same device within the inference library’s official sample app worked perfectly. The exact root cause was not fully confirmed, but the problem clearly occurred at the junction between the wrapper layer and the native inference library.
After switching to direct native interface calls, the problem disappeared, and inference speed returned to normal. The comparison between the two approaches is as follows:
| Dimension | Via Wrapper Layer | Direct Native Interface Call |
|---|---|---|
| Development Efficiency | High, simple interface | Medium, requires maintaining platform-specific code |
| Stability | Depends on wrapper quality, hard to troubleshoot | Consistent with official samples, easy to cross-check |
| Lifecycle Control | Indirect, prone to resource retention | Explicit, creation and release are clearly visible |
| Upgrade Cost | Requires wrapper maintainer to follow new versions | Directly follows inference library updates |
Conclusion: For critical paths like inference, which consume heavy resources and take a long time, you should prioritize connecting directly to the official native interface and keeping the adapter layer thin, responsible only for parameter conversion.
4. Model Lifecycle: Heavy Resource Singleton, Light Resource On-Demand
On-device models are large in size, and loading them once consumes several GBs of memory and storage; therefore, the engine should be a singleton. Session objects are relatively lightweight and suitable for creation during each inference and immediate release afterward.
There are three core principles:
- Initialize the engine only once. The loading process is time-consuming and consumes a large amount of memory; it should not be executed repeatedly for every request.
- Create sessions on demand and close them immediately. Sessions save context state; failing to close them promptly leads to continuous memory growth.
- Release the old engine before switching models. The simultaneous existence of old and new engines will double the memory peak, easily triggering system reclamation.
The pseudocode example is as follows:
class LocalModelRuntime:engine = Nonedef ensure_loaded(model_path, backend, max_context):if LocalModelRuntime.engine is None:engine = create_engine(model_path=model_path,backend=backend,max_context_tokens=max_context,)engine.initialize()LocalModelRuntime.engine = enginereturn LocalModelRuntime.enginedef generate(prompt, options):engine = LocalModelRuntime.enginewith engine.new_session(options) as session:for chunk in session.stream(prompt):yield chunk # Streaming output, session auto-released at the end of the with blockdef unload():if LocalModelRuntime.engine is not None:LocalModelRuntime.engine.close()LocalModelRuntime.engine = None
The upper limit of the context length should not simply be set to the maximum value supported by the model. A higher limit means larger memory consumption and longer single-inference time. It is recommended to determine a conservative value based on the tested memory headroom of the target device, and perform long-text truncation or segmentation in the business layer.
5. Unified Client Abstraction: Shielding Local vs. Cloud Differences
The business layer should rely only on a unified interface, regardless of whether the underlying layer is a local model or a cloud service:
interface LLMClient:complete(request) -> Responsestream(request) -> AsyncIterator<Chunk>capabilities() -> Capabilities # Max context, stream support, structured output support
The capabilities() method is easily overlooked but very important. The context window of local models is usually smaller than that of cloud models, and they may not support all output formats. The business layer should read the capability declaration first before deciding the prompt length and output constraints, rather than assuming all backends behave identically.
With a unified interface, switching backends only requires modifying configuration items. Business code does not need to determine the current model type, nor does it need to write separate branches for local scenarios.
6. Multi-Agent Concurrency: Scheduling is More Important Than Acceleration
In real-world applications, multiple agents usually work simultaneously. For example, a card agent processes user input, a knowledge base agent organizes structured information, and a media analysis agent handles images and audio. If they call the same local engine simultaneously, the following problems occur:
- Multiple sessions compete for the same computing resources, slowing down inference for each other;
- Memory peaks overlap, easily triggering system reclamation;
- Foreground interactive requests are blocked by background batch tasks, causing noticeable lag.
There are three common response strategies:
| Strategy | Approach | Pros | Cons |
|---|---|---|---|
| Independent Engine per Agent | Each loads the model | Good isolation | Memory multiplies, largely unfeasible |
| Global Mutex Lock | Only one inference allowed at a time | Simple implementation, safe results | Low-priority tasks may wait a long time |
| Priority Queue + Single Worker Thread | All requests enter the queue, dequeued by priority | Balances safety and responsiveness | Requires maintaining scheduling logic |
The third strategy is recommended. A global lock ensures safety but does not distinguish task urgency. A priority queue allows requests the user is actively waiting for to execute first, while background batch processing completes during idle periods.
A schematic implementation of the scheduler is as follows:
class InferenceScheduler:queue = PriorityQueue() # Elements are (priority, sequence number, task, result handle)seq = 0def submit(task, priority, timeout):future = Future()seq += 1queue.put((priority, seq, task, future)) # Sequence number ensures same-priority tasks execute in submission orderreturn futuredef run_loop(): # Only one worker thread, serial access to the enginewhile True:_, _, task, future = queue.get()if future.is_cancelled() or future.is_expired():continuetry:future.set_result(task.run())except Exception as err:future.set_exception(err)
Priorities should be divided by scenario: direct user interactive requests are highest, background generation tasks are in the middle, and batch analysis like images and audio are lowest. Batch tasks should also have execution windows, such as running only when the device is charging and idle.
7. Stability, Resources, and Degradation Strategies
Memory Monitoring. Upon receiving a low-memory notification from the system, immediately unload non-essential engines and cancel low-priority tasks. The next request will then reload, trading an extra loading delay for overall stability.
Temperature and Power. Sustained full-load inference will heat the device, causing the system to throttle frequencies, which actually decreases speed. There should be intervals between batch tasks, and background tasks should be paused when the device temperature is high.
Timeout and Cancellation. Every session should have an upper limit. When the user leaves the page or closes the feature, the corresponding task should be canceled to avoid inference spinning in the background.
Degradation Path. When local inference fails, the application can provide a clear prompt or switch to a cloud service if authorized by the user. Degradation behavior must be visible in the UI and cannot be silently replaced, to prevent users from mistakenly thinking their data is still being processed locally.
Observability. When troubleshooting on-device issues, you need to log the model version, backend type, device model, system version, context length, and session duration. Without this information, it is difficult to reproduce and attribute the same type of exception.
8. Common Issues and Checklist
Before going live, you can confirm the following items one by one:
- Is the inference engine initialized only once, and is the old instance released when switching models?
- Does every session have a clear close timing, including exception paths?
- Is the context length upper limit based on device-tested values rather than model nominal values?
- Do multiple agents share the same scheduler instead of accessing the engine independently?
- Is there a priority distinction between foreground requests and background batch processing?
- Are system low-memory notifications monitored and responded to?
- When an exception occurs, is there enough log information available to locate the problem?
9. Conclusion
The engineering challenges of on-device large models focus on three areas: the stability of the inference path, lifecycle management of resources, and scheduling in multi-task scenarios. While wrapper layers can speed up development, direct connection to native interfaces is more controllable on resource-intensive critical paths. Engine singleton, on-demand sessions, a unified client interface, and priority scheduling constitute a proven basic architecture. Implementing this approach can ensure stable and predictable local AI capabilities while protecting user data.
