On-Device LLM Deployment: Inference Stability and Architecture Practices

    This article documents the engineering practice of integrating a lightweight open-source LLM into a local-first personal knowledge management app for fully offline on-device inference. It covers how a wrapper plugin caused device-level instability and how it was diagnosed, a four-layer architecture with singleton engine and per-request sessions, a unified interface for switching between local and cloud models, and global serialization for concurrent multi-agent workloads, along with a troubleshooting checklist.

    1. Background and Goals

    Running a large language model on a mobile device has two direct benefits: data never leaves the device, and no network connection is required. This matters especially for privacy-sensitive data such as personal notes, schedules, photos, and voice recordings. Using a local-first personal knowledge management app as an example, this article documents how to integrate a lightweight open-source model on-device and achieve fully offline inference. It focuses on three questions: stability, layered architecture, and concurrent scheduling.

    The conclusions come from engineering-level observations and apply to other on-device inference scenarios.

    2. Phase One: Stability Risks from the Wrapper Layer

    The initial approach used an off-the-shelf cross-platform UI framework plugin that wraps the underlying inference engine behind a simpler interface. The development experience was good, but sustained inference on real devices exposed a serious problem: the device occasionally went black and rebooted entirely, rather than the app merely crashing.

    An app crash is usually confined to the process, while a full device reboot typically indicates that a memory- or power-related system-level exception triggered a protection mechanism. This suggests the problem was likely related to large memory allocations or hardware accelerator resource usage.

    The diagnosis used a controlled-variable approach: on the same device with the same model file, inference was run through the wrapper plugin and through direct calls to the native SDK. The path calling the native interface directly never triggered a reboot. The specific root cause was not fully identified, but one thing is clear: the longer the call chain, the harder it is to control memory lifecycles, threading models, and resource release timing.

    Therefore, in stability-first scenarios, minimize intermediate layers and integrate directly with the native interfaces provided by the underlying inference engine.

    3. Phase Two: Layered Architecture and Resource Management

    The revised architecture has four layers:

    1. Business layer (Agents, task scheduling)
    2. ↓ Unified LLMClient interface
    3. Cross-language communication channel (parameter serialization, streaming callbacks)
    4. ↓
    5. Native plugin layer (lifecycle management, session creation)
    6. ↓
    7. Inference engine (model loading, GPU computation)

    3.1 Singleton Engine: Load the Model Only Once

    Model files often reach several gigabytes. Loading consumes substantial memory and VRAM and takes considerable time. The engine should therefore be a process-level singleton, initialized on first use and reused afterward.

    1. // Illustrative pseudocode, not the real interface of any specific SDK
    2. class InferenceEngineHolder:
    3. instance = null
    4. lock = Mutex()
    5. function get():
    6. lock.acquire()
    7. if instance == null:
    8. instance = Engine(
    9. model_path = resolve_model_path(),
    10. backend = GPU,
    11. max_tokens = 10000,
    12. cache_dir = app_cache_dir()
    13. )
    14. instance.initialize()
    15. lock.release()
    16. return instance

    The lock ensures multiple threads cannot trigger duplicate loading simultaneously.

    3.2 On-Demand Sessions: Create and Release per Request

    A session holds the context of a single conversation, and creating one is far cheaper than creating the engine. Creating a new session for each inference and closing it immediately afterward prevents context contamination between requests and releases temporary caches promptly.

    1. function infer(user_text):
    2. session = engine.create_session(config)
    3. try:
    4. for chunk in session.send_async(user_text):
    5. emit(chunk)
    6. finally:
    7. session.close() // release on success, failure, or cancellation

    The finally block guarantees resource release on exception paths as well. On-device, resource leaks gradually accumulate into memory pressure and eventually cause stability problems.

    3.3 Unified Interface: Transparent Switching for the Upper Layer

    The business layer should not care whether a model runs in the cloud or locally. Abstract all model providers behind the same interface so switching only requires a configuration change.

    1. interface LLMClient:
    2. function complete(prompt, options) -> stream<Token>
    3. class LocalModelClient implements LLMClient: ...
    4. class CloudModelClient implements LLMClient: ...
    5. // Configuration-driven
    6. provider = config.get("llm.provider") // "local" or "cloud"
    7. client = factory.create(provider)

    To add a new model source, simply implement the interface; the upper-layer Agent code needs no changes.

    4. Multi-Task Concurrency: Global Serialization

    An app typically runs multiple Agents in parallel—for example, card processing, knowledge base organization, and image and audio analysis. All of them need to call the same local model. Compute resources for on-device inference are limited; submitting multiple requests simultaneously causes VRAM contention, latency spikes, and can even retrigger stability issues.

    There are three common approaches:

    Approach Pros Cons
    Each Agent holds its own engine Good isolation Memory usage multiplies; basically infeasible
    Global mutex Simple to implement, controllable resources Tasks run serially, limited throughput
    Priority queue with a single worker thread Controllable scheduling order, supports cancellation Higher implementation complexity

    For on-device scenarios, a single engine with a global mutex is a sound starting point. Keep the following in mind during implementation:

    1. The lock granularity must cover a complete inference run, not just engine creation.
    2. Analysis tasks (such as image and audio) take a long time; set timeouts and cancellation mechanisms to avoid holding the lock for extended periods.
    3. User-triggered interactive tasks should get higher priority to keep foreground operations responsive.
    4. Long-running background tasks should execute in batches, yielding the lock between batches to leave windows for foreground requests.
    1. // Illustration of a global inference queue
    2. queue = PriorityQueue()
    3. worker_lock = Mutex()
    4. function submit(task, priority):
    5. future = new Future()
    6. queue.push(priority, {task, future})
    7. return future
    8. function worker_loop():
    9. while true:
    10. item = queue.pop_highest()
    11. with worker_lock:
    12. result = run_with_timeout(item.task, timeout = 60s)
    13. item.future.resolve(result)

    5. Common Issues and Troubleshooting Checklist

    Symptom Possible Cause Recommendation
    Device occasionally reboots Memory peak too high, or call chain too long Reduce intermediate layers, monitor peak memory, shorten context length
    Very slow first response Model loading takes time Warm up after launch, or initialize during idle time
    Slows down after multiple requests Sessions not released, caches accumulating Use try/finally to guarantee release
    Output mixing across requests Session being reused Use a new session for each inference
    Tasks blocking each other Lock granularity too large or no timeout Set timeouts, split long tasks

    6. Conclusion

    The engineering difficulty of on-device LLMs is not whether the model can run, but whether it can run stably and controllably over the long term. This article summarizes three lessons:

    • Minimize the call chain, prefer stable interfaces close to the底层底层 layer—close to the底层底层. Prefer stable interfaces close to the底层底层 layer, and use a controlled-variable approach to locate problems.
    • Make the engine a singleton, create sessions on demand, and use try/finally to guarantee timely resource release.
    • Isolate local and cloud implementations behind a unified interface, and serialize multi-task requests through global scheduling.

    These principles are independent of any specific model or framework and can be applied directly to other on-device inference scenarios.