Next-Generation Open-Source On-Device Model Architecture: Deep Dive into PLE and Cross-Layer KV Sharing Adaptation
Open-weight small model families now ship several sizes in a single release, spanning phones, PCs, and single-GPU servers. Getting them to run is easy, but engine developers face a harder problem: within one family, different sizes combine different mechanisms. This article breaks down three representative ones—per-layer embedding (PLE), cross-layer KV sharing, and native multimodal input—and explains the memory-bandwidth-versus-compute trade-offs behind them. It then offers a configuration-driven, structure-aware adaptation methodology: a five-step workflow, a reusable checklist, layer-by-layer numerical validation techniques, and guidance on accuracy, performance, and memory benchmarking across phones, desktops, and servers.
1. Background: For Next-Generation On-Device Models, “Parameter Scaling” Is Only the Surface
Over the past year, open-weight small model families have iterated densely. A single generation often ships multiple sizes at once, from billion-parameter on-device models to ten-billion-parameter desktop models, covering phones, PCs, and single-card servers. For application developers, the barrier to “getting it running” is indeed lowering, but for inference engine developers, the real challenge is just beginning.
In the past, differences between sizes within the same generation were mainly the number of layers, hidden dimensions, and attention heads, and a single general-purpose template could cover them all. New-generation models are different: to fit long-context and multimodal capabilities into 2–4 GB of usable memory, designers combine different architectural mechanisms across sizes. As a result, within one series, some sizes keep an independent value projection while others use the key directly as the value; some share KV across roughly ten layers while others approach twenty. This means an engine can no longer rely on a single assumption—it must first “understand” the model, then decide how to compile and schedule it.
This article takes the adaptation practice of an open-source on-device model series as background and focuses on three of the most representative mechanisms:
- Per-Layer Embedding (PLE): In addition to a shared vocabulary embedding, an embedding input is added for each layer.
- Cross-layer KV sharing: Several adjacent layers share the same Key/Value cache.
- Multimodal input: Images and audio are encoded into tokens, concatenated with the text sequence, and inferred together.
Below we give a principled explanation, engineering-level implementation details, and a reusable adaptation checklist.
2. From “Per-Layer Independent” to “Structured Sharing”: Three Generations of Evolution
To understand the complexity of the new models, we need to stretch out the timeline. The open-source small model series has gone through roughly three stages, and the on-device-oriented multimodal transition version first introduced mechanisms such as per-layer embedding and cross-layer KV sharing. The new-generation model discussed here did not appear out of nowhere; it continues to extend and reorganize these mechanisms.
| Dimension | First generation | On-device transition | Current generation |
|---|---|---|---|
| Attention structure | Local + global window mix | Local + global window mix | Local + global window mix, ratio varies by size |
| KV Cache | Stored independently per layer | Shared within groups, ~10 layers | Sharing group expands to ~18–20 layers |
| Word embedding | Shared input/output vocab embedding | Per-layer embedding, injected directly | Per-layer embedding, fused after projection |
| QKV normalization | Q/K Norm | Q/K/V Norm | Q/K/V Norm, attention scaling fixed at 1.0 |
| V projection | Independent v_proj | Independent v_proj | Some sizes share K and V, no v_proj |
| KV heads | Uniform across layers | Uniform across layers | Heterogeneous across layers, specified per layer |
| Vision encoder | CLIP-pretrained ViT | Lightweight CNN | ViT + independent pooling module |
| Audio encoding | None | Streaming audio encoder | Streaming encoder based on an industrial-grade speech model |
| Sparse experts (MoE) | None | None | Some sizes: 128 experts, Top-8 routing |
| Notable mechanism | — | Activation sparsity, block-level residual re-estimation | K=V, heterogeneous KV heads, dual-layer RoPE |
This table can be summarized into three evolution lines:
First is the memory compression line. KV sharing expands from about ten layers to nearly twenty, directly determining how much memory the engine must reserve for the cache.
Second is the representation refinement line. Word embeddings are upgraded from “look up and add directly” to “look up, apply a small projection, then fuse.” Attention normalization fills in the value branch, and the scaling factor changes from learnable to a fixed 1.0. These changes do not alter the interface shape but significantly affect numerical behavior.
Third is the sparsification line. Some sizes introduce mixture-of-experts, using 128 experts with 8 activated at a time, expanding parameter capacity while controlling compute.
All three lines serve the on-device scenario. The main conflict in on-device inference is not compute but memory capacity and memory bandwidth, and model weights must be moved from memory to the compute unit at nearly every step. Therefore, the design logic of the new-generation architecture can be summarized as “trade structure for bandwidth, trade precision for footprint.” For an engine, this means the adaptation focus shifts from “can the operator compute” to “how tensors are organized, how sharing relationships are maintained, and how quantization strategies are layered.”
3. Mechanism 1: Per-Layer Embedding (PLE)
3.1 What Problem It Solves
The hidden dimension of on-device models is usually only 1–2 thousand, and the backbone parameters are very limited. If there is only one vocabulary embedding at the input layer, all layers see the same “raw word meaning.” The idea of per-layer embedding is that, besides the shared embedding, a dedicated embedding vector is prepared for each layer and injected before that layer’s computation. You can think of it as giving each layer its own “dictionary,” letting shallow layers focus more on word form and syntax, and deeper layers focus more on semantics and coreference.
This idea has precedent in even smaller models. For example, sharing vocabulary embeddings across layers, untying output embeddings from input embeddings, and per-layer hashed embeddings to compress the vocabulary. What is new is that the new model places per-layer embedding in the same framework as multimodal and KV sharing, and provides two injection methods.
3.2 Comparison of Two Injection Methods
| Dimension | Direct injection | Projection fusion |
|---|---|---|
| Fusion method | Per-layer embedding added directly to hidden state | Per-layer embedding passed through a small projection matrix before adding |
| Weight read per token per layer | ~1× hidden dimension | ~1× projected dimension + projection matrix |
| Compute per token per layer | Nearly zero | Adds one matrix-vector multiply |
| Memory bandwidth pressure | Higher | Lower |
| Applicable scenario | Compute-rich desktop/server | Memory-constrained but adequate-compute phones |
The core difference between the two methods lies in the trade-off between bandwidth and compute. Direct injection reads an amount of data equal to the hidden dimension, with no extra computation; projection fusion adds one matrix multiply but reduces the lookup read to the post-projection dimension (usually a fraction of the hidden dimension). Once the projection matrix is resident in cache, the measured read overhead is often lower than direct injection. So phones are better suited to projection fusion, while desktops have ample compute and direct injection actually saves compute.
3.3 Engine Adaptation Points
- Weight parsing must support both layouts. Some sizes pack per-layer embedding and vocabulary embedding into the same tensor, which must be split by the “layers × vocab × dimension” layout, and per-layer offsets are not necessarily contiguous; other sizes store them per layer independently.
- Quantization strategy must be handled separately. Backbone weights can be aggressively quantized to 4-bit weight-only; applying the same to per-layer embedding would amplify precision loss in small models; the projection matrix is dense compute and is better suited to symmetric int8 or weight-activation joint quantization.
- Resident memory must be counted in the budget. Per-layer embedding is read-only, so it is suitable for mapping to a read-only memory segment and including in the budget alongside other weights, avoiding discovering a memory overrun at runtime.
Illustrative pseudocode (it only expresses the data flow and does not correspond to any specific implementation):
def layer_forward(x, layer_id, token_ids):# Method 1: direct injection, ple shape is [num_layers, vocab, hidden]if cfg.ple_mode == "direct":x = x + ple[layer_id][token_ids]# Method 2: projection fusion, ple_proj shape is [num_layers, hidden, dim]else:e = embedding_lookup(ple[layer_id], token_ids) # [batch, seq, dim]x = x + matmul(e, ple_proj[layer_id])return transformer_layer(x)
4. Mechanism 2: Cross-Layer KV Sharing and Heterogeneous Attention Structure
4.1 Principle and Cost
A standard decoder saves its own K/V at every layer. Cross-layer sharing lets several adjacent layers share the same cache: within the sharing group only the first layer computes and writes K/V, and the rest reuse it directly. For a spec with 32 layers and a sharing group of about ten layers, the cache is roughly one-third of independent storage; when the sharing group expands to nearly twenty layers, the reduction exceeds half.
It should be noted that a larger sharing group is not necessarily better. Layers within the same group lose independent K/V representation and rely on Q/K/V normalization, per-layer projection, and FFN differences to compensate. Therefore, the partitioning of the sharing group is itself a balance point between precision and memory.
4.2 Heterogeneous Structure: K=V, Different KV Heads Per Layer, Dual-Layer RoPE
The new model also stacks several “non-standard” structures inside attention:
- K=V: Some layers have no independent v_proj and directly use the K projection’s output as V. The benefit is one fewer weight and one fewer matrix multiply, at the cost of V’s representation being bound to K.
- Heterogeneous KV heads: The KV head count of different layers is specified per layer by configuration, ranging from a single head per layer (MQA) to equal to the Q head count (MHA), so the kernel must read this parameter per layer.
- Dual-layer RoPE: Local and global layers use different rotary position embedding bases, so the position encoding cache must be prepared per layer.
4.3 Engine Adaptation Points
- Tensor aliasing: Layers within a sharing group should hold references pointing to the same cache object; allocating separately per layer is prohibited.
- Write-order constraint: During decoding, the sharing group is read layer by layer, and KV updates must be performed uniformly after the entire group has been read; otherwise the updates will corrupt subsequent layers’ inputs.
- Per-layer shape inference: Each layer’s cache shape is
[2, kv_heads_l, max_seq_len, head_dim], and KV head count, head_dim, and RoPE base are all taken per layer, without reusing global defaults.
# Illustration: parse cache shape and RoPE config per layerfor layer in model.layers:layer.kv_cache = alloc_kv(kv_heads=layer.kv_heads, # heterogeneous per layerhead_dim=layer.head_dim,dtype=cache_dtype, # e.g. fp16 or int8)layer.rope = build_rope(base=layer.rope_base) # local/global base differs
If the engine uses paged cache management, layers within a sharing group must be bound to the same set of page blocks; otherwise the paging mechanism will “scatter” the sharing relationship, and memory will increase rather than decrease. On GPU servers, the sharing relationship can be turned into a VRAM benefit: only one copy of K/V needs to be served within a sharing group.
5. Mechanism 3: Native Multimodal Input
New models natively support image and audio input, unified through “encode into tokens, insert into the sequence” to feed into the language backbone.
The vision branch uses a CLIP-pretrained ViT followed by an independent pooling module that compresses patch features to the target token count. Independent pooling means that even if the backbone and the ViT are deployed separately, consistent downsampling behavior is maintained.
The audio branch uses a streaming audio encoder composed of convolutional downsampling and self-attention modules. The streaming design means it can take chunked input and produce incremental output, which is suitable for real-time interaction.
Adapting this kind of model requires attention to four aspects:
- Modality placeholder parsing: Image and audio placeholders in the prompt must be located to specific token ranges, and during prefill the encoding results replace the text embeddings at the corresponding positions.
- Position encoding alignment: Inserted modality tokens also occupy sequence positions, so the position index must be consistent with the final concatenated sequence; otherwise attention will be misaligned.
- Vision token budget: Token count is positively correlated with input resolution, so a resolution cap and pooling ratio should be provided as config to prevent long images from blowing up the context.
- Encoder cache reuse: When the same image appears repeatedly across multiple dialogue turns, its visual tokens can be cached and reused to avoid running the ViT repeatedly.
# Illustration: embedding concatenation for multimodal prefilltext_emb = token_embedding(input_ids) # [1, L, hidden]image_emb = vision_pooler(vision_encoder(image)) # [1, N_img, hidden]audio_emb = streaming_audio_encoder(audio_chunks) # [1, N_aud, hidden]# Replace at placeholder positions, then concatenateinputs_emb = replace_placeholders(text_emb, image_emb, audio_emb)logits = language_model.prefill(inputs_emb, position_ids=arange(inputs_emb.shape[1]))
6. Inference Engine Adaptation Methodology: Five-Step Process and Checklist
Looking at the above mechanisms together, the difficulty of adapting next-generation on-device models can be summed up in one sentence: the same “model” is a different compute graph under different sizes. So the engine needs to decouple “config parsing” from “graph construction,” letting the same set of kernels adapt to all sizes through parameterization.
Recommended five-step process:
- Config parsing: Abstract the model config into a unified capability description, including each layer’s KV head count, sharing group partitioning, per-layer embedding mode, whether v_proj is present, modality switches, and so on.
- Graph construction: Generate the attention subgraph parameterized by config, uniformly handling tensor aliasing, per-layer RoPE, normalization, and scaling.
- Quantization and precision planning: Backbone int4/int8 weight-only, per-layer embedding handled differently by mode, normalization layers kept at high precision.
- Cache and memory planning: Allocate KV by sharing group, count per-layer embedding in the resident budget, and quantize KV to int8 if necessary.
- Validation and tuning: First do layer-by-layer numerical alignment, then run end-to-end accuracy and performance evaluation.
Ready-to-use checklist:
- Are KV sharing groups correctly aliased to tensors? Are updates deferred and applied uniformly during decoding?
- Are each layer’s KV head count and head_dim parsed per layer? Does the paged cache maintain the sharing relationship?
- Do layers without v_proj correctly reuse the K projection output?
- Are RoPE tables built separately for local and global layers?
- Can both modes of per-layer embedding load correctly? Is the quantization strategy configured per mode?
- Are normalization layers and attention scaling factors left unchanged by quantization?
- Are multimodal placeholder replacement and position indices consistent?
- Is the allocation of shared cache included in the memory budget cap?
7. Accuracy and Performance Validation
7.1 Layer-by-Layer Numerical Alignment
The most time-consuming part of adaptation is often not writing code, but locating “why the output is wrong.” It is recommended to run the reference implementation and the engine on the same weights and compare layer by layer:
ref = reference_model.forward_layers(input_ids) # reference implementation per-layer outputsout = engine.forward_layers(input_ids) # engine per-layer outputsfor i, (a, b) in enumerate(zip(ref, out)):cos = cosine_similarity(a, b)max_err = (a - b).abs().max()print(f"layer {i}: cos={cos:.6f}, max_err={max_err:.4f}")assert cos > 0.999, f"layer {i} deviation too large"
In practice, first-layer deviation usually comes from weight loading errors or quantization; middle-layer deviation mostly comes from sharing relationships or RoPE config; last-layer deviation is often caused by accumulated error from earlier layers and should be traced forward first.
7.2 Evaluation Dimensions
- Accuracy: general understanding, code, and math benchmarks, plus a self-built business set.
- Performance: prefill first-token latency and decode tokens per second are counted separately, because the two have different bottlenecks—the former is affected by compute and weight read volume, the latter is mainly limited by memory bandwidth.
- Memory: peak resident memory = backbone weights + per-layer embedding + KV cache + temporary activations. Per-layer embedding is easily overlooked but can account for a considerable proportion of total memory.
- Power and heat: the thermal constraint of sustained on-device inference determines the actual sustainable performance.
7.3 Selection Recommendations
- Memory-constrained devices like phones: choose a small dense model, enable KV sharing and projection-style per-layer embedding, and quantize KV to int8.
- Desktop and workstation: a medium size can already deliver good multimodal and long-context capability, and per-layer embedding can use direct injection.
- Server: you can choose sparse-expert sizes to get greater parameter capacity under the same compute budget, provided the engine supports routing and expert scheduling.
8. Practical Advice and Common Misconceptions
- Don’t infer architecture from parameter scale. KV sharing depth, per-layer embedding mode, and V projection structure can all differ across sizes in the same generation; always defer to the model config.
- Per-layer embedding is not “optional.” Some models pack it with the vocabulary embedding; a parsing omission will not throw an error, it will just noticeably degrade output quality.
- Sharing does not automatically save memory. In scenarios like paged cache and multi-engine parallelism, the sharing relationship must be explicitly maintained; otherwise the memory overhead will be amplified.
- Multimodal is not “just concatenate.” Position encoding alignment, token budget, and encoder cache are all indispensable.
- Quantization needs per-layer decisions. Normalization, attention scaling, and per-layer embedding each differ in their sensitivity to numerical error, so a uniform strategy often costs more than it saves.
9. Summary
Next-generation open-source on-device models trade capability density under extremely small parameter scales for per-layer embedding, cross-layer KV sharing, heterogeneous attention, and native multimodal input. For inference engines, the core of adaptation is no longer “which operators are supported” but how to accurately express the model’s structural constraints: which tensors are shared, which differ per layer, and which modules can be quantized. Once you master this “config-driven, structure-aware” methodology, whether for on-device deployment or server-side acceleration, you can land new models with lower trial-and-error cost.
