On-Device Small LLM Integration: From System Crashes to Stable Inference

    Facing random device reboots caused by a community Flutter wrapper during on-device LLM inference, our team rebuilt the integration on official native Kotlin APIs—fixing stability through engine singleton reuse, short-lived conversation management, and minimal cross-language calls. This article shares the architecture decisions, pitfalls, and tuning lessons from the process.

    Driven by growing mobile compute power and rising privacy awareness, on-device AI inference is moving from an experimental feature to production-ready deployment. Recently, while integrating an open-source lightweight model into a purely local personal knowledge management app, our team went through a complete tuning cycle—from frequent system crashes to stable, efficient inference. The pitfalls we hit, the trade-offs we made, and the final solution are worth sharing with fellow engineers.

    1. Background: The Product Need for Offline Inference

    Our app is positioned as a “local-first” AI journaling and knowledge management tool, with all user data strictly residing on the device. Previously, the app relied on general-purpose large model APIs from various cloud providers for semantic understanding and content generation. While the results were acceptable, this approach always carried network dependency and data privacy concerns. To offer users a fully offline option, we began evaluating small-parameter open-source language models that could run directly on-device.

    The models we evaluated were a family of multimodal lightweight models optimized for edge devices, with parameter counts in the 2B–4B range. The quantized files are about 2.6GB and can be deployed in the unified memory of mid-to-high-end phones, with GPU or NPU acceleration for inference. In terms of specs, this model family delivers solid baseline semantic capability while respecting mobile power and memory constraints—an excellent fit for our requirements.

    2. First Attempt: A Stability Crisis Caused by a Community Wrapper

    At the start of the project, we prioritized development speed and directly adopted a popular cross-platform community wrapper. The wrapper, built on Flutter’s plugin mechanism, packaged the underlying inference engine as Dart-callable APIs, theoretically supporting both Android and iOS.

    The actual results caught us completely off guard—during inference, the test device would reboot without warning. Not an app crash or an ANR, but a system-level cold reboot. After multiple rounds of reproduction, we confirmed the issue was random but highly probable: any inference operation had a significant chance of causing the device to go black and restart.

    Further investigation pointed to the cross-language call overhead in the wrapper layer. The wrapper communicated bidirectionally through JNI and Flutter MethodChannel. In high-frequency, high-throughput token streaming scenarios, data copying and reference passing between the Dart and C++ layers easily triggered memory race conditions. Combined with the underlying inference engine’s aggressive memory allocation strategy, this ultimately led to kernel-level critical errors.

    3. Root Cause Analysis: Why the Official Path Is Stable

    On the same test device, we ran a control test using the model’s official demo app—and inference ran smoothly with zero crashes. The official demo calls the inference engine’s low-level APIs directly from Kotlin, bypassing all intermediate abstraction layers. This made it clear: the inference engine itself had no fatal flaws; the problem lay in the implementation quality of the community wrapper.

    Specifically, the official Kotlin API has the following key characteristics:

    • Singleton engine lifecycle: The engine is initialized only once per process, and the model file stays resident in memory, avoiding memory fragmentation from repeated loading.
    • Lightweight conversation design: Each conversation is cheap to create and closed immediately after use, accumulating no useless intermediate state.
    • Native coroutine support: The API implements streaming output via Kotlin Flow, naturally fitting Android’s asynchronous architecture.

    By contrast, the community wrapper managed engine initialization implicitly, and its conversation lifecycle potentially conflicted with Dart-side garbage collection—especially fatal in long-conversation scenarios.

    4. Architecture Rebuild: A Stable Implementation on Native APIs

    After weighing the options, we abandoned the community wrapper and moved to an architecture built on the official Kotlin API with a custom Platform Channel. The new architecture follows three principles: engine reuse, short-lived conversation management, and a minimal asynchronous chain.

    1. // Engine as a singleton, ensuring the model loads only once
    2. object LiteRtLmEngineHolder {
    3. private val engine: Engine by lazy {
    4. Engine(
    5. EngineConfig(
    6. modelPath = LocalModelManager.getModelPath(),
    7. backend = Backend.GPU(),
    8. maxNumTokens = 10000,
    9. cacheDir = AppContextHolder.get().cacheDir.absolutePath
    10. )
    11. ).apply { initialize() }
    12. }
    13. fun getEngine(): Engine = engine
    14. }
    15. // Create an independent Conversation per inference request and destroy it immediately after use
    16. suspend fun generateResponse(userInput: String): String {
    17. val conversation = LiteRtLmEngineHolder.getEngine().createConversation(
    18. ConversationConfig()
    19. )
    20. return try {
    21. val response = StringBuilder()
    22. conversation.sendMessageAsync(userInput).collect { token ->
    23. response.append(token.text)
    24. }
    25. response.toString()
    26. } finally {
    27. conversation.close()
    28. }
    29. }

    This design stays consistent with the official demo app. The key changes include:

    1. Removing Dart’s involvement in the inference pipeline: Dart only initiates requests and receives results; it no longer participates in relaying or decoding the token stream.
    2. Transmitting complete strings over MethodChannel: Although each transfer carries more data, the frequency of cross-language calls drops dramatically, reducing crash risk.
    3. Using Protocol Buffers instead of JSON for data exchange between Dart and the native layer, minimizing string serialization overhead.

    After the refactor, inference speed returned to normal, devices no longer rebooted under prolonged stress testing, and the stability problem was fully resolved.

    5. Lessons Learned: Five Pitfalls Worth Noting

    Beyond the core architecture decision, we documented several detail-level traps that are easy to fall into during this kind of integration:

    1. Memory Bandwidth Is the Key Bottleneck

    Although mobile GPU inference loads the model into GPU memory, data movement between CPU and GPU (such as copying token embeddings) remains the main bottleneck during inference. In the new architecture, we pinned repetitive preprocessing steps—input tokenization, attention mask generation—on the native side, preventing the Dart layer from ever touching internal model tensors.

    2. Precision Trade-offs with Quantized Models

    The E2B/E4B models use symmetric quantization. While the degradation is acceptable on vision-language tasks, precision loss accumulates in long-text reasoning and mathematical derivation scenarios. If your business has high output-quality requirements, consider enabling the inference engine’s “high-precision fallback” option, allowing certain critical layers to execute in FP16.

    3. Memory Warm-up and Insufficient GPU Memory

    A 2.6GB model file resident on the GPU means the app’s baseline memory footprint is significantly higher than a typical app. On resource-constrained mid-to-low-end devices, you need to listen for system memory pressure callbacks, release conversation caches promptly, and proactively degrade to CPU inference in low-memory situations (slower, but it prevents the process from being killed by the low-memory killer).

    4. Latency Control for Streaming Output

    In on-device inference, token generation speed is limited by the chip’s compute capability. In the actual product, we adopted an incremental UI rendering strategy—the UI refreshes only when the Dart layer receives a complete sentence rather than a single token. This greatly improved reading experience and reduced the UI thread’s refresh frequency.

    5. Recovery After the Process Is Killed

    If the user leaves the app in the background for too long, the system may reclaim GPU resources. When resuming inference, first check the engine state. If the engine has become invalid, re-initialize the Engine and reload the model—show a clear loading indicator during this process to avoid a frozen-looking UI.

    6. Conclusion and Outlook

    From crashing reboots to smooth operation, this integration project deeply validated one principle: in on-device AI inference, native capabilities are always the most reliable guarantee of stability. The convenience offered by framework wrappers often turns into uncontrollable system-level risk when facing long-running, high-throughput inference tasks.

    Going forward, we plan to further experiment with quantization-aware training and structured pruning, trading acceptable performance degradation for smaller model sizes so that on-device inference can reach a broader range of devices. We also hope the model ecosystem and mobile platforms will provide more fine-grained inference scheduling APIs—such as CUDA Graph-style modes or NPU direct-access modes—to reduce context-switching overhead at the lower layers.

    For development teams currently evaluating or advancing on-device LLM integration, our core advice is: don’t blindly trust “out-of-the-box” community solutions—run rigorous stability stress tests; and if conditions allow, build your native inference pipeline on low-level APIs as early as possible. That is the right path to balancing feature development with system stability.