Multi-Spec LLM Architecture Design and On-Device Inference Adaptation
This article examines how to adapt inference systems for LLM families that span multiple parameter sizes and combine different architectural mechanisms, including per-layer embeddings, cross-layer KV cache sharing, heterogeneous KV heads, and multimodal encoders. It covers the architectural evolution, engineering constraints, performance evaluation methods, and deployment selection guidance for on-device and server scenarios, helping readers assess and implement multi-spec inference systems more systematically.
Multi-Spec LLM Architecture Design and On-Device Inference Adaptation
1. Background and Scope
The same generation of large models often offers multiple parameter specifications at the same time: small specifications for on-device devices such as phones and earbuds, medium specifications for personal computers, and large specifications for server clusters. The span between specifications can exceed an order of magnitude. If only the number of layers and hidden dimensions are scaled, the adaptation workload for the inference engine is not large. The real difficulty is that different specifications use different combinations of architectural mechanisms, and the same inference code must handle multiple structures at once.
This article is not an evaluation of whether a particular model is good or bad. Rather, it addresses a general question: when model architectures introduce per-layer embeddings, cross-layer cache sharing, multiple attention head configurations, and multimodal encoders, how should the inference system be designed, and how should deployment teams evaluate it? The code examples in this article are illustrative and do not correspond to any specific implementation interface.
2. Architectural Evolution of Multi-Spec Models
Model architecture evolution usually proceeds along three lines: attention and cache efficiency, vocabulary representation capability, and input modality coverage. The following table compares three generations of typical designs to make the order in which these mechanisms appeared easier to understand. The table is a high-level summary and does not represent the complete specification of any particular model.
| Design dimension | Early dense architecture | On-device optimized architecture | New-generation multi-spec architecture |
|---|---|---|---|
| Attention | Global attention | Hybrid local and global | Hybrid local and global, configured per layer |
| KV cache | Independent per layer | Shared by some layers | Cross-layer sharing, reused within layer groups |
| Word embeddings | Single shared embedding | Per-layer embedding lookup injection | Per-layer embeddings fused with projection |
| Normalization | Q, K normalization | Q, K, V normalization | Q, K, V normalization, adjusted scaling strategy |
| Key-value projection | Independent projection | Independent projection | Reused by some layers, shared keys and values |
| Number of KV heads | Uniform across layers | Uniform across layers | Heterogeneous across layers |
| Vision encoding | ViT-style encoder | Lightweight convolutional encoder | ViT-style encoder with pooling projection |
| Audio encoding | None | Convolution-enhanced encoder | Convolution-enhanced encoder |
| Sparse structure | None | Activation sparsity | Mixture of experts, activating a small number of experts on demand |
The common goal of the three generations is to reduce memory footprint while preserving representation capability at smaller parameter counts. The four mechanisms discussed below revolve around these two goals.
3. Mechanism 1: Per-Layer Embeddings
3.1 Principle
In the standard approach, input tokens go through a single embedding lookup to obtain hidden vectors, and all subsequent layers share this starting point. Per-layer embeddings prepare an additional low-dimensional embedding table for each layer. Each token can look up a low-dimensional vector at every layer, which is then projected to the hidden dimension and added to the residual stream. In this way, every layer can directly receive signals related to token identity without relying entirely on propagation from previous layers.
3.2 Why It Suits On-Device Deployment
Lookup operations involve almost no floating-point arithmetic; the main cost is memory reads. Embedding tables are large but sparsely accessed, so they can be placed in larger, slower storage and only the required rows need to be read. This differs from the usual assumption that inference is compute-bound. During adaptation, the bottleneck should be identified as storage bandwidth.
3.3 Engineering Adaptation Points
- Storage layout: Store rows contiguously by token to reduce the number of random reads.
- Quantization strategy: Embedding tables are usually less sensitive to precision than linear layers, so a lower-bit quantization scheme can be selected separately. However, output quality should be confirmed on a validation set.
- Operator fusion: Lookup, projection, and residual addition can be fused into a single operator to reduce reads and writes of intermediate tensors.
Illustrative code:
def per_layer_embed_add(hidden, token_ids, layer_idx, table, proj):# table: [layer_count, vocab_size, low_dim], low-dimensional embeddings stored per layerlow = table[layer_idx][token_ids] # lookup, no multiply-add operationsdelta = proj[layer_idx](low) # project to hidden dimensionreturn hidden + delta # inject into residual stream
4. Mechanism 2: Cross-Layer KV Cache Sharing
4.1 Memory Composition
During decoding, each token requires cached keys and values for each layer. Cache size can be estimated as follows:
Cache bytes = 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element
The factor 2 accounts for keys and values. In long-context scenarios, this term often exceeds the memory occupied by the model weights themselves.
4.2 Sharing Strategy
Cross-layer sharing divides several adjacent layers into a group and keeps only one key-value cache per group. The first layer in the group (the anchor layer) writes to the cache, while the remaining layers only read from the cache and use their own query vectors to compute attention. In this way, the number of cache copies drops from the number of layers to the number of groups.
Sharing reduces the cache but does not reduce query projections or attention computation. Whether decoding speed improves depends on whether memory bandwidth is the main bottleneck.
4.3 Mapping Layers to Cache Slots
# Assume 24 layers, with one cache shared by every 2 layersdef build_cache_map(num_layers, group_size):cache_map = {}for layer in range(num_layers):cache_map[layer] = layer // group_size # layers in the same group map to the same cache slotreturn cache_mapcache_map = build_cache_map(24, 2)num_slots = len(set(cache_map.values())) # only 12 caches are needed in practice
4.4 Engineering Points
- Write constraints: Only anchor layers can write to the cache. The inference framework must guarantee correct read/write ordering; otherwise, stale data may be read.
- Difference between prefill and decoding: In the prefill stage, an entire input is processed at once, so the anchor layer must complete its writes before subsequent layers read. In the decoding stage, generation advances token by token, and the same ordering constraint still applies.
- Cache preallocation: Compute the number of slots from the mapping table to avoid waste caused by allocating according to the number of layers.
5. Mechanism 3: Heterogeneous KV Heads and Attention Variants
5.1 Heterogeneous KV Heads
In traditional designs, all layers have the same number of KV heads, which makes implementation simple. Heterogeneous designs allow different layers to use different numbers of KV heads, and some layers can use fewer KV heads to reduce cache usage. The cache manager in the inference framework must support per-layer shapes and must not assume that all layers have the same shape.
5.2 Key-Value Projection Sharing
In some layers, the value vectors directly reuse the projection result of the key vectors, eliminating one set of projection parameters. For the inference engine, weight loading must identify layers with “no value projection” and branch correctly during computation.
5.3 Normalization and Numerical Stability
Normalizing queries, keys, and values can constrain the numerical range of attention scores. The scaling factor affects the attention distribution, and the implementation must exactly match the setting used during training. Any difference will cause the output to drift, and such deviations are difficult to see directly from logs.
5.4 Adaptation Checklist
- Output a manifest during loading for the number of KV heads, head dimension, and whether projection is shared for each layer, making it easier to verify.
- Write separate numerical comparison tests for normalization layers and scaling factors.
- The attention type of different layers (local or global) determines the mask shape and should be explicitly distinguished during graph construction.
6. Mechanism 4: Multimodal Input Integration
6.1 Vision Branch
The vision encoder splits an image into patches and outputs a set of visual features. The pooling and projection module compresses these features into the language model’s token space and inserts them into the text sequence as placeholder tokens.
Key parameters include input resolution, patch size, and the number of tokens produced per image. More tokens provide richer detail, but prefill time and cache occupancy also increase. During deployment, an upper limit should be set according to business needs, and the resolution strategy should be fixed in the preprocessing stage.
6.2 Audio Branch
Audio is first converted into spectral features, downsampled in the time dimension through convolution, and then passed into the encoder. The downsampling ratio determines the number of tokens produced per second of audio and is a main parameter for controlling latency.
6.3 Engineering Points
- Preprocessing consistency: If any of the scaling method, normalization mean and variance, or channel order differs from training, the results will drift.
- Image feature caching: When the same image is queried multiple times, reusing the vision encoding result avoids repeated computation.
- Placeholder expansion: The number of placeholder tokens in the prompt template must strictly match the encoder output length.
Illustrative code:
def build_multimodal_prompt(text_tokens, image_feats, placeholder_id):n = image_feats.shape[0]# The number of placeholder tokens must match the length of visual featuresassert text_tokens.count(placeholder_id) == 1expanded = []for t in text_tokens:if t == placeholder_id:# Expand to n placeholders; later replace embeddings at these positions with visual featuresexpanded.extend([placeholder_id] * n)else:expanded.append(t)return expanded
7. Performance Evaluation for On-Device and Server Deployment
7.1 Metric Definitions
- Time to first token: The time from request arrival to the first output token, mainly reflecting prefill capability.
- Decoding speed: The number of output tokens per second, reflecting memory bandwidth and compute efficiency.
- Peak memory: Includes weights, cache, and intermediate tensors, and should be recorded separately.
- Quality metrics: Accuracy or human ratings on a fixed task set, used to determine whether quantization and optimization cause regression.
7.2 Testing Method
- Fix the hardware model, system version, and background load, and record environment information.
- Group tests by prompt length, for example, 128, 1024, and 8192 tokens.
- Warm up for several rounds first, then take the median and percentiles across multiple runs to avoid single-run fluctuations affecting conclusions.
- Conduct quality tests and performance tests separately to ensure that before-and-after comparisons are based on the same input set.
This article does not provide specific performance numbers. Data is heavily affected by hardware and tasks, and readers should measure in their own environments. Directly applying data from others can easily lead to misjudgment.
8. Selection and Deployment Recommendations
By scenario:
- Offline, privacy-sensitive, or poor-network scenarios: Prioritize small models and focus on peak memory and time to first token.
- Personal computers or workstations: Medium specifications are more suitable and can balance quality and speed.
- High-concurrency server deployment: Large models have clear quality advantages, but batching strategy and cache capacity need to be evaluated.
- Multimodal requirements: First confirm input resolution and audio duration limits, then estimate the token cost per request.
Common risks:
- Quantization precision loss: Different layers have different sensitivities to quantization, and key layers can retain higher precision.
- Template and tokenizer mismatch: The chat template and special token definitions must remain consistent with the model release; otherwise, output quality will drop noticeably.
- Multimodal preprocessing bias: Inconsistent image resizing or audio resampling can manifest as incorrect understanding of image content by the model.
- Licensing terms: Before use, check the model license agreement and commercial restrictions to confirm whether they apply to the target scenario.
9. Conclusion
Multi-spec architectures allow the same model generation to cover a wider deployment range, at the cost of requiring the inference system to handle more structural differences. Teams should decompose architectural mechanisms into verifiable modules, compare training code and inference code item by item, and then use unified performance and quality benchmarks for decision-making.
