On-Device Small Model Selection and Fully Offline Agents: A Practical Mobile Guide

    A practical engineering guide to choosing open-source small language models for mobile devices and shipping agents that run with no network. It defines what "fully offline" means, covers evaluation dimensions such as weight size, resident and peak memory, inference backends, context length, throughput, structured output reliability, quantization format and cold start, and shows how to make measurements reproducible across device tiers. It then explains why multi-layer cross-platform wrappers amplify stability risk, presents a native inference plugin behind a platform channel with a singleton engine and per-turn sessions, and details multi-agent concurrency using a single scheduler that serializes inference while business logic stays concurrent. The article closes with model distribution and hash verification, open-source license compliance, runtime capability detection, degradation paths, optional cloud fallback, evaluation sets and metrics, and a pre-launch checklist.

    Introduction: How do you pick an on-device small model, and how do you build a mobile agent on top of it?

    How should you choose an open-source small model for a phone? How do you diagnose the crashes, overheating, and out-of-memory failures that show up in on-device inference? How do you design an agent that is fully offline by default and never silently reaches for the cloud? And when several agents run at once, how do you keep the inference queue from spiraling out of control?

    This article answers those questions with an engineering approach that you can actually ship: selection criteria, a native inference pipeline, concurrency governance through a single scheduler, model distribution, license compliance, capability detection, degradation strategies, and evaluation metrics. The goal is to turn on-device small models into a stable, dependable product capability.

    1. Define the boundary first: what is a fully offline agent?

    Before comparing models, define what “fully offline” means. In this article, fully offline means the agent completes its core tasks without depending on the network by default: the model files are already on the device, inference runs locally, data never leaves the device, and capability detection, degradation, and logging are all handled locally.

    If the product later offers a cloud fallback, it should be designed as an optional degradation path, not the default path. The offline mode has to be explicit and visible in settings: cloud upload is off by default, and only after the user actively enables networked enhancement may part of the context be sent to the cloud. Otherwise the privacy promise of an offline product gets broken by default networking behavior.

    The advantages of on-device small models are:

    • Controllable privacy: conversations, notes, and image recognition results never leave the device.
    • Works offline: summaries, classification, extraction, and rewriting still function in airplane mode, on weak networks, and during a commute.
    • Stable latency: with no network round trip, time to first token is more predictable.
    • Controllable cost: no recurring cloud inference bill, and marginal cost is close to zero.
    • Customizable: different model tiers can be delivered depending on device memory, chip capability, and the tasks users actually perform.

    That said, on-device is not “the smaller the better,” and it is not “it runs, therefore it works.” What actually determines the experience is the combination of model capability, memory footprint, backend compatibility, concurrency governance, and degradation strategy.

    2. How to choose: evaluation dimensions and test methodology for on-device small models

    Do not select based on public benchmarks alone. On-device environments vary enormously: the same model can behave completely differently across device models, OS versions, and inference backends. Validate along the following dimensions.

    2.1 Memory and weight size

    The on-device bottleneck is usually memory, not raw compute. Track at least three distinct numbers:

    • Weight file size: affects the installer or download size.
    • Resident memory after loading: affects whether the app survives in the background and how it handles task switching.
    • Peak inference memory: includes context cache, KV cache, temporary tensors, and similar allocations.

    The longer the context, the higher the peak. Measure peak memory on the target device rather than looking only at averages.

    2.2 Inference backend and hardware acceleration

    Common backends include CPU, GPU, and NPU. Backend support for a given model’s operators differs, and some operators may fall back to CPU, which can make the accelerated path slower than the plain one. Test each backend separately, and always keep a CPU fallback path.

    2.3 Context length and throughput

    Record these separately:

    • Time to first token: reflects model loading, warmup, scheduling, and first-chunk generation cost.
    • Per-token latency: reflects real throughput during steady generation.
    • Long-context degradation: in multi-turn conversations or long documents, watch whether latency climbs sharply.

    2.4 Instruction following and structured output

    What matters in agent scenarios is not prose quality but reliably emitting output a program can parse. Focus on:

    • JSON Schema field completeness rate.
    • Tool-call argument correctness rate.
    • Multi-turn instruction-following rate.
    • Whether refusal behavior is controllable.

    If structured output is unstable, no amount of sophistication in the agent layer above it will help; it will simply fail often.

    2.5 Quantization format and ecosystem compatibility

    Prefer weights in mainstream quantization formats with good runtime compatibility. The longer the conversion chain, the more precision loss, missing operators, and platform differences you accumulate. For an on-device product, stability is usually worth more than one extra point of accuracy.

    2.6 Cold start vs. warm start

    A cold start may include weight verification, deserialization, engine initialization, and graph compilation warmup, ranging from a few hundred milliseconds to several seconds depending on the device. The product must distinguish cold start from warm start and show loading progress, retry on failure, and surface a degradation notice.

    2.7 Comparison table template

    Use a table like the one below to compare candidate models. The numbers must come from testing on real devices, not from vendor marketing.

    Model size Quantization Suggested backend Resident memory P95 time to first token Per-token latency Suitable tasks
    0.5B–1B 4-bit / int4 CPU, GPU To be measured To be measured To be measured Classification, short summaries, tag extraction
    1B–3B 4-bit / int4 GPU, CPU To be measured To be measured To be measured Multi-turn Q&A, card generation
    3B–4B 4-bit / int4 High-memory devices To be measured To be measured To be measured Complex rewriting, long-context summarization

    2.8 Test methodology

    To keep conclusions reproducible, fix the following conditions:

    • Devices: cover low-memory, mid-range, and high-memory devices.
    • OS versions: at least the versions your main user base runs.
    • Chip and acceleration capability: record CPU, GPU, and NPU separately.
    • Quantization format: state explicitly whether it is int4, int8, or something else.
    • Context length: test at least 1024, 2048, and 8192 tokens.
    • Warmup strategy: separate cold start from warm start.
    • Sampling: report P50, P95, and P99. P95 matters more than the mean.
    • Sustained load: run inference continuously for 10 to 30 minutes and observe temperature rise, throttling, and success rate.

    3. Common pitfalls: how layered abstractions amplify stability risk

    The most counterintuitive problems in on-device inference projects usually come from multi-layer wrappers introduced “to save effort.”

    Some cross-platform frameworks offer high-level inference wrapper plugins that get you running in a few lines of code. On real devices, however, you may see intermittent black screens, whole-device reboots, or native-layer crashes. These are usually not business logic bugs. They come from the bridging layer, thread management, out-of-bounds memory access, or mishandled JNI boundaries, and the resulting exception crosses the application sandbox and trips a system-level protection mechanism.

    A sensible order of investigation:

    1. Run the official reference sample first to confirm that the model, the backend, and the device itself are all fine.
    2. Use bisection to add your own wrapper layers back one at a time, changing only one variable at each step.
    3. Collect native crash logs, system error codes, and tombstone information.
    4. Monitor peak memory, GC pressure, and thread states to rule out OOM or thread contention.

    Avoid overgeneralizing here. Not every cross-platform wrapper is unusable. The point is that when stability is critical and the official reference implementation already meets the functional requirement, prefer the thinner wrapper chain. If the product must keep a cross-platform abstraction, then add isolation, degradation, logging, rollback, and real-device regression testing.

    A more reliable principle: every layer of abstraction in the inference path should have a clear benefit, an observable failure path, and a way to roll back. Saving a few lines of glue code is not worth introducing system-level crashes that are hard to localize.

    4. Architecture: a native inference plugin plus a platform channel

    In stability-sensitive scenarios, use a pipeline like this:

    1. UI / business logic (cross-platform layer)
    2. │ method calls + streaming callbacks
    3. Platform channel (Platform Channel / message bridge)
    4. │
    5. Native inference plugin (Native Inference Plugin)
    6. │
    7. Official inference engine (CPU / GPU / NPU backend)

    The platform channel is the message bridge between the cross-platform UI layer and the native layer. A conversation is the context container for a single inference task and should be released when the task ends. The benefit of this design is a shorter path in which native exceptions are easier to localize.

    4.1 Engine singleton, conversations created on demand

    Loading a model is an expensive operation and should happen as close to once as possible. Per-turn conversation state, on the other hand, must be isolated. Make the engine a global singleton and make conversations lightweight objects created on demand and released when done.

    1. class LocalInferencePlugin(private val ctx: Context) {
    2. @Volatile
    3. private var engine: Engine? = null
    4. @Synchronized
    5. fun engine(): Engine {
    6. engine?.let { return it }
    7. val cfg = EngineConfig(
    8. modelPath = ctx.filesDir.resolve("model.bin").absolutePath,
    9. backend = Backend.GPU(), // fall back to CPU if initialization fails
    10. maxNumTokens = 8192, // upper bound of the context window
    11. cacheDir = ctx.cacheDir.absolutePath,
    12. engineVersion = "1.0.0", // used for compatibility checks
    13. abi = Build.SUPPORTED_ABIS, // must match the weight format
    14. warmup = true // whether to warm up
    15. )
    16. return try {
    17. Engine(cfg).also { it.initialize() }
    18. } catch (e: EngineInitException) {
    19. // log why initialization failed, then fall back to CPU or notify the user
    20. engine = null
    21. throw e
    22. }
    23. }
    24. fun chat(prompt: String, onToken: (String) -> Unit) {
    25. engine().createConversation(ConversationConfig()).use { conv ->
    26. conv.sendMessageAsync(prompt)
    27. .collect { chunk -> onToken(chunk.text) }
    28. }
    29. }
    30. }

    EngineConfig also carries prerequisites: the model file format must match the inference engine version; the ABI must be compatible with the instruction set; the private directory must be readable; and if initialization fails, the failure reason should be logged and the code should try a smaller model, the CPU backend, or a rules-based capability.

    4.2 Keep local and cloud behind the same abstraction

    Even when the default is fully offline, the agent layer should call inference through a single interface:

    1. interface LLMClient {
    2. fun chat(messages: List<Message>, options: Options): Flow<String>
    3. }

    The local implementation can be LocalLLMClient, and an optional networked implementation can be CloudLLMClient. Business logic above should not care where inference happens. This keeps the fully offline default path intact while letting you reuse the same prompt and parsing logic when the user explicitly enables networked enhancement.

    5. Multi-agent concurrency: global serialization with a single scheduler

    When one app runs several agents at once — card generation, knowledge-base summarization, image recognition, tag classification — submitting inference requests concurrently leads to uncontrolled queuing, memory spikes, contention over inference engine state, and wasted battery.

    The core principle: serialize model inference globally; business logic may stay concurrent.

    Note that simply wrapping a PriorityQueue in a Mutex does not give you real priority scheduling. A mutex only guarantees that one thread at a time enters the critical section; it is not a scheduler. The more reliable approach is a single-threaded dispatcher, or a single worker that consumes the priority queue.

    5.1 Task model and priorities

    1. enum class Priority(val weight: Int) {
    2. INTERACTIVE(300),
    3. FOREGROUND_BATCH(200),
    4. BACKGROUND(100)
    5. }
    6. data class InferenceTask(
    7. val id: String,
    8. val priority: Priority,
    9. val createdAt: Long,
    10. val deadline: Instant,
    11. val timeoutMillis: Long,
    12. val onCancel: () -> Unit,
    13. val run: suspend () -> Unit
    14. )

    Three priority tiers work well:

    • Foreground interactive: Q&A, generation, and search the user is actively waiting on.
    • Foreground batch: user-initiated bulk summarization or import organization.
    • Background batch: nightly sync, archiving old notes, low-priority indexing.

    5.2 A single worker consuming the priority queue

    1. class InferenceScheduler(
    2. private val scope: CoroutineScope,
    3. private val capacity: Int = 32
    4. ) {
    5. private val queue = PriorityQueue<InferenceTask>(
    6. compareByDescending<InferenceTask> { it.priority.weight }
    7. .thenBy { it.createdAt }
    8. )
    9. private val worker = scope.launch(Dispatchers.IO) {
    10. while (isActive) {
    11. val task = queue.poll() ?: run {
    12. delay(16)
    13. continue
    14. }
    15. try {
    16. withTimeout(task.timeoutMillis) {
    17. task.run()
    18. }
    19. } catch (e: TimeoutCancellationException) {
    20. task.onCancel()
    21. // log the timeout, then degrade or retry per policy
    22. } catch (e: CancellationException) {
    23. task.onCancel()
    24. } catch (e: Exception) {
    25. // log the failure and trigger degradation or fallback
    26. }
    27. }
    28. }
    29. fun submit(task: InferenceTask): Boolean {
    30. return synchronized(queue) {
    31. if (queue.size >= capacity) {
    32. false // queue is full: reject, or move to a longer delayed queue
    33. } else {
    34. queue.offer(task)
    35. true
    36. }
    37. }
    38. }
    39. }

    This is an illustrative implementation. In production, use a coroutine dispatcher, cancellable tasks, timeouts, and resource-cleanup hooks.

    5.3 Concurrency governance rules

    Beyond the scheduler, define these rules explicitly:

    • Priority preemption: a running task is usually not interrupted; high-priority tasks are inserted into the waiting queue. If preemption is unavoidable, cancel only resumable background tasks and record a checkpoint.
    • Task cancellation: when the user navigates away, cancels generation, or exits the scenario, send a cancellation signal instead of burning battery.
    • Timeouts: use different timeout thresholds for foreground, batch, and background tasks.
    • Queue capacity: the queue must have a hard limit; when full, reject, degrade, or move work to a delayed queue.
    • Failure fallback: retry once after an inference failure; if it still fails, switch to a smaller model, a rules-based capability, or prompt the user.
    • Context budget: when several agents share one model, enforce a unified token budget so a single agent cannot consume the whole context window.

    6. Practical concerns: model distribution, capability detection, and degradation

    Any on-device solution has to deal with model distribution, license compliance, capability detection, and the degradation path.

    6.1 Model distribution and updates

    Model files are usually large and should not all be bundled into the installer. Download on first use instead. After download, verify the hash, for example SHA-256. If verification fails, delete the corrupted file and download again, or roll back to the last known-good version.

    Recommended distribution strategy:

    • Ship small, medium, and large model tiers, delivered according to device memory.
    • Keep weights separate from the installer to shrink the initial download.
    • Write to the app’s private directory with least privilege.
    • Record version number, hash, download time, and source.
    • Keep a rollback version so a bad new model is recoverable.
    • Provide a cleanup policy for the private directory when storage is low or the user resets the app.

    6.2 Open-source model licenses and distribution compliance

    Open source does not mean unrestricted commercial use. For every model, check:

    • License type, for example Apache-2.0, MIT, or a custom community license.
    • Whether redistribution is permitted.
    • Whether copyright notices must be retained.
    • Whether the model card, training-data description, or modification notes must be disclosed.
    • Whether commercial use or user scale is restricted.
    • Whether the model may be bundled inside a mobile application.

    If the license does not allow redistribution, switch to runtime download and explain the data source in the privacy policy. The product should display the model name, version, source, license summary, and intended scenarios.

    6.3 Runtime capability detection

    At app startup, or before entering an inference screen, check:

    • Available device memory.
    • Available inference backends.
    • CPU instruction set and ABI.
    • Whether GPU or NPU is supported.
    • Whether the local model is complete.
    • Whether the hash check passes.
    • Whether there is enough storage.

    When a check fails, do not fail silently; fall back to a smaller model, the CPU backend, or notify the user.

    6.4 The degradation path

    A reasonable degradation order for a fully offline scenario:

    1. Use the model at the current tier.
    2. If memory is insufficient, switch to a smaller model.
    3. If the quantization format is incompatible, pick a compatible format.
    4. If inference keeps failing, fall back to rules-based local processing.
    5. Only after the user explicitly enables networked enhancement may a cloud fallback be used.

    Any cloud fallback must clearly tell the user what data is sent, where it goes, and whether it can be turned off. Fully offline mode should block cloud requests by default so it does not conflict with the privacy promise.

    6.5 Infrastructure and optional cloud fallback

    If the product genuinely needs an optional cloud fallback, it can usually be supported by general-purpose cloud services: object storage for model weights, a container platform for your own inference service, and logging plus monitoring to observe latency and failure rates. Whether additional infrastructure is needed depends on user scale, compliance requirements, and operational capacity; it should not be assumed mandatory for every on-device product.

    7. Evaluation: turning subjective experience into numbers

    Before shipping an on-device small model, build two evaluation sets: an offline capability set and a real-device performance baseline.

    7.1 Offline capability evaluation set

    Each case can carry fields like these:

    1. {
    2. "id": "case_001",
    3. "input": "Turn the following note into three cards",
    4. "expected_schema": ["title", "summary", "tags"],
    5. "must_fields": ["title", "summary"],
    6. "forbidden_fields": ["id"],
    7. "expected_intent": "structured card generation",
    8. "max_tokens": 512
    9. }

    Core metrics:

    • Structured output field completeness rate: fields passing schema validation divided by the total number of fields expected.
    • Instruction-following accuracy rate: samples that satisfy the rules divided by the total number of samples.
    • Extraction accuracy: exact match or F1.
    • Refusal accuracy rate: does the model refuse when it should, and does it wrongly refuse when it should not?

    7.2 Real-device performance evaluation

    Performance testing should be tiered by device class and record:

    • Cold start time.
    • Time to first token at P50, P95, and P99.
    • Per-token latency.
    • Resident memory.
    • Peak memory.
    • Temperature rise and throttling after 10 to 30 minutes of continuous inference.
    • Task success rate.
    • Cancellation response time.

    Define measurement windows explicitly. Time to first token runs from the inference call to the first displayable token; per-token latency covers the subsequent steady generation phase; thermal observation should last at least 30 minutes of sustained load.

    8. Launch checklist

    • Is the fully offline boundary explicit, with cloud use limited to an optional enhancement the user turns on?
    • Is the inference path as thin as possible, and can you compare the official reference implementation against your own wrapper?
    • Is the engine loaded as a singleton, with conversations created on demand and released?
    • Do local and cloud share one client interface?
    • Is a single scheduler or single worker consuming the priority queue, rather than a mutex standing in for a scheduler?
    • Are task cancellation, timeouts, priorities, queue capacity limits, and failure fallback supported?
    • Are long-running tasks placed in a foreground service or work queue, with progress shown?
    • Are device capability detection, multi-tier model delivery, and the degradation path implemented?
    • Does model download include hash verification, retry on failure, version rollback, and private-directory cleanup?
    • Are the open-source model license, redistribution terms, model card, and commercial restrictions reviewed?
    • Are an offline capability set and a real-device performance baseline established and included in version regression?
    • Is local data encrypted at rest, with least-privilege permissions?
    • Is generated content filtered locally, with an option to disable filtering in sensitive scenarios?

    The value of on-device small models is not that they “run,” but that they run reliably under the resource constraints of real devices. Keep the wrapper layer at the right thickness, get concurrency governance right, and complete the compliance, degradation, and evaluation work — then an offline agent becomes a genuine product capability instead of a switch that works only sometimes.