On-Device LLM Deployment on Android: Offline Inference and Local API Serving

    This article walks through running large language models locally on Android devices, covering why on-device inference matters, the practical limits of mobile inference frameworks, a step-by-step deployment flow from installation to model loading, how to read Prefill and Decode performance metrics, and how to expose a loaded model as a LAN-compatible API service. It also includes a troubleshooting checklist and guidance on splitting work between on-device and cloud inference.

    1. Why On-Device Inference Is Becoming a Requirement

    The most typical scenario for on-device inference is simple: you have only a mobile device and no workstation available, yet you still want to use a large language model for conversation. Placing the full model weights in local device storage and running inference on the device’s own processor and memory yields three direct benefits. First, the privacy boundary is clear, since input never leaves the device. Second, the cost structure is fixed, with no pay-per-call charges. Third, availability does not depend on network quality, so the model works on weak or absent connections.

    To be objective, on-device solutions are not meant to replace cloud-based models. Limited by memory capacity, thermal conditions, and power budget, a device can typically host only a smaller parameter count, and it lags noticeably behind the cloud on long-context, complex reasoning, and multi-turn tool-calling tasks. The right positioning for on-device inference is low-latency local interaction, offline fallback, data-sensitive scenarios, and lightweight inference services for other terminals on the same local network.

    2. Technical Prerequisites: What On-Device Inference Frameworks Can and Cannot Do

    Running a large model on mobile usually depends on a class of inference frameworks built for end devices. Their shared capabilities include operator-level optimization for mobile processors, conversion and quantization of common model weight formats, multi-threading and memory reuse mechanisms, and a runnable sample client that lowers the barrier to entry.

    Understanding the boundaries matters more than memorizing the feature list:

    • Memory is a hard constraint. Weights must stay resident in memory, and combined with intermediate activations during inference, actual usage exceeds the model file size.
    • Quantization is a necessity. The common approach compresses weights to a lower bit width, trading size for speed at the cost of a controlled loss in accuracy.
    • Thermals determine sustained performance. Short-term peak speed often cannot be maintained, and continuous inference triggers throttling.
    • The first load has a fixed overhead. Reading weights from storage into memory takes time, and cold-start experience scales with model size.

    3. Deployment Flow: From Getting the Package to Completing the Load

    The overall path breaks into four steps, each with details that are easy to overlook.

    3.1 Get the Client and Installation Package

    The official repository of an on-device inference framework typically publishes only source code and documentation, while prebuilt packages for ordinary users are usually posted on a separate sample-app release page. In practice, confirm the device architecture and OS version first, then pick the matching package to avoid crashes after installation caused by an instruction-set mismatch.

    3.2 Install and Update

    Version lag in package distribution is normal. If the first launch reports an available update, upgrading online is recommended, since new versions usually fix inference accuracy and memory usage issues. The upgrade is essentially a reinstall: confirm each step as prompted by the system, then verify that both the app version and the inference engine version have been updated.

    3.3 Choose a Model Size

    The client generally includes a model download entry, organized by capability type such as text chat, image understanding, text-to-image, and audio understanding. Every entry in the list shows its size, so the selection logic should revolve around the device’s compute capacity:

    Parameter scale Typical size When to choose
    Very small Hundreds of MB Instruction control and simple Q&A, speed first
    Medium Around 1 GB Balance of speed and quality, the default choice for most devices
    Larger Several GB Better quality, but noticeable heat and throttling

    A practical rule is to start with the medium size, and step down if the device heats up noticeably or slows sharply during sustained inference. Picking the largest model blindly usually produces a result that “runs but is not usable.”

    3.4 Load and Start the First Conversation

    After the download finishes, return to the local model list and double-click to trigger loading; a medium-size model generally loads within a few seconds. Once loaded, type a question in the input box and send it.

    4. Performance Evaluation: Two Metrics That Matter

    On-device experience cannot be judged only by “does it reply.” Two metrics matter:

    • Prefill (prompt processing speed): determines time to first token and is strongly tied to prompt length and context caching strategy.
    • Decode (decoding speed): determines how smoothly output continues, usually measured in tokens generated per second.

    A widely cited reference is that an average person reads at roughly a dozen tokens per second. Once decode speed exceeds that level, the conversation feels natural enough. If time to first token is high, shorten the prompt, trim the system instructions, and avoid pasting a long document all at once.

    For evaluation, keep the same device, the same model, and the same prompt for comparison, and distinguish short-term peaks from sustained performance; otherwise the numbers are not comparable.

    5. Turning a Local Model into a LAN API Service

    The added value of an on-device client is serviceability: once the model is loaded, it can expose an endpoint on the local network that is compatible with a common request format. Other devices only need to point their request URL at that device’s LAN address and port to reuse the compute. The engineering significance is that one device’s model capability is shared by multiple terminals, with no need to download weights on each one.

    Illustrative call logic (address and port are placeholders):

    1. import requests
    2. endpoint = "http://192.168.1.10:8080/v1/chat/completions"
    3. payload = {
    4. "model": "local-model",
    5. "messages": [
    6. {"role": "user", "content": "Explain on-device inference in one sentence"}
    7. ],
    8. "stream": False,
    9. }
    10. resp = requests.post(endpoint, json=payload, timeout=120)
    11. print(resp.json()["choices"][0]["message"]["content"])

    Four engineering points to note. First, the service should bind only to the LAN address and must not be exposed to the public internet. Second, without authentication any device on the same network can call it, so use it only within a controlled network. Third, concurrency is limited by memory and compute, so serialize requests or add a queue. Fourth, device sleep or the OS reclaiming the app will interrupt the service, so disable power-saving policies and keep the app in the foreground.

    6. Common Pitfalls and Troubleshooting Checklist

    • Crash after installation: usually an architecture mismatch or an OS version that is too old.
    • Load failure: insufficient memory; switch to a smaller size or clear background processes.
    • Sharp slowdown: thermal throttling; step down the size and improve cooling.
    • Other devices cannot connect: confirm the same subnet, the correct port, and that the firewall allows it.
    • Poor output quality: first adjust prompt structure and sampling parameters such as temperature, then consider switching models.

    7. How to Split Work with the Cloud

    On-device and cloud are not substitutes but layers that cooperate. A workable architecture keeps sensitive data and high-frequency short interactions local, and offloads complex reasoning, long-document processing, and batch jobs to the cloud. If unified model management and elastic compute are needed, a container platform can host the inference service, object storage can distribute model files, and logging and monitoring with alerting can track call quality. In such a layered architecture, Baidu AI Cloud typically supplies the cloud-side capabilities, while the local stage is handled by the device itself.

    8. Summary

    The value of on-device models lies not in parameter count but in placing usable inference where the data is produced. Master three things—size selection, metric interpretation, and service wrapping—and you can build a stable, offline, shareable local inference environment on a single device, laying the groundwork for later cooperation with cloud capabilities.