On-Device Deployment of Open-Source Small Language Models: A Complete Path from Pitfalls to Stable Inference

    As open-source lightweight LLMs in the 2B–4B parameter range become genuinely usable for general tasks, running inference locally on mobile devices is increasingly practical. This article documents a real-world deployment journey for a local Agent product: model selection and benchmarking, why a community cross-platform wrapper caused crashes and full device reboots, how rebuilding the integration with official native APIs and a Dart–Kotlin bridge resolved it, and how to handle concurrency across multiple Agents with a serialized inference queue—along with remaining challenges such as long-context limits and thermal constraints.

    Why On-Device Inference Is Worth the Effort

    As open-source lightweight LLMs improve rapidly, models in the 2B–4B parameter range can now deliver usable output quality on general tasks. For teams building local Agent products on mobile devices, the value of on-device inference is clear:

    • Data never leaves the device: personal notes, photos, and voice recordings all stay local, significantly reducing compliance pressure and improving user trust;
    • Fully offline: no dependency on cloud services, so features keep working on weak or unavailable networks;
    • Predictable cost: no per-token inference charges—long-term usage costs approach zero;
    • Low latency: with no network round trip, time-to-first-token depends mainly on local compute.

    The trade-offs are equally obvious: model capability falls short of flagship cloud models, device memory and battery impose hard constraints, and engineering integration is complex. This article documents one complete on-device deployment effort from start to finish.

    Model Selection and Understanding the Specs

    Lightweight open-source models typically ship in multiple sizes—for example, an efficient ~2B version, a balanced ~4B version, and quantized variants targeting higher throughput. When choosing, weigh three dimensions:

    1. Memory footprint: model weights loaded into GPU/device memory usually run around 2GB. You must leave headroom for the OS and other apps, or the process risks being killed by the system;
    2. Inference quality: more parameters generally means better quality, but on-device you often trade some quality for acceptable decoding speed;
    3. Quantization level: quantization is standard practice for on-device deployment. Lower weight precision typically means faster inference and smaller memory use, but stability on long-tail tasks may degrade.

    Benchmark on your actual target devices before committing: run a fixed set of prompts and record time-to-first-token, decoding speed (tokens/s), and peak memory. Then decide on the final model size.

    Integration Path: Wrapper Libraries vs. Official Native APIs

    This was the most important lesson of the whole project.

    3.1 The “Easy” Route First: Cross-Platform Wrapper Packages

    To save development effort, we initially used a community-maintained cross-platform wrapper package. These packages sit on top of the underlying inference engine and expose a unified API, which looks like a low-cost way to integrate. In testing, however, we hit serious problems: the app not only crashed—in extreme cases it triggered a full device reboot.

    Our troubleshooting process:

    • With the same device and the same model file, the official demo app ran perfectly fine;
    • The key difference: the official app calls the native inference API directly, while the wrapper adds an extra cross-platform Plugin forwarding layer;
    • Our suspicion centered on memory management, thread scheduling, or resource lifecycle issues during the cross-layer handoff—but the root cause could not be identified within a reasonable time frame.

    The conclusion was straightforward: on-device inference touches low-level resources like GPU memory management. When stability risk becomes unacceptable, fall back to the official native API instead of continuing to patch the wrapper layer.

    3.2 Building Our Own Platform Channel to the Native Inference Engine

    The final architecture became a classic cross-platform bridge:

    1. Dart (business layer)
    2. → MethodChannel (cross-platform channel)
    3. → Kotlin Plugin (native bridge layer)
    4. → On-device inference engine (GPU backend)

    The core design on the native side is a singleton Engine with Conversations created on demand:

    1. // The Engine is initialized only once—model weights are loaded into GPU memory a single time
    2. val engine = Engine(
    3. EngineConfig(
    4. modelPath = modelPath,
    5. backend = Backend.GPU(),
    6. maxNumTokens = 10000,
    7. cacheDir = context.cacheDir.absolutePath,
    8. )
    9. )
    10. engine.initialize()
    11. // Create a lightweight Conversation per request and release it when done
    12. engine.createConversation(config).use { conversation ->
    13. conversation.sendMessageAsync(userText).collect { token ->
    14. // Stream tokens back via callback
    15. }
    16. }

    Why this design makes sense:

    • Model loading is a heavy operation (GB-scale weights read into GPU memory). It must happen exactly once globally to avoid memory churn from repeated loads;
    • Conversations are lightweight: create one per request and close it when finished. This naturally isolates context, preventing state bleed and memory leaks;
    • Streaming output is collected through an async flow, so the UI layer can render tokens as they arrive—the experience matches a cloud streaming API.

    After switching to this path, inference speed returned to normal, and the crashes and reboots disappeared.

    Transparent to the Upper Layer: A Unified LLMClient Interface

    To keep on-device inference decoupled from business logic, the Dart side implements an LLMClient interface identical to the one used for cloud providers:

    1. abstract class LLMClient {
    2. Future<void> init();
    3. Stream<String> sendMessage(String prompt);
    4. void dispose();
    5. }
    6. class GemmaLocalClient implements LLMClient { ... }

    The upper-layer Agent always calls the same interface; switching between local models and cloud services requires changing only one configuration entry. This abstraction is key to long-term evolution—it turns “offline mode” into a product option rather than a separate code branch.

    Multi-Agent Concurrency: Inference Must Be Serialized

    One of the biggest differences between on-device and cloud inference is concurrency capacity. Cloud services scale horizontally; on-device you have exactly one GPU and one inference engine. When multiple Agents run in parallel (for example, a card-processing Agent, a knowledge-base Agent, and an image/audio analysis Agent), letting each fire inference requests directly leads to resource contention, out-of-memory failures, or even engine crashes.

    A practical solution is a global inference lock:

    • All inference requests enter a task queue; only one Conversation is active at any moment;
    • Requests are scheduled by priority (e.g., interactive requests a user is waiting on take precedence over background batch work);
    • Background Agents are refactored toward “batching”—merging multiple small requests into a single long-context call to reduce queue-switching overhead.
    1. class InferenceScheduler {
    2. final _lock = Lock();
    3. Future<T> run<T>(Future<T> Function() task) =>
    4. _lock.synchronized(task);
    5. }

    This pattern is simple but effective: throughput is limited, but stability and predictability improve dramatically—and those are exactly the qualities on-device products need most.

    Open Issues and Next Steps

    • Crash root cause still unresolved: the wrapper-induced device reboots were never traced to a definitive root cause; we handled it by avoidance and will keep monitoring future wrapper releases;
    • Long-context support: the current maxNumTokens is set around 10,000, which is not enough for knowledge-base organization tasks. Context compression or retrieval-augmented generation (RAG) is worth exploring to fill the gap;
    • Power and thermals: sustained GPU-backend inference generates heat and drains battery. We need further observation in real usage scenarios and may need to throttle or defer background tasks when necessary.

    Conclusion

    The engineering challenges of on-device inference are not about “getting it to run”—they are about stability, the concurrency model, and upper-layer abstraction. The core lessons boil down to three: prefer official native APIs over multi-layer wrappers; make the inference engine a global singleton with short-lived conversations; and serialize inference through a global queue in multi-Agent scenarios. Get these three right, and an open-source lightweight model can fully support a local Agent product where data never leaves the device.