On-Device LLM Inference in Practice: A Complete Guide to Mobile GPU Acceleration and Deployment
This article walks through the full path of running large language models on mobile devices with GPU acceleration: why on-device inference is worth the effort, the real memory and compute limits of mobile SoCs, how to pick and quantize a model that actually fits, how to cross-compile the runtime and solve dynamic library lookup, how GPU backends deliver their speedup and which parameters to tune, how to expose the engine over an OpenAI-compatible HTTP API, the engineering pitfalls that surface in production, and a baseline set of acceptance metrics. It is written for engineers who need to ship stable, low-latency, offline-capable inference under tight memory, power, and thermal budgets.
1. Why Move Large Models onto the Device
The value of on-device inference is not “getting it to run.” It solves three problems at once:
- Data never leaves the device. Input is processed locally, raw text is never uploaded, and the risk of sensitive data leaking out is eliminated by construction. Compliance costs are markedly lower than a cloud-forwarding design.
- Predictable latency. Cloud inference pays a network round trip, and the experience degrades badly on weak networks — subways, underground parking garages. With local inference, time-to-first-token depends almost entirely on the device’s own compute.
- Offline availability with zero marginal cost. It still works in airplane mode, on air-gapped intranets, and while roaming abroad, and heavy usage generates no token billing.
The cost is equally direct: device memory is limited, compute is heterogeneous, and thermal and battery budgets are constrained. So the correct positioning for an on-device solution is “close the loop locally for lightweight tasks, hand complex tasks back to the cloud” — not to replace large cloud models.
2. Hardware Fundamentals: The Real Boundaries of Mobile Compute and Memory
2.1 How the Compute Units Divide the Work
A flagship mobile SoC typically integrates three kinds of programmable compute units, each suited to a different workload shape:
| Compute unit | Good at | Role in LLM inference |
|---|---|---|
| CPU (multi-core, with performance cores) | Serial logic, branch-heavy code, irregular memory access | Vocabulary sampling, sampling/decoding logic, pre- and post-processing, operator dispatch |
| GPU (tile-based rendering architecture) | Large-scale parallel dense matrix multiply-add | Runs the high-concurrency operators of the Transformer backbone; the main acceleration point |
| NPU / DSP | Low-precision fixed-point tensor math, low power | Suited to sustained workloads with a fixed operator graph, but limited in generality and operator coverage |
In practice the right approach is heterogeneous cooperation: the GPU handles the backbone matrix math, the CPU handles sampling and scheduling, and the NPU selectively takes over depending on operator support. No single unit can run the entire inference pipeline on its own.
2.2 Memory: The Actual Hard Constraint
Mobile devices use a unified memory architecture — CPU and GPU share the same physical memory, with no discrete VRAM. That forces two calculations you have to do up front:
- Static footprint = quantized weights + KV cache. The KV cache grows linearly with context length and, in long-context scenarios, often exceeds the weights themselves.
- Peak footprint = static footprint + intermediate compute tensors + framework overhead. Budget 20–30% of headroom in engineering terms.
A rough estimate: for N billion parameters quantized to 4-bit, the weights take about N × 0.55 GB. Add the context-dependent overhead on top. When per-process available memory gets tight, shrink the context length first rather than reflexively swapping in a different model.
3. Model Selection and Quantization: Squeezing the Size Down to Fit
3.1 Choosing a Quantization Format
On-device deployments generally use post-training quantization (PTQ) to bring weights down to low bit widths. The selection principle is not “fewer bits is better,” but “the best balance of perplexity and downstream task score at a given size.”
- 4-bit uniform quantization (what the industry commonly calls the Q4 family): the general-purpose default, with the best size/accuracy balance. Most instruction-tuned small models lose an acceptable amount of capability at this precision.
- 8-bit: step up a level for numerically sensitive tasks (long-chain reasoning, structured extraction, code), at double the size.
- Mixed precision (higher bits on sensitive layers): keep more bits on sensitive layers such as attention and embeddings — a cost-effective option when accuracy is the binding constraint.
3.2 Typical Size Reference
The sizes below are order-of-magnitude references only; always defer to the specific model files.
| Size class | 4-bit weight size | Fits | Notes |
|---|---|---|---|
| ~0.5B–1B dense small model | ~0.3–0.6 GB | Intent detection, short-text rewriting, summarization | Fast startup; recommended as the first thing to try |
| ~2B instruction-tuned model | ~1.0–1.5 GB | Multi-turn dialogue, general Q&A | The balance point of quality vs. size |
| Small-activation MoE model | Comparable to or slightly above the dense models in the same class | Domain-specific tasks | Large total parameters, few activated per pass; watch the weight-residency strategy |
| Small multimodal model | ~1.5–2.0 GB | Image and text understanding | Highest memory pressure; resolution and frame counts must be strictly capped |
Recommended selection order: first define the minimum viable capability for the task (score a set of 30–50 representative business samples), then work upward from the smallest size class until you clear the acceptance bar, and stop there. Do not start from the largest model and compromise downward — that usually means wasting both memory and power.
4. Setting Up the Runtime: Cross-Compiling and Dependency Management
An on-device inference engine cannot be compiled on the device itself. The standard practice is to cross-compile on the desktop side with the mobile development toolchain, producing ARM64 shared libraries and executables, then push them to the device.
4.1 Directory Layout and Dependencies
A typical build output:
/build-arm64/├── bin/│ ├── llama-cli # Interactive command-line inference│ └── llama-server # HTTP inference server└── lib/├── libggml.so # Tensor math and backend dispatch└── libllama.so # Model loading and inference logic
When pushing to the device, the relative directory structure must be preserved, otherwise the dynamic linker cannot find the dependencies. The classic symptom is an immediate startup failure with cannot open shared object file.
4.2 Resolving the Shared Library Lookup
Two common approaches:
# Option 1: set the library search path explicitly (temporary, handy for debugging)export LD_LIBRARY_PATH=/vendor/lib64./bin/llama-cli -m ./models/model-q4.gguf -p "Hello"# Option 2: bake an rpath in at compile time (recommended, more robust for release)# During cross-compilation, set -Wl,-rpath,'$ORIGIN/../lib'
Prefer rpath for production, because $ORIGIN resolves relative to the executable itself rather than depending on launch-time environment variables. This avoids path drift across different launch paths (adb shell, systemd, an in-app fork).
4.3 Model Distribution
Model files are large and should not be bundled into the app package. The sensible approach: upload training and quantization artifacts to object storage, have the app pull the right size class for its device model on first launch, verify integrity locally (digest comparison), then persist a cache. Support version-number-driven incremental updates and rollback.
5. How GPU Backend Acceleration Works, and How to Tune It
5.1 Where the Speedup Comes From
The decoding phase of a Transformer is fundamentally a large volume of “matrix × vector” and “matrix × matrix” operations — highly data-parallel but memory-access-heavy. The job of a GPU backend is to split the operator graph into a set of kernels, execute them simultaneously across thousands of parallel threads, and stream weights into shared memory in tiles. The gains usually come from three places:
- Operator-level reimplementation: writing dedicated matrix-multiply, attention, normalization, RoPE, and activation kernels for mobile graphics APIs.
- Memory layout optimization: rearranging weights according to the GPU’s tiling and swizzling patterns to improve cache hits.
- Amortizing dispatch overhead: submitting as much compute as possible per call to reduce CPU↔GPU synchronization round trips.
5.2 Key Tuning Parameters
# General shape of a serving launch./bin/llama-server \-m ./models/model-q4.gguf \--n-gpu-layers 99 \ # Layers offloaded to the GPU; reduce step by step if memory runs short--ctx-size 4096 \ # Context length; directly determines KV cache size--batch-size 256 \ # Batch size; affects prefill throughput--threads 4 \ # CPU-side thread count; match the number of performance cores--host 0.0.0.0 --port 8080
Suggested tuning order:
--n-gpu-layers: start with a full offload. If you hit OOM or frequent fallbacks to the CPU, bisect downward until it is stable. This is the first lever for both memory and speed.- Context length: don’t set it to the model’s maximum out of habit. The KV cache difference between 4K and 32K can be several times over.
- Thread count: align with the number of performance cores. Too many threads cause cross-core migration and synchronization overhead and end up slower.
- Batch size: mainly affects prefill throughput. Noticeable gains for long documents; keep the default for short conversations.
5.3 Treat the Two Phases Separately
The on-device experience is determined by two metrics that must be measured independently:
- Prefill (processing the input prompt): influenced by both compute and memory bandwidth; determines time-to-first-token (TTFT).
- Decode (generating tokens one at a time): reads all the weights on every step, a classic memory-bandwidth-bound workload; determines tokens/s.
A common mistake is judging performance from tokens/s alone and calling it “fast enough.” In real conversations, prefilling a long instruction often consumes most of the wait, and that time is not counted in the generation speed.
6. Serving Layer: Making the Engine Invisible to the Application
On-device inference engines usually expose an HTTP interface so that WebViews, native apps, and scripts can all integrate the same way:
# Start the local inference service./bin/llama-server -m ./models/model-q4.gguf --n-gpu-layers 99 --port 8080# Example call (OpenAI-compatible chat-style endpoint)curl -s http://127.0.0.1:8080/v1/chat/completions \-H "Content-Type: application/json" \-d '{"messages": [{"role":"user","content":"Explain quantization in one sentence"}],"temperature": 0.3,"max_tokens": 256,"stream": true}'
Streaming output is a key design decision for on-device UX: even if generation runs at only a handful of tokens per second, getting the first token out quickly reduces the perceived wait by an order of magnitude.
Security note: this service has no authentication by default, and binding to 0.0.0.0 exposes it to everything on the same LAN. On-device, bind to 127.0.0.1 and add token validation at the application layer; open up the listening scope only in debug mode.
7. The Real Engineering Pitfalls
- Shared library and ABI mismatches: when the cross-compilation toolchain version diverges too far from the device’s OS version, the usual crash point is missing C++ runtime symbols. Run a compatibility matrix against target devices before release.
- Getting killed for memory: under high load, the system’s reclamation policy may terminate the process outright. Persist state from lifecycle callbacks and support fast cold-start recovery of conversation context.
- Power and thermal throttling: sustained full load heats the SoC quickly and triggers downclocking, so the speed in the first 20 seconds and the speed after 3 minutes can differ by 2×. Acceptance must be based on the sustained-load curve, not the instantaneous peak.
- First-load stall: model loading involves large-file I/O and graph construction. Do it on a background thread and show progress, so the main thread is never blocked and flagged as unresponsive.
- Accuracy regressions: switching quantization formats or backends requires re-running the business evaluation set. Low-bit quantization can break output formatting on a small number of structured tasks.
8. Device–Cloud Collaboration: A Sensible Division of Labor
Putting training, quantization, and evaluation in the cloud while keeping inference on the device is the most cost-efficient architecture. On the cloud side, general-purpose service categories cover these stages:
- Container platforms: build reproducible quantization and conversion pipelines so artifacts stay traceable.
- Object storage: distribute model files, supporting per-device-model size tiers and staged rollouts.
- Log services plus monitoring and alerting: collect on-device latency, failure rates, and throttle counts, and roll back versions promptly when quality degrades.
- LLM service APIs: when on-device capability is insufficient (long-form generation, complex reasoning, heavy multimodal tasks), route to the cloud as a fallback.
The general-purpose capabilities Baidu AI Cloud offers for this kind of device–cloud architecture are exactly that combination: training/quantization pipelines, model hosting and distribution, and runtime observability — letting lightweight on-device inference and stronger cloud models complement each other rather than sit in isolation.
9. Suggested Acceptance Metrics
At minimum, fix these five metrics so you have a comparable baseline:
| Metric | Definition | Reference target |
|---|---|---|
| TTFT | From request issued to first token | ≤ 1.5s for short instructions |
| Generation speed | tokens/s during decode | ≥ 8 tokens/s is acceptable |
| Peak memory | Peak process RSS | Under 70% of available memory |
| Sustained stability | Performance decay after 5 minutes at full load | ≤ 30% decay |
| Task accuracy | Pass rate on the business evaluation set | Meets the agreed acceptance bar |
10. Conclusion
The hard part of on-device LLM inference has never been “can it run” — it is making the experience stable under three simultaneous constraints: memory, power, and thermals. The methodology reduces to four sentences: trade quantization for size, trade heterogeneity for throughput, trade streaming for perceived latency, and trade device–cloud collaboration for a higher capability ceiling. Get the whole pipeline working end to end with the smallest viable model first, then step the size up tier by tier while hardening evaluation and monitoring in step. That is the lowest-risk and fastest-iterating path.
