On-Device Large Model Architecture Evolution and Inference Adaptation: A Complete Guide
As large models move from the cloud to end devices, running them well on real hardware has become an inference-engineering problem rather than a matter of shrinking a cloud model. This article explains how on-device large models evolved across three stages, breaks down the key mechanisms that make on-device inference harder (per-layer embedding, KV-cache sharing, heterogeneous attention heads, multimodal fusion, and sparse expert routing), and shows how to adapt an inference engine from model parsing to production monitoring. It also outlines an evaluation framework covering quality, performance, and stability, plus deployment guidance for phones, desktop workstations, and servers under a cloud-device collaboration model. The goal is to help developers and enterprise teams evaluate whether an on-device large model is worth adopting and turn architecture innovations into stable, observable inference capabilities.
1. Background: On-Device Large Models Are Not Just Smaller Cloud Models
As large model capabilities extend from the cloud to end devices, on-device hardware, edge devices, desktop workstations, and server-grade inference environments have all started running different kinds of large model workloads. Compared with the past scenario of a single cloud call, on-device models must contend with far stricter resource constraints: limited memory capacity, power sensitivity under sustained inference, low cold-start latency requirements, and high demands for offline privacy protection. As a result, whether a model runs reliably in a real device environment depends not only on parameter count, but also on architecture design, inference-engine adaptation, and deployment engineering maturity.
A typical characteristic of a new generation of multi-size large models is that different parameter sizes are not simple homogeneous scaling. Instead, they combine different architectural mechanisms to produce differentiated variants aimed at different hardware scenarios. For example, small-parameter models focus on low latency, low memory, and low power; medium-parameter models emphasize an overall experience on the desktop; and large-parameter models are better suited to server-side high concurrency, multitasking, and complex reasoning. Because model structures, attention forms, caching strategies, input modalities, and expert-routing methods differ, an inference engine that still relies on fixed assumptions will run into problems such as inaccurate memory or VRAM estimation, missing operator support, reduced batching efficiency, and insufficient long-context stability.
This article is organized around five areas—architecture evolution, key mechanisms, inference-engine adaptation, evaluation methods, and deployment recommendations—to discuss how to more reliably support large model applications in cloud-device collaboration scenarios.
2. Architecture Evolution: From General-Purpose Large Models to On-Device-Friendly Models
The development of on-device large models did not happen overnight. Early general-purpose large models typically targeted cloud-based offline batch processing or high-throughput serving, and their architecture design emphasized training stability and large-scale parallel efficiency. Later, in order to enter terminal scenarios such as phones, tablets, and smart hardware, models began to adopt dedicated designs for end devices. Eventually, models further integrated multimodal capabilities such as vision and audio, and expanded in directions like cache reuse, embedding injection, and sparse experts.
From an architecture-evolution perspective, this can be summarized in three stages.
2.1 General-Purpose Large Model Stage: Pursuing Expressiveness and Training Efficiency
Early general-purpose models typically used a fairly complete attention structure, in which every layer independently maintained its own key-value (KV) cache. Input embeddings generally acted only on the first layer, and subsequent layers passed information forward through hidden states layer by layer. This structure is simple to implement and has a clear inference path, making it suitable for high-throughput cloud deployment. However, it introduces two obvious pressures on end devices:
- Independent per-layer caching causes memory usage to grow linearly with the number of layers;
- In long-context scenarios, high cache read/write frequency can easily create a bandwidth bottleneck.
Therefore, directly migrating a general-purpose model to a terminal device often leads to high memory peaks, insufficient stability during sustained conversations, and high long-text inference costs.
2.2 On-Device Dedicated Stage: Reconstructing Model Structure Around Resource Constraints
To adapt to terminal devices, on-device dedicated models began introducing a series of resource-saving designs. Typical changes include:
- Sharing KV caches between some layers to reduce total cache size;
- Introducing a per-layer embedding mechanism so that input information participates in computation more flexibly across different layers;
- Adjusting the normalization structure to improve training and inference stability for small-parameter models;
- Adding lightweight vision or audio modules so that on-device models have basic multimodal capabilities.
The core goal of this stage is not simply to pursue a larger parameter count, but to maintain usable language-understanding ability as much as possible under limited memory, compute, and power budgets.
2.3 New-Generation Multi-Size Models: More Complex Architectural Combinations
New-generation models push on-device optimization mechanisms further in a more systematic direction. Different sizes may adopt different structural combinations, for example:
| Capability Dimension | Early General-Purpose Model | Transitional On-Device Model | New-Generation Multi-Size Model |
|---|---|---|---|
| Attention mechanism | Standard hybrid attention | Mixed local and global attention | Dynamic combination of local windows and global attention |
| KV cache | Independent cache per layer | Shared cache across some layers | More layers share caches and support heterogeneous KV heads |
| Embedding method | Standard shared embedding | Per-layer lookup-table injection | Per-layer lookup combined with projection fusion |
| Normalization design | Query and key normalization | Query, key, and value normalization | Adds attention scaling and numerical-stability strategies |
| Value projection design | Independent value projection per layer | Independent value projection per layer | Some layers reuse the key representation, reducing projection branches |
| Visual input | General-purpose visual encoder | Lightweight visual encoder | Visual encoding fused with pooling |
| Audio input | Not supported | Convolutional audio encoding | Streaming audio recognition aligned with text |
| Expert structure | Dense parameters | Dense parameters | Sparse experts with dynamic routing |
| Unique mechanisms | None | Lightweight bypass and activation sparsity | Cache reuse, heterogeneous KV heads, dual positional encoding |
As this shows, new-generation models are not the enhancement of any single technology, but a systems-engineering effort built by stacking multiple mechanisms. This also means an inference engine cannot merely understand that “this is a Transformer-type model”; it must also understand the specific differences in layer count, cache grouping, embedding paths, modal inputs, and expert activation.
3. Key Mechanisms: Why On-Device Inference Is Harder
3.1 Per-Layer Embedding: Better Expressiveness, More Complex Memory Management
In traditional large models, input text is first converted into word vectors and then fed only into the first layer; subsequent layers rely on hidden states to continue computation. The per-layer embedding mechanism allows the input representation to participate in fusion more directly across different layers, improving the model’s ability to connect shallow features with deep semantics.
The advantages of this design are:
- Small-parameter models can make fuller use of input information;
- It is friendlier to short-text, instruction-following, and multi-task conversation scenarios;
- Under limited on-device resources, it helps improve the expressive efficiency per parameter.
However, the inference engine must handle several additional issues:
- Each layer may need to read a different embedding vector independently;
- If a lookup-plus-projection-fusion approach is used, it introduces additional small-scale matrix computation;
- If embedding vectors are long, resident memory usage increases;
- Under concurrent requests, shared embeddings and request-private embeddings must be distinguished.
For this reason, the inference engine should ideally model per-layer embedding as an independent resource pool and support on-demand loading, precomputation, and lifecycle management.
3.2 KV-Cache Sharing: A Key Design for Reducing Memory Peaks
KV-cache sharing is a very typical optimization direction for on-device models. In traditional models, every layer must store its own KV cache; sharing mechanisms allow some layers to reuse the same set of caches, or to reference the same key-value tensors across layers.
The benefits come mainly in three aspects:
- Reducing KV-cache memory usage;
- Lowering memory or VRAM bandwidth pressure during the decoding phase;
- Improving sustained-inference stability in long-context scenarios.
That said, the engineering implementation is not simple. The inference engine needs to clarify the following questions:
- Which layers can share caches and which must remain independent;
- Whether the update strategy for shared caches is append, overwrite, or read-only reuse;
- Whether different batch requests can safely reuse the same cache;
- When a sharing group spans layers, how to guarantee correct attention results;
- How to avoid reference-counting errors during cache eviction and reclamation.
A relatively robust approach is to introduce the concept of a “cache group”: map shareable layers to the same cache object, and allocate separately for non-shareable layers. The pseudocode can be expressed as follows:
for layer in model.layers:if layer.kv_share_group is not None:kv_cache = shared_cache_pool.get(layer.kv_share_group)else:kv_cache = layer_cache_pool.allocate(head_count=layer.kv_head_num,max_seq_len=layer.max_seq_len)process_layer(layer, kv_cache)
This turns cache sharing from an “implicit assumption” into “explicit resource management.”
3.3 Heterogeneous KV Heads and Layer-Level Value-Projection Skipping: Execution Plans Must Become Dynamic
Some new-generation models no longer use a fully uniform attention-head structure. Different layers may have different numbers of KV heads, and some layers may lack an independent value projection and instead directly reuse the key representation.
This heterogeneous design reduces wasted computation and lowers parameter redundancy, but it places higher demands on the inference engine:
- The attention shape of each layer may differ;
- Operator kernels cannot assume a fixed number of heads;
- Batching requires building different execution plans per layer;
- Cache layout must support variable head counts and different dimensions;
- Quantization strategies must account for inter-layer differences.
If the inference engine still relies on a static graph or fixed templates, it can easily encounter shape mismatches, out-of-bounds memory access, or sudden performance drops. Therefore, a more mature approach is to generate independent metadata for each layer, including:
layer_idattention_typekv_head_countvalue_projection_enabledcache_group_idembedding_moderope_mode
The inference runtime then dynamically selects operators, cache strategies, and batching methods based on this metadata.
3.4 Multimodal Support: More Than Adding a Vision Module
Once on-device models gain vision and audio capabilities, the inference pipeline expands from pure text to multimodal fusion. Visual input is typically converted by an image encoder into visual tokens and then concatenated with text tokens; audio input needs to go through frame-level encoding, temporal alignment, and semantic projection.
The main difficulties of multimodal inference include:
- Image and audio preprocessing can be time-consuming and easily become an end-to-end bottleneck;
- The large number of visual tokens significantly increases sequence length;
- Multimodal encoders generally have higher precision requirements than the language backbone;
- Streaming audio input needs to support incremental decoding and resumable processing;
- Text generation and visual encoding may need an asynchronous pipeline.
Therefore, the inference system should decouple multimodal preprocessing from language-backbone inference as much as possible. For example, visual frames can be encoded and cached ahead of time, audio streams can be processed incrementally with a sliding window, and ultimately only the compressed semantic tokens are fed into the language model.
3.5 Sparse Expert Structures: Large Total Parameters, Dynamic Activation Paths
Some large model sizes introduce a sparse expert mechanism. Such models have a large total parameter count, but each inference activates only a small number of experts. The advantage is that model capacity can be expanded under a controllable amount of computation, but it also brings engineering challenges:
- Expert routing results are dynamic, making batching more difficult;
- If expert distribution is uneven, hot-spot experts can appear;
- Cold start requires loading or indexing a large number of expert weights;
- Under concurrent requests, expert switching can cause cache thrashing;
- If an on-device system lacks sufficient memory, expert-loading strategies must be designed carefully.
For these models, the inference engine needs to support dynamic routing, expert hotness statistics, and on-demand loading. For cloud high-throughput scenarios, experts can be kept resident and merged into batches; for low-memory on-device scenarios, sparse deployment, quantized compression, or local expert caching must be considered.
4. Inference-Engine Adaptation in Practice: From Model Parsing to Production Monitoring
4.1 Build a Unified Model-Structure Abstraction
Faced with multiple sizes and multiple architectural combinations, an inference engine must first abstract the model structure into a unified intermediate representation. At minimum, this representation should include the following information:
- Number of layers, hidden dimension, and attention type;
- Number of KV heads and cache-sharing relationships;
- Per-layer embedding paths and projection methods;
- Normalization positions and numerical-stability parameters;
- Positional-encoding form;
- Input/output specifications for visual and audio encoders;
- Sparse-expert routing strategy.
Only after completing this structural abstraction can subsequent operator selection, memory allocation, and batching scheduling rest on a stable foundation.
4.2 Cache Pooling: Turning Sharing Relationships into Manageable Resources
KV-cache sharing is not simply about “allocating one less block of memory”; it requires complete cache-lifecycle management. It is recommended to divide caches into multiple resource pools:
- Shared cache pool: for KV caches reused across layers;
- Request-private cache pool: for independent layers within a single request;
- Multimodal feature pool: for outputs of visual and audio encoders;
- Expert-weight cache pool: for dynamic residency of hot-spot experts;
- Temporary computation pool: for attention intermediate results and temporary normalization tensors.
Each resource pool should support reference counting, capacity watermarks, eviction policies, and metric reporting. This avoids memory fragmentation or cache leaks during long-context inference.
4.3 Operator Fusion: Reducing Memory-Access and Scheduling Overhead on Devices
On-device systems are usually very sensitive to memory bandwidth and power consumption. Inference engines can use operator fusion to reduce reads and writes of intermediate tensors and the number of kernel launches. Common fusion points include:
- Fusing layer normalization with residual connections;
- Fusing query, key, and value projections;
- Fusing rotary positional encoding with attention projections;
- Fusing attention-score scaling with mask handling;
- Fusing output projection with residual addition;
- Merging per-layer embedding lookup with fusion computation.
It is worth emphasizing that fusion should not pursue only a reduction in kernel count; numerical stability must also be considered. Especially when using low-precision computation, necessary normalization safeguards, scaling factors, and high-precision accumulation strategies should be retained.
4.4 Quantization Deployment: Not Every Module Should Use the Same Precision
Quantization is an important tool for on-device model deployment, but different modules differ in precision sensitivity. In general:
- The large matrix operations of the language backbone can be moderately quantized;
- The embedding layer and per-layer embedding projections are relatively sensitive to semantic impact;
- Visual encoders and audio encoders should maintain relatively higher precision;
- KV-cache quantization can save memory, but long-context stability must be evaluated;
- Sparse-expert routing results should retain higher precision to avoid routing drift.
A more robust approach is a mixed-precision strategy: apply low-bit quantization to compute-intensive but fault-tolerant parts, and retain higher precision for precision-sensitive small modules.
4.5 Scheduling Optimization: Prefill and Decode Should Be Modeled Separately
Large model inference is usually divided into a prefill phase and a decode phase. The prefill phase processes the input prompt and is compute-intensive; the decode phase generates tokens one by one, is memory-access-intensive, and is latency-sensitive. On-device scenarios especially require distinguishing these two phases.
The prefill phase can:
- Merge multiple request inputs;
- Process visual or audio features in parallel;
- Build cache structures ahead of time;
- Compute long prompts in chunks.
The decode phase can:
- Use continuous batching to improve throughput;
- Reduce the number of reads for shared-cache layers;
- Keep multimodal feature caches resident;
- Lower perceived latency through streaming output.
If a scheduler mixes prefill and decode together, it can easily cause jitter in time-to-first-token and also affect the stability of subsequent token generation.
4.6 Cloud-Device Collaboration: Devices Handle Low Latency, the Cloud Handles Elastic Scaling
On-device models are not meant to fully replace cloud models, but to complement them. A reasonable division of labor can balance privacy, latency, and cost:
- For privacy-sensitive tasks, complete them on the local device first;
- For low-latency interactive tasks, prefer small on-device models;
- For complex reasoning, long-document analysis, or high-accuracy multimodal tasks, call cloud models;
- For model version management, use the cloud for unified distribution and canary updates;
- For runtime stability, continuously observe via log collection, metric monitoring, and alerting systems.
When putting cloud-device collaboration into practice, teams can leverage general-purpose capabilities available in cloud environments such as Baidu AI Cloud—for example, container platforms, logging services, monitoring and alerting, and model distribution mechanisms—to handle model version management, resource scheduling, canary releases, and runtime metric observation. These general-purpose capabilities help teams move a model from an experimental environment into production and continuously improve stability.
5. Evaluation Methods: Don’t Look at Single-Output Quality Alone
Evaluating on-device large models requires covering quality, performance, and stability at the same time. It is recommended to build an evaluation system across the following dimensions.
5.1 Quality Dimension
Quality evaluation should include:
- Basic language-understanding ability;
- Instruction-following and format-constraint ability;
- Long-text summarization and information-extraction ability;
- Semantic understanding in Chinese-language scenarios;
- Code generation and logical reasoning;
- Visual-alignment ability in multimodal question answering;
- Audio transcription and streaming recognition ability.
Evaluation should not rely on a single short-text sample; instead, it should cover inputs of different lengths, different difficulty levels, and different modalities.
5.2 Performance Dimension
Performance metrics should include at least:
- Time to first token;
- Per-token decode latency;
- Tokens generated per second;
- Throughput under concurrent requests;
- Memory or VRAM peak;
- Cold-start time;
- Latency growth under long context;
- End-to-end time under multimodal input;
- Device power consumption and temperature rise.
For on-device systems, power consumption and temperature rise often affect the real experience more than peak throughput.
5.3 Stability Dimension
Stability evaluation needs to focus on:
- Whether cache expansion occurs during long conversations;
- Whether semantic drift occurs across multiple rounds of generation;
- Whether shared caches cause context cross-talk;
- Whether the system can safely degrade when audio or visual input is abnormal;
- Whether there is a graceful reclamation strategy when memory is insufficient;
- Whether routing hot spots or expert-loading failures occur under high concurrency.
A reliable inference system must not only work under ideal inputs, but also maintain predictable behavior under abnormal inputs and constrained resources.
6. Deployment Recommendations: Choose the Right Size for Each Scenario
6.1 Phones and Low-Power Terminals
Phone terminals should prioritize small-parameter, low-latency models. This scenario needs focused optimization on:
- Memory usage and background-residency strategy;
- Time to first token and smoothness of continuous conversation;
- Power consumption and temperature-rise control;
- Local privacy protection;
- Integration with system-level voice and vision capabilities.
For small-parameter models, per-layer embedding and cache sharing are often more valuable than simply increasing the parameter count.
6.2 Desktop Workstations and Development Devices
Desktop systems usually have stronger memory and compute, so they can choose medium-parameter models for code assistance, document understanding, knowledge question answering, and lightweight multimodal tasks. The focus here should be on:
- Long-context stability;
- Multimodal file-parsing efficiency;
- Batch-task throughput;
- Integration with the local development environment;
- Log collection and problem-localization ability.
6.3 Servers and Cloud Platforms
Server scenarios are better suited to large-parameter or sparse-expert models, which fit multi-user concurrency, complex reasoning, and cross-modal tasks. Cloud deployment needs to focus on:
- Batching scheduling efficiency;
- Expert-routing balance;
- Cache reuse and request isolation;
- Model hot updates and canary releases;
- Monitoring, alerting, and capacity planning;
- Coordination with general cloud components such as object storage, message queues, and container platforms.
7. Conclusion: The Core of On-Device Large Model Competition Lies in Inference Engineering
The real challenge of new-generation multi-size large models is not just model training, but how to make different architectural mechanisms run stably, efficiently, and observably in a real inference environment. Designs such as per-layer embedding, KV-cache sharing, heterogeneous attention heads, multimodal fusion, and sparse experts all change the inference engine’s assumptions about memory, operators, and scheduling.
For developers and enterprise users, evaluating whether an on-device large model is worth investing in cannot rely only on the advertised parameter count or single-query results. Instead, start from the following questions:
- Is the model structure clear, and can it be parsed accurately by the inference engine?
- Is cache sharing reliable, and is there a risk of memory leaks?
- Does multimodal input support asynchronous processing and degradation?
- Does the model still maintain key-task accuracy after quantization?
- Does it support continuous batching, streaming output, and cloud-device collaboration?
- Does it have a complete logging, monitoring, and canary-release mechanism?
In the long run, the value of on-device large models lies not in simply replacing the cloud, but in building a more complete AI application infrastructure through local inference, privacy protection, low-latency interaction, and cloud-device collaboration. Only by truly converting architectural innovation into stable inference-engineering capability can on-device large models continuously deliver value in real business.
