On-Device LLM Architecture: Core Mechanisms and Inference Engine Adaptation
This article analyzes the structural evolution of open-source lightweight large language models for on-device deployment. It focuses on five recurring mechanisms—cross-layer KV cache sharing, layer-wise embeddings, asymmetric attention structures, sparse mixture-of-experts, and native multimodal integration—and explains why they are introduced, where they constrain inference engines, and how to validate them. It also covers graph construction, kernel fusion, KV cache and paging management, differentiated quantization, export pipelines, numeric consistency checks, scenario-based metrics, and practical pitfalls.
On-Device LLM Architecture: Core Mechanisms and Inference Engine Adaptation
1. Background: Open-Source Lightweight Models Are Entering an Architecture Divergence Phase
1.1 Parameter Count Is No Longer the Only Axis
Over the past two years, the evolution of open-source small-parameter models has mainly followed an “isomorphic scaling” approach: using a fixed Transformer structure and extending it linearly through layers, width, and vocabulary size. This approach has one clear advantage: inference engines only need to support one operator path. Its disadvantage is that quality improvements suffer rapidly diminishing marginal returns. Under an on-device budget of 2B–4B parameters, simply adding parameters yields far less benefit than structural redesign.
As a result, a set of “high-density” model families has appeared. These include on-device specifications of 2B–4B parameters, or even sub-2B; desktop-level specifications of 10B–30B; and server-level specifications ranging from tens of billions of parameters to sparse expert forms. Their common feature is not larger parameter counts, but the introduction of structural mechanisms targeting memory bandwidth, long context, and multimodal workloads.
For inference engines, this shifts adaptation from parameter tuning to capability expansion. Kernels must support new cache layouts, quantization must use different strategies for different layer groups, and computational graphs must accommodate asymmetric attention head configurations.
1.2 Key Difficulty: Mechanisms Differ Even Within the Same Model Family
The more challenging issue is that different specifications in the same family are not simple parameter scaling; they are combinations of different architectural mechanisms:
- Smaller specifications tend to use aggressive cross-layer KV reuse and aggressive low-bit quantization to reduce memory usage.
- Desktop specifications usually retain independent KV layers and may add sparse experts to preserve quality.
- Multimodal specifications additionally require visual encoders, audio encoders, and modality projection layers.
Therefore, inference engines cannot be adapted to “one model” in isolation. They need to be adapted to a matrix of mechanism switches. Engineering-wise, the same code should describe differences through configuration rather than creating separate branches for each specification. Otherwise, maintenance costs will explode as the number of specifications grows.
1.3 Scope of This Article
This article does not discuss models or tools from any specific vendor. It focuses on five mechanisms that repeatedly appear in this generation of open-source lightweight models:
- Cross-layer KV reuse
- Layer-wise embeddings
- Asymmetric attention structures
- Sparse mixture of experts
- Native multimodal integration
The article answers three questions: why each mechanism is introduced, where it constrains inference-side implementation, and how to validate it.
2. Architecture Evolution: Structural Comparison Across Three Generations
The table below summarizes the evolution of on-device-friendly models into three stages. The generations are general classifications and do not refer to specific products.
| Feature | First Generation (Dense On-Device) | Transitional Generation (On-Device Multimodal) | Current Generation (Diverging Series) |
|---|---|---|---|
| Attention pattern | Mix of global and local sliding-window attention | Mixed | Mixed, with adjustable ratio of windowed and global layers |
| KV cache | Independent per layer | Partially shared, about 10 layers per group | Larger layer groups, about 18–20 layers per group |
| Token embeddings | Globally shared embedding | Layer-wise embeddings with direct lookup injection | Layer-wise embeddings with lookup plus low-rank projection fusion |
| QKV normalization | Q/K Norm | Q/K/V Norm | Q/K/V Norm, attention scale factor of 1.0 |
| V projection | Independent v_proj | Independent v_proj | Some specifications set K = V and remove independent v_proj |
| KV heads | Uniform | Uniform | Heterogeneous; different layers use different numbers of heads |
| Position encoding | Single RoPE base frequency | Single base frequency | Dual base frequencies; local and global layers use different values |
| Vision encoder | ViT trained with contrastive learning | Lightweight convolutional backbone | ViT plus pooling module |
| Audio encoder | None | Convolutional augmented Transformer | Enhanced convolutional-augmented Transformer |
| Sparse experts | None | None | Yes; hundreds of experts with Top-k routing |
| Unique mechanisms | — | Periodic parameter upsampling, activation sparsification | K = V, heterogeneous KV heads, dual-base RoPE |
Three clear evolution patterns can be read from the table:
- Memory priority: KV reuse layer groups expand from about 10 layers to 18–20 layers, with memory benefits scaling nearly linearly.
- Quality compensation: compressing KV inevitably reduces expressiveness, so layer-wise embeddings inject additional layer-specific signals to compensate.
- Capability expansion: vision, audio, and sparse experts are gradually integrated into the same backbone rather than attached as separate models.
3. Core Mechanism Breakdown
3.1 Cross-Layer KV Cache Sharing
Principle
In standard decoding, each layer has independent Key/Value projections and cache entries. However, it has been observed that K/V representations generated by adjacent layers are highly correlated in representation space. Therefore, a layer group can be defined, where layers within the group share the same K/V cache. Only the Query projection and output projection remain layer-specific. Equivalently, attention in the i-th layer of a group uses the K/V computed by the first layer of the same group.
Illustrative implementation:
# Illustrative example: sharing KV within layer groupsdef build_layer_groups(num_layers, group_size):groups = []for start in range(0, num_layers, group_size):groups.append(list(range(start, min(start + group_size, num_layers))))return groups# During decoding, only the first layer in a group computes KV projections and writes to the cachedef decode_step(layer_idx, group_id, x):if layer_idx == group_members[group_id][0]:k, v = kv_proj(x) # The only KV computation pointkv_cache.write(group_id, k, v)q = q_proj(x)out = attention(q, kv_cache.read(group_id))return out_proj(out)
Memory benefit
The KV memory footprint for a single token is proportional to:
2 × num_groups × kv_heads × head_dim × dtype_size
If the original model has 48 independent layers, changing to groups of 18 layers reduces num_groups from 48 to 3, and KV memory drops to about 6%. This is a fundamental reason why such models can support 32K context on-device, and it is also one of their strongest selling points.
Adaptation points
- Non-uniform layout: different layer groups may have different numbers of kv_heads, as discussed in Section 3.3. Paged cache implementations cannot assume a globally uniform page shape.
- Single write point: when fusing computational graphs, if an optimizer mistakenly lowers the KV projection to every layer in a group, memory usage may increase instead of decrease, while numerical outputs may still look correct, making the issue extremely difficult to debug.
- Prefix cache compatibility: shared layer groups can still support prefix caching, but hit granularity must align with layer group boundaries rather than individual layers.
3.2 Layer-wise Embeddings
Why they are needed
When KV cache is reused, historical information seen by deeper Query layers becomes compressed. Layer-wise embeddings address this by injecting a separate, lower-dimensional embedding representation into each layer. This redistributes token surface information and positional information across layers to compensate for reduced expressiveness.
Two common forms
- Direct lookup injection: each layer maintains a small table of shape
(vocab_size, d_per_layer). After tokenization, the token is looked up and added to that layer’s input. - Lookup plus low-rank projection fusion: on top of the lookup table, a low-rank matrix projects the table vector into the hidden dimension and fuses it with the main residual stream.
The first form saves compute. The second improves quality but adds one GEMM per layer. The transitional generation mostly uses the first form, while the current generation mostly uses the second.
Cost and quantization
- The additional parameter count is approximately
num_layers × vocab_size × d_per_layer. When the vocabulary is very large, such as hundreds of thousands of tokens, and the model has many layers, this overhead is not negligible and should be budgeted separately. - At inference time, each layer incurs an extra gather and projection, making this stage sensitive to memory bandwidth. In on-device measurements, this overhead often accounts for a noticeable portion of decode time. When writing fused kernels, gather, projection, and bias addition should be merged into a single operator.
- These tables are sensitive to quantization error. They usually retain higher precision, at least 8-bit. They should not be aggressively quantized to 4-bit together with the main backbone, otherwise first-token quality may degrade significantly.
3.3 Asymmetric Attention Structure
The current generation breaks away from homogeneous design through four major changes:
- Q/K/V normalization: compared with only normalizing Q/K, adding V normalization helps suppress extreme activations, but it also changes the output distribution. Quantization calibration sets must include long-text samples.
- Attention scale factor of 1.0: this removes the multiplication before softmax. It means the 1/√d factor must be folded into the Q or K projection weights. This is easy to miss during export, and the symptom is that logits are uniformly amplified.
- K = V, no independent v_proj: the Key projection output is directly reused as Value, saving one set of weights. In fused kernels, one tensor is consumed by two downstream operations, so constant folding and alias analysis must handle this case correctly.
- Heterogeneous KV heads: different layer groups may use different numbers of KV heads. For example, global layers may use 2 heads while local layers use 8 heads. This requires the cache allocator to support different page shapes per layer group. The assumption of uniform contiguous memory allocation no longer holds.
In addition, dual-base rotary position embedding lets local layers use a larger base frequency for smoother short-range resolution, while global layers use a smaller base frequency for longer-range extrapolation. Inference engines need to maintain two sets of cos/sin tables and select them by layer index. Long-context extrapolation behavior cannot be inherited from single-base models and must be evaluated separately.
3.4 Sparse Mixture of Experts
Server and desktop specifications may introduce sparse structures with hundreds of experts, such as 128 experts with 8 activated per token. The value is that total parameters can be large while activated parameters remain small. For example, a 26B total-parameter model with about 4B activated parameters can approach the quality of a dense 30B model while requiring compute closer to a 5B model.
There are three practical challenges for on-device deployment:
- Weight residency: total expert weights far exceed available memory, so only a subset can remain resident and others must be loaded on demand. In practice, memory mapping combined with page caching can keep hot experts in memory.
- Routing imbalance: a small number of experts handle most tokens, causing tail latency. Engineering methods include capacity-factor constraints, load balancing during expert parallelism, and offline analysis of routing distributions for prefetching.
- Quantization strategy: expert weights are suitable for 4-bit quantization, but routers usually need higher precision. Otherwise, Top-k selection becomes unstable, leading to unstable outputs or even significantly different results for the same prompt across multiple generations.
3.5 Native Multimodal Integration
The key to native multimodal support is not the vision encoder itself, but modality bridging:
- Vision side: a lightweight backbone handles feature extraction, while a pooling module compresses patch tokens to a reasonable number. The pooling ratio, such as 4-to-1, directly determines prefill cost for long-image scenarios and should be configurable.
- Audio side: a convolutional augmented Transformer with downsampling is commonly used, usually with subsampling and multi-scale convolutions.
- Alignment layers: encoder outputs are projected into the language model hidden dimension. When the language side uses layer-wise embeddings, it must be explicitly defined which layers receive the projected outputs and with what fusion weights.
- Sequence construction: the insertion position of modality tokens, whether before or interleaved; the offset method for position IDs; and the attention mask—vision blocks are often bidirectional while text is causal. Any inconsistency in these three items can cause generation quality anomalies rather than explicit errors.
4. Inference Adaptation: From Computational Graph to Kernels
Configuration-driven graph construction. Inference engines should expose mechanism switches as explicit configuration: layer group size, whether KV heads are heterogeneous and their distribution, whether K = V, embedding form, RoPE base frequency list, number of experts, and Top-k. The graph-building stage should generate subgraphs according to configuration rather than hardcoding by model name.
Operator fusion checklist. At minimum, support should cover:
- Gather, projection, and bias addition for layer-wise embeddings
- Write deduplication for shared K/V
- Fusing QK/V normalization into adjacent GEMMs
- Folding attention scaling
- Merging convolution operations in the pooling module
KV and paging management. When using paged attention, the page table should be built per layer group. Under heterogeneous head counts, allocation should use layer groups rather than layers as the minimum unit to avoid fragmentation. The memory budget formula should be fixed as follows:
kv_bytes = 2 * num_groups * kv_heads[group] * head_dim * dtype_bytes * seq_len * batchcache_budget = total_mem - weights - activations - runtime fragmentation reserve (recommended: 10%-15%)
Differentiated quantization. A recommended combination is:
- Main backbone linear layers: 4–8 bit
- Layer-wise embedding tables: at least 8 bit
- KV cache: int8 per group with finer grouping granularity
- Expert weights: 4 bit
- Router: higher precision
Because KV cache is shared across multiple layer groups, its quantization error is reused and accumulated across layers in the group. KV quantization in shared settings should be more conservative than in standard settings.
Speculative decoding and long context. A draft model must be compatible with the main model’s KV layout. Rollback logic becomes more complex under shared layer groups. It is better to first validate the non-speculative path before introducing speculative decoding. For long context, three metrics should be tested together: TTFT, peak memory, and extrapolation quality. Behavior at the 32K position and the 4K position cannot be inferred from each other in dual-base RoPE models.
5. Export and Evaluation Methodology
Export pipeline. The recommended export pipeline is:
- Weight loading
- Structure normalization: explicitly represent K = V alias relationships, or materialize independent tensors and record shared flags
- Folding and constant optimization: attention scaling, precomputed position encoding tables
- Quantization calibration: the calibration set must cover multimodal samples, long text, code, and multilingual data
- Serialization with signature and version verification
Numerical consistency validation. Do not rely only on end-to-end answers. Layer-wise comparison is recommended:
- Cosine similarity of first-token logits
- Maximum absolute error of output tensors at each layer
- Sampled consistency of KV cache
- Error near modality token boundaries under multimodal inputs
An end-to-end model that “answers correctly” may still hide a missed scaling fold at a certain layer.
Metric system. Metrics should be split by scenario:
- On-device: first-token latency, decode speed, peak memory, power consumption and thermal rise, cold-start time, and post-quantization accuracy loss
- Desktop: throughput at concurrency 1 and concurrency 4, memory usage curve, long-context stability
- Service: TTFT, P99 tail latency, expert routing load distribution, and scaling linearity
Conclusion presentation. Use an acceptance matrix with mechanisms, scenarios, and metrics instead of a single number. Claims such as “model X achieves score Y” are not comparable across mechanisms, because different specifications differ in KV reuse layer groups, quantization strategies, and context length.
6. Recommendations and Common Pitfalls
- Choose the budget first, then the mechanism. For on-device deployment, prioritize large-group KV reuse combined with layer-wise embeddings. For desktop, consider specifications with sparse experts to trade memory for quality. For service-side deployment, focus on TTFT and routing balance.
- Start quantization from 8-bit and then compress. Jumping directly to 4-bit while enabling aggressive KV sharing often makes accuracy loss a combined result of both techniques, which is difficult to isolate.
- Evaluation sets must cover real modality combinations. A model that performs normally on pure text benchmarks may show order-of-magnitude differences in prefill cost under mixed text-image inputs and long context.
- Make observability a default capability. Use logging services to collect latency percentiles and error distributions, and use monitoring alerts to set thresholds for memory usage, tail latency, and routing skew. For elastic scaling and batch inference, consider using a managed container platform and object storage to handle weight distribution and artifact archiving instead of maintaining scheduling and distribution pipelines yourself.
- Debugging checklist:
- Repeated or degraded output: check position encoding tables and masks
- Abnormal logits scale: check whether attention scaling was folded
- Memory usage increasing instead of decreasing: check whether KV write deduplication failed
- Inconsistent results across multiple requests: check router precision or expert loading order
- Extremely slow first token with multimodal input: check pooling ratio and image tiling
7. Conclusion
The real change in this generation of open-source lightweight models is the composability of mechanisms. KV reuse layer groups, layer-wise embeddings, asymmetric attention, sparse experts, and multimodal bridging are modular switches rather than fixed recipes. For inference teams, the adaptation goal is no longer to “support a certain model,” but to build a capability matrix organized by mechanism. Each mechanism should have its own implementation, its own quantization strategy, and its own acceptance criteria.
When this is done as a matrix, adapting to a new specification can be reduced from “rewriting an operator path” to “filling in one configuration line.” This is both the biggest engineering challenge introduced by this generation of models and the most worthwhile direction for investment.
