Running Small LLMs On-Device: Building a Fully Offline Local AI Agent

    This article shares practical lessons from integrating an on-device small language model into a mobile app to create a fully offline AI agent. It covers why local inference matters for privacy and availability, why a community cross-platform wrapper caused system-level crashes and how direct native integration solved it, an architecture built around an engine singleton with lightweight sessions, why on-device inference should be serialized behind a global lock, and key engineering details like model distribution, quantization, context budgeting, and thermal management.

    Running Small LLMs On-Device: Building a Fully Offline Local AI Agent

    Why Move Large Language Models onto the Phone

    As small open-source LLMs improve rapidly, running local inference on mobile devices has evolved from a “demo toy” into a viable product capability. For personal journaling and knowledge management apps, fully offline inference offers three irreplaceable benefits:

    • Data sovereignty: Highly private data such as journals, photos, and voice memos never leaves the device—nothing is transmitted over the network;
    • Availability: Features don’t degrade in no-network or weak-network environments; everything keeps working on the subway or on a plane;
    • Predictable cost: There’s no per-request billing, so high-frequency background tasks like auto-categorization and auto-summarization can run freely.

    Our app originally followed a “bring your own model service” architecture, where users configured their own cloud model APIs. After adding a zero-dependency fully offline option, users can switch between “high-quality cloud” and “high-privacy local” with a single tap. Below are the key decisions and pitfalls from the integration process.

    Lesson One: The Stability Trap of Cross-Platform Wrappers

    To validate quickly, we initially chose a community-provided cross-platform plugin that wrapped the underlying on-device inference runtime with a clean interface—just a few lines of code to get running. But testing revealed a serious problem: during inference, the device would occasionally reboot entirely—not an app crash, but a system-level black-screen restart.

    The investigation delivered an important insight:

    1. With the same device model and the same model file, the official native sample app ran stably with no reboots;
    2. The difference was that the community plugin added an extra cross-platform bridging layer on top of the native inference engine, involving asynchronous callbacks over the platform channel, thread switching, and cross-layer memory buffer copies;
    3. On-device inference involves low-level resources like GPU memory mapping and tensor buffers; if any layer of the wrapper mishandles their lifecycle or threading model, it can trigger a driver-level fault.

    Conclusion: For a capability as resource- and stability-sensitive as on-device inference, you should not casually introduce an unverified intermediate wrapper. Directly integrating with the platform’s official native inference API is the only reliable engineering choice. This principle applies broadly to all kinds of on-device AI scenarios.

    Architecture Rebuild: Direct Native Integration + Engine Singleton

    After abandoning the wrapper, we wrote our own platform channel, resulting in a clean three-layer architecture:

    1. UI/Business Layer (Dart) → MethodChannel → Native Plugin Layer → On-Device Inference Engine

    The core design on the native side is an engine singleton with sessions created on demand:

    1. // The engine is initialized only once: loading multi-GB model weights into GPU memory
    2. val engine = Engine(EngineConfig(
    3. modelPath = modelPath,
    4. backend = Backend.GPU(),
    5. maxNumTokens = 10000,
    6. cacheDir = context.cacheDir.absolutePath,
    7. ))
    8. engine.initialize()
    9. // A lightweight session is created for each inference request and released when done
    10. engine.createConversation(config).use { conversation ->
    11. conversation.sendMessageAsync(userText).collect { token ->
    12. // Stream tokens back to the upper layer
    13. }
    14. }

    Three considerations drive this design:

    • Model loading is expensive. Loading multi-GB weights into GPU memory takes several seconds and consumes a huge amount of memory. The engine must be globally unique and long-lived in memory—never reloaded per request;
    • Sessions are lightweight. Conversation context and sampling parameters can be created independently per task without polluting each other, and destroyed after use to prevent unbounded context growth;
    • Streaming output is essential for UX. First-token latency of on-device small models is relatively acceptable, but full generation takes a while; tokens must be pushed to the UI incrementally, or users will assume the app has frozen.

    After switching to direct native APIs, inference speed returned to normal and the device-reboot problem disappeared completely.

    The upper-layer abstraction matters just as much. We defined a unified model client interface at the business layer, with local and cloud implementations following the same contract—completely transparent to the agents above. Switching to the local model requires changing a single configuration item. This vendor-agnostic interface design lets the app host both cloud LLMs and on-device small models, routing tasks flexibly by type.

    Concurrent Agents: A Global Lock Is Mandatory

    Multiple agents run in parallel inside the app: card processing, knowledge-base organization, image and audio content analysis. Problems appeared when they issued inference requests to the local model simultaneously.

    Compute and memory on edge devices are scarce resources. A multi-GB model already occupies a large share of GPU memory, and concurrent inference sessions lead to:

    • Stacked GPU memory usage, triggering system memory pressure or even process termination;
    • Contention for GPU compute, slowing all requests while causing heat and thermal throttling;
    • Unpredictable output quality due to resource jitter.

    The solution is a global mutex: all local inference requests enter a serial queue, and only one session may run inference at a time. Combined with request priorities—user-initiated interactive requests take precedence over background batch jobs—this guarantees stability while keeping the foreground experience unaffected by background work.

    The practical takeaway: the concurrency model for on-device inference should default to serial, and reserve “parallelism” for the cloud. If throughput is genuinely needed, improve efficiency by batching tasks (e.g., summarizing multiple records in a single request) rather than spawning concurrent sessions.

    Engineering Details and Lessons Learned

    Beyond the main path, several details are worth noting:

    • Model distribution: Multi-GB model files should not be bundled into the app package. Download on first use, verify integrity, then persist to disk, with resume support for interrupted downloads;
    • Quantization choices: More aggressive quantization significantly reduces memory footprint and power consumption, but must be validated with quality regression tests on your actual tasks—not just generic benchmarks;
    • Context budget: On-device small models have limited effective context. Knowledge-base tasks require proper retrieval and trimming—feed the model the most relevant snippets instead of dumping in the entire library;
    • Thermal-aware degradation: Sustained inference triggers thermal throttling. Background batch jobs should be executed in chunks with cooling intervals in between;
    • Managing capability boundaries: On-device small models excel at structured tasks like summarization, classification, rewriting, and information extraction. Complex reasoning and long-form writing should still be routed to the cloud, and the product should set clear expectations about these boundaries.

    Conclusion

    Integrating an on-device small model is ultimately an exercise in “deterministic engineering under constrained resources”: bypass unstable wrapper layers, stick to the engine singleton, constrain concurrency with a global lock, and manage memory and thermals carefully. Get these right, and the local agent becomes a reliable counterpart to cloud capabilities. For developers who want to balance privacy and user experience, this path is now genuinely viable at the product level.