Running Large Language Models On-Device: Key Stability Considerations for Mobile Inference

    This article examines the practical integration of an on-device language model into a mobile application that already uses cloud-based models. It covers deployment options, a system-level stability issue caused by an intermediate wrapper, and a refactored architecture based on a unified client interface, a singleton inference engine, and per-request session management.

    1. Background and Objectives

    Running a large language model on a mobile device provides three main benefits: data remains on the device, the application can continue working without a network connection, and long-term usage costs can be reduced. These benefits are particularly valuable for applications focused on personal journaling and knowledge management, where users’ notes, habits, and daily records are often sensitive.

    This article focuses on a practical engineering problem: how to integrate an on-device language model into a mobile application, allow it to share a common calling interface with existing cloud-based models, and maintain stability during long-running operation. The experience described here comes from a complete implementation process, including solution selection, stability failures, and the approaches used to address them.

    2. Choosing an On-Device Inference Approach

    On-device inference generally follows one of three paths:

    Approach Advantages Risks
    Calling the model through a third-party cross-platform wrapper Fast integration and a shared codebase across platforms Adds another layer for lifecycle and thread management, making issues harder to diagnose
    Calling the native APIs provided by the inference engine directly A shorter call path with behavior closer to the official examples Requires separate native implementations and increases cross-platform maintenance costs
    Using a cloud inference service Strong model capabilities without managing device resources Requires network connectivity and introduces privacy and usage-cost concerns

    The key selection criterion is whether the team can control every layer of the inference path. When a layer produces unexplained behavior, troubleshooting costs are often much higher than the cost of writing additional native code. For this reason, observability and controllability should be treated as equally important as development efficiency during solution selection.

    3. Stability Failure: System-Level Risks Introduced by an Intermediate Wrapper

    At the beginning of the project, a cross-platform wrapper was used to accelerate integration. During operation, a serious issue occurred: the device would occasionally display a black screen and reboot during inference. This was a system-level failure with a much broader impact than an application crash.

    During the investigation, the same device ran normally with the same model file in the official sample application. This comparison was highly valuable because it narrowed the problem to the integration layer rather than the model file itself.

    The exact cause of the reboot was not fully confirmed. Possible causes included:

    1. Excessive memory peaks during model loading and inference, triggering the system’s resource protection mechanisms;
    2. Timing issues between accelerator memory allocation and release and the underlying driver;
    3. Additional thread switching or object lifecycle management in the wrapper that did not match the expectations of the underlying engine;
    4. Session objects being created and destroyed too frequently, causing resources to accumulate without being released in time.

    These possibilities should be verified individually through logs, memory profiles, and device monitoring. Before the root cause is confirmed, the engineering priority should be to reduce risk directly. In this case, that means bypassing the uncertain intermediate layer and using a calling method closer to the underlying engine.

    4. Refactoring: Layered Decoupling and a Unified Interface

    4.1 Overall Architecture

    After the refactoring, the call path was structured as follows:

    1. Business layer (agent and conversation logic)
    2. ↓
    3. Unified model client interface (the same protocol for cloud and local implementations)
    4. ↓
    5. Cross-platform communication channel (native mobile bridge)
    6. ↓
    7. Native inference service (managing the engine and sessions)
    8. ↓
    9. On-device inference engine (using hardware acceleration)

    Each layer has a clear responsibility. The business layer only needs to send messages and receive streamed output; it does not need to know whether the model is running locally or in the cloud. The communication channel is responsible only for data serialization and thread switching. The native service manages resources, which is the key to improving stability.

    4.2 Singleton Engine and On-Demand Sessions

    On-device inference involves two types of resources with very different lifecycles:

    • Inference engine: Loads the model file and consumes a significant amount of memory or accelerator memory. Initialization is relatively slow. It should be initialized only once per process and tied to the lifecycle of the application or service.
    • Session: Stores the context for a single conversation. It is lightweight and can be created before each inference request and released immediately afterward to prevent context from leaking between conversations.

    The following pseudocode illustrates the structure. Parameter names should be verified against the documentation for the inference engine being used.

    1. // 1. Initialize only once per process
    2. engine = InferenceEngine.create(
    3. modelPath = modelFile.absolutePath,
    4. accelerator = PREFER_GPU,
    5. maxContextTokens = configuredLimit,
    6. cacheDir = appCacheDir
    7. )
    8. engine.initialize()
    9. // 2. Create a session for each inference request and release it afterward
    10. engine.openSession(sessionConfig).use { session ->
    11. session.streamReply(userText).collect { chunk ->
    12. emitToUi(chunk)
    13. }
    14. }

    This design separates heavyweight resources from lightweight state. If the model is loaded again for every request, the application repeatedly performs large memory allocations, which creates a high risk in resource-constrained on-device environments.

    4.3 Unified Client Interface

    The capabilities required by the upper-layer agent are simple: accept input messages and provide streamed output. A unified client interface allows the business layer to use the same calling protocol for both cloud and local models, while the implementation details remain isolated below the interface.