On-Device LLM Architecture Evolution and Inference Adaptation: A Practical Guide
This article examines how on-device and desktop LLM architectures have evolved from homogeneous Transformer stacks toward heterogeneous, efficiency-oriented designs, and what that shift means for inference engines. It breaks down the key mechanisms—per-layer embeddings, cross-layer KV sharing, K=V attention, heterogeneous KV heads, sparse experts, and native multimodality—and explains the trade-offs they make among memory, bandwidth, and compute. It then covers the core steps of adapting an inference engine (graph conversion, KV cache layout and lifecycle, layer-wise precision alignment, and performance evaluation), offers guidance on device selection and optimization, and provides a troubleshooting checklist for common problems such as semantic drift, garbled output, and multimodal misalignment. The goal is to help readers deploy these models stably and efficiently on mobile and desktop-class hardware.
1. Introduction: On-Device LLM Competition Has Shifted from Parameter Scale to Architecture Efficiency
Over the past two years, bringing open-source LLMs to the edge has mostly followed one path: stacking homogeneous Transformer layers and scaling parameters from hundreds of millions to billions. Inference engines only needed to optimize the same handful of things—GQA, quantization, and operator fusion—around a single pattern. Recent device-first models, however, show a clear trend toward architectural heterogeneity. Take, for example, a model family spanning phones to desktop-class devices:
- Its lineup covers a roughly 2B on-device form, a desktop single-GPU tier ranging from just over 1B to 3B parameters, and a sparse expert variant with about 26B total parameters that activates only about 4B per token.
- These tiers are not simple parameter scaling; they combine different architectural mechanisms.
For an inference engine, the model definition is no longer a matter of “swap the layer count, change the hidden dimension.” It is a complex compute graph with cross-layer dependencies, dynamic routing, and multimodal branches. This article approaches the topic from four angles—mechanism principles, adaptation points, evaluation methods, and practical recommendations—to discuss how to deploy this class of models stably and efficiently on edge and desktop devices.
2. Three Milestones in Architecture Evolution: From Parameter Alignment to Heterogeneous Design
Looking back at recent open-source edge models, we can identify three typical milestones (illustrated with representative configurations):
- Aligned design: Represented by early lightweight models, with homogeneous layer structure, per-layer independent KV cache, and shared weights between word embeddings and the output layer. The advantage is a regular compute graph that every inference framework can use out of the box; the cost is lower memory utilization and weaker perception of input details in shallow layers.
- On-device reconstruction: Aimed at memory-constrained mobile devices, introducing mechanisms such as cross-layer KV sharing, per-layer embeddings (PLE), separate Q/K/V normalization, and local/global hybrid attention, with the goal of preserving multimodal capability under limited memory.
- Heterogeneous and sparse: Built further on the previous generation. Some configurations drop the independent V projection and set K=V directly; some layers use the same number of KV heads as query heads (heterogeneous KV heads); local and global layers use different RoPE base frequencies; and there appear sparse expert models with large total parameters but small activated parameters.
| Mechanism | Aligned | On-device (reconstructed) | Heterogeneous / Sparse |
|---|---|---|---|
| Attention structure | Hybrid attention | Hybrid attention | Hybrid attention |
| KV cache | Per-layer independent | Cross-layer sharing for some layers | Broader cross-layer sharing |
| Embedding injection | Shared input/output embeddings | Per-layer embeddings (direct injection) | Per-layer embeddings (lookup + projection fusion) |
| Normalization | Q/K Norm | Q/K/V Norm | Q/K/V Norm, attention scaling factor = 1.0 |
| V projection | Independent | Independent | Some configs set K=V, no independent V projection |
| KV heads | Uniform across the model | Uniform across the model | Some layers match the query head count |
| Vision encoder | Vision Transformer | Lightweight backbone | Vision Transformer + pooling module |
| Audio capability | None | Convolution-augmented Transformer | Streaming convolution-augmented Transformer |
| Sparsification | Dense | Dense | 128 experts, Top-8 routing |
These changes impose four new requirements on inference engines:
- Graph structure: shifts from layer-by-layer stacking to a directed graph with cross-layer dependencies;
- Data layout: the KV cache must support sharing across multiple consumers;
- Operator set: normalization position, scaling factors, and positional encoding schemes all vary by layer;
- Scheduling strategy: sparse routing introduces dynamic execution paths.
The following sections break each of these down.
3. Key Mechanisms Explained
3.1 Per-Layer Embeddings (PLE): Trading Memory for Compute
The core idea of per-layer embeddings is to maintain an additional learnable lookup table for each layer, mapping the original token to a small-dimensional embedding vector that is then injected into that layer’s hidden state. This way, even when the hidden state has been highly abstracted in deeper layers, the original symbolic information can still be reused.
Why is it needed? A standard Transformer injects the word embedding only once, at the bottom. As the number of layers grows, information is continuously mixed and compressed, and deeper layers become less sensitive to input details such as low-frequency words, digits, and code symbols. PLE effectively provides a “bypass of original information” for each layer, letting deep layers see the raw tokens directly. This is in the same spirit as residual connections stabilizing gradients and gated recurrence preserving historical information.
Where does the cost come from? Directly copying a full word-embedding table for each layer brings unacceptable parameter and memory overhead. With a vocabulary of about 260K and a hidden dimension of 2048, a single table holds about 500M parameters; across 24 layers that is 12B—far exceeding the backbone itself. Practical solutions generally adopt low-rank strategies:
- Small-dimension lookup: each table maps only to 128–256 dimensions;
- Cross-layer sharing or grouped reuse: the injection for some layers is derived from the results of adjacent layers;
- Precision-tiered storage: lookup tables keep higher precision while projection layers participate in low-bit quantization.
Two implementation variants. The on-device (reconstructed) type is usually “inject directly after lookup”—the lookup result is added to the hidden state after a simple linear transform. The heterogeneous/sparse type adds “projection fusion”: the lookup result first passes through a projection, then is fused with the backbone output via a learnable gate. Both approaches require the inference side to retain the full lookup tensors, which often account for a substantial portion of the overall model file size.
# Per-layer embedding injection (pseudocode; dimensions use hidden size H)def layer_forward(hidden, layer_idx, token_ids):# Lookup: each layer has a small-dimension (D) embedding table; token_ids are the current token idse = ple_tables[layer_idx][token_ids] # [batch, seq, D]# Variant A: direct injection. Add directly when D == H, otherwise project W_proj: D -> H firstinjected = proj[layer_idx](e) if D != H else e# Variant B: projection fusion. After projection, combine with the backbone output via a learnable gate gout = transformer_block(hidden)fused = g * out + (1 - g) * injected # g is computed from the current statereturn fused
3.2 Cross-Layer KV Sharing: Trading Compute for Memory
The KV cache is the dominant memory cost in long-context inference. The KV footprint per token per layer can be written as:
KV_bytes/token/layer = 2 × kv_heads × head_dim × dtype_bytesTotal KV usage = KV_bytes/token/layer × number of layers with independent KV × sequence length
The idea behind cross-layer KV sharing is that several adjacent layers no longer each compute and store their own K/V, but instead read from the same set of tensors directly. It is often mistaken for merely “computing K/V projections a few fewer times,” but the real benefit goes well beyond that.
(1) The memory benefit may be underestimated. On-device memory is measured in GB, and after the framework and model are resident, the space left for the KV cache is often less than 1 GB. Every time the sequence length doubles, KV usage doubles—which usually matters more for whether the model can run at all than “computing a few fewer matrix multiplications.”
Example (illustrative estimate)
- Assumptions: 24 layers, 4 KV heads, head_dim 128, stored in FP16; of these, 20 layers share one K/V group, so the number of independent KV layers is 24 − 20 + 1 = 5.
- KV usage per token: 48 KiB without sharing (2 × 4 × 128 × 2B × 24), 10 KiB after sharing (2 × 4 × 128 × 2B × 5).
- Under a 4K context, total usage drops from about 192 MiB to 40 MiB, a reduction close to 80%.
- If KV is further quantized to INT8 or 4-bit, it can be compressed further on top of this.
Similarly, in a typical GQA configuration with 32 heads and 4 KV heads (an 8:1 ratio), KV usage is only 1/8 of MHA.
(2) The bandwidth benefit determines decode speed. During the decode phase, every generated token requires reading all historical KV—a classic memory-bound process. After sharing, the amount of K/V data read from memory by the shared layers drops proportionally.
(3) It requires “paying back” in compute. Shared layers still need to compute their own Q and perform attention against the shared K/V, so the computation is not reduced in step. However, some implementations let several layers reuse the same Q and attention output, then apply different output projections. In that case, the shared layers only carry lightweight projection computation, and the benefit finally matches the savings in memory and bandwidth.
(4) Engineering constraints cannot be ignored.
- Shared layers must depend serially on the output of the “producer layer,” so graph scheduling can no longer treat each layer as independent;
- Sharing groups may be non-contiguous, so the inference side needs an explicit “layer → KV group” mapping table;
- When switching KV layouts between Prefill and Decode, the sharing relationships must remain consistent.
3.3 Heterogeneous Attention: K=V, Heterogeneous KV Heads, and Scaling Factor
(1) K=V: dropping the V projection. Some configurations no longer compute value separately but set K=V. Note that attention output is essentially a weighted sum of value vectors; when K=V, the same tensor can be reused for both “scoring” and “weighting.” This brings two changes:
- The weight file no longer contains a V projection, and some frameworks that load weights by fixed name will fail outright;
- The attention output dimension remains the same as the conventional structure; the change is only internal to the compute graph.
(2) Heterogeneous KV head counts: local layers are not compressed. Conventional GQA uses a uniform “query heads : KV heads” ratio across the entire model, whereas some new architectures compress KV heads only in global attention layers, while local layers set the number of KV heads equal to the number of query heads. If memory is allocated uniformly by the global ratio, the actual requirement will be over- or under-estimated, so it must be counted per layer.
(3) Scaling factor of 1.0. Conventional implementations divide the attention scores by √head_dim, but some new configurations explicitly set the scaling factor to 1.0, meaning the magnitude of the logits is noticeably larger. Combined with full Q/K/V normalization (rather than only Q/K), the numerical distribution is more concentrated. The inference side needs to note two things:
- During quantization, set appropriate scales for the attention input and output to avoid overflow of intermediate values before softmax;
- Do not reuse the fixed scaling constant from older implementations.
(4) Dual RoPE: different layers use different base frequencies. Local and global layers (or different modalities such as text vs. vision/audio) may use different RoPE base frequencies, or even different positional encoding schemes, so the inference side needs to maintain a separate cos/sin cache for each layer.
# Attention computation (pseudocode): read heterogeneous per-layer configcfg = layer_configs[layer_idx] # per-layer head counts, whether K=V, scaling factor, etc.q = q_proj(x).view(seq, cfg.q_heads, head_dim)if cfg.kv_shared_from is not None:k, v = kv_pool[cfg.kv_shared_from] # reuse K/V from the producer layerelse:k = k_proj(x).view(seq, cfg.kv_heads, head_dim)v = k if cfg.k_equals_v else v_proj(x).view(seq, cfg.kv_heads, head_dim)q, k = qk_norm(q), qk_norm(k)scores = (q @ k.transpose(-1, -2)) * cfg.scale # scale may be 1.0out = softmax(scores) @ v
3.4 Sparse Experts and Native Multimodality: Activated Parameters Determine Real Cost
(1) Sparse experts (MoE). Taking “128 experts, Top-8” as an example, each token activates only about 1/16 of the experts, so total parameters and compute are decoupled. Its impact on inference shows up mainly in:
- Memory residency: all expert weights must stay resident in memory, so the edge side needs to evaluate swap-in/swap-out strategies, or use a unified memory architecture to reduce copying;
- Dynamic execution graph: routing results are only determined at runtime, so static-graph engines need to abstract “routing + grouped expert computation” into a variable-length operator;
- Load balancing: routing distributions over consecutive tokens are usually fairly concentrated, so parallel efficiency along the expert dimension can be significantly lower than the theoretical value.
(2) Native multimodality. Beyond the text backbone, the model also has a built-in vision encoder (a Vision Transformer + pooling module) and an audio encoder (a streaming convolution-augmented Transformer). Images and audio are encoded into “soft tokens” and, before Prefill, substituted into the placeholder positions in the text sequence. The key points for inference adaptation are four:
- Independent subgraph: the encoder is exported and scheduled separately, and its memory footprint should be counted in the total budget;
- Length alignment: the number of vision tokens is usually related to the number of image patches and the pooling factor, and must match the number of placeholders exactly;
- Type consistency: soft tokens and word embeddings must be unified in precision and layout before concatenation;
- Streaming audio: a streaming encoder that supports recognize-as-you-record needs to maintain a state cache and must reset it correctly when the session ends.
4. Key Steps for Adapting the Inference Engine
4.1 Graph Conversion: From Layer Stacking to Cross-Layer Dependencies
The traditional conversion pipeline treats each Transformer layer as an independent, homogeneous subgraph and simply concatenates them. Faced with heterogeneous architectures, the recommended first step is to make the process “configuration-driven”: parse the attention type, KV head count, whether KV is shared, scaling factor, positional encoding base frequency, and number of experts for each layer from the model configuration file, and generate a per-layer description table. All subsequent optimizations should be based on this table. If you still treat each layer as a homogeneous unit, the most common consequence is that shared layers misuse independent KV, and the output degrades noticeably.
4.2 KV Cache: Layout, Sharing, and Lifecycle
- Unified pooling: describe the cache as “layer group × KV heads × head_dim,” allocate a single copy of space for each sharing group, and let multiple layers read and write the same memory through a mapping table.
- Match the attention backend: paging management, sliding windows, and KV quantization all require specific memory layouts. In sharing scenarios, confirm whether the backend allows “one buffer, multiple consumers.”
- Define the lifecycle clearly: within a sharing group, only the producer layer writes and the others only read, and the write must happen before any consumer reads.
- Align before quantizing: quantizing shared layers separately introduces inconsistency, so fuse first and then quantize, or share the same set of scales.
4.3 Precision Alignment: Compare Layer by Layer, Not Just Final Results
When a “correct first token but gradually drifting afterward” problem appears in a heterogeneous architecture, it is usually not a quantization issue but a configuration-parsing error in one particular layer. A three-tier alignment approach is recommended:
- Operator level: compare the input and output of a single layer against an FP32 reference implementation;
- Layer level: use the token sequence produced by greedy decoding as the baseline and compare the cosine similarity of hidden states layer by layer;
- End-to-end: compare the logits distribution and the generated text.
A practical rule of thumb: keep the QKV projections, normalization, and softmax at FP16/FP32, quantize the weights to 4-bit or 8-bit, and retain higher precision for the lookup embeddings.
4.4 Performance Evaluation: Separate Prefill from Decode
- Prefill: focus on first-token latency (TTFT) and prefill throughput;
- Decode: focus on per-token decode latency and overall decode throughput.
It is advisable to build separate benchmark sets for “short/long context” and “text-only/multimodal,” and to record peak memory, avoiding the use of averages alone to mask long-tail problems.
5. Selection, Optimization, and Usage Recommendations
- Select by device memory: for the edge, prefer 2B–4B-class dense models; for desktop or single-GPU environments with 8 GB or more of memory, consider the tier from just over 1B to 3B parameters; sparse expert models are better suited to servers with 24 GB or more of VRAM.
- Follow a “mixed-precision” principle for quantization: use low-bit quantization for weights, choose FP16 or INT8 for the KV cache depending on precision requirements, and keep normalization and softmax at high precision.
- Get it running before optimizing: in the first adaptation round, do not enable operator fusion, graph optimization, and quantization all at once; introduce them one by one with regression checks so problems can be located quickly.
- Pay attention to long context: the impact of context length on memory and latency is often super-linear, so set upper limits based on the actual business distribution.
- Load multimodal modules on demand: if the workload involves text only, consider trimming the vision/audio branches to reduce memory usage.
- Leverage cloud resources: for cloud-based training, fine-tuning, or large-scale evaluation, cloud platforms such as Baidu AI Cloud can provide general-purpose capabilities—container platforms, object storage, logging services, and monitoring/alerting—to handle environment orchestration, data flow, and metrics observation.
6. Troubleshooting Checklist
| Symptom | Possible cause | Where to look |
|---|---|---|
| First token fine, semantics drift later | Shared KV overwritten by a consumer layer | Check shared-group write timing and the mapping table |
| Garbled or repeated output | Wrong RoPE base frequency or scaling factor | Verify the per-layer configuration parsing |
| Weight loading fails | Non-standard structures such as K=V | Loosen weight name matching, fill in optional projections |
| Sharp accuracy drop on long text | KV layout inconsistent between Prefill and Decode | Align the cache views of the two phases |
| Multimodal answers misaligned | Soft token count doesn’t match placeholders | Validate encoder output length and replacement logic |
| Abnormally high first-token latency | Frequent expert weight swap-in/swap-out | Evaluate expert residency or prefetch strategies |
7. Conclusion
The competition in on-device LLMs is shifting from “parameter scale” to “architecture efficiency.” Mechanisms such as cross-layer KV sharing, per-layer embeddings, K=V, heterogeneous KV heads, sparse experts, and native multimodality are all, at their core, redistributing the budget among memory, bandwidth, and compute. For an inference engine, the focus of adaptation has moved from “whether an operator is supported” to “whether the model’s configuration semantics can be understood correctly”: a per-layer parsed configuration table, a shared KV pooling mechanism, and a tiered precision-alignment process often determine the final experience more than operator optimization alone. On platforms such as Baidu AI Cloud Qianfan, model services likewise need targeted optimization around these low-level mechanisms to reliably and efficiently unlock the true capabilities of large models on edge and desktop devices.
