Adapting Inference Engines for On-Device Multimodal LLMs: Per-Layer Embeddings, Cross-Layer KV Sharing, and Benchmarking
This article examines what it takes to adapt an inference engine to a new generation of open-source on-device multimodal models whose efficiency has been designed into the model architecture itself. It compares three generations of model structure, breaks down three mechanisms that dominate adaptation effort (per-layer embeddings, cross-layer KV sharing, and multimodal fusion with heterogeneous KV heads and dual RoPE), and lays out a graph-rewrite-centric export pipeline, a benchmark matrix organized by model size × hardware tier × modality, and a troubleshooting checklist covering missing-weight load errors, silent garbled output, memory overshoot, high time-to-first-token, and quantization accuracy regression. Reference values such as shared layer counts, expert counts, and RoPE parameters are illustrative; always defer to the model config file.
1. Background: Open-Source On-Device Models Enter a Phase of Structural Innovation
For the past few years, the main line of open-source small models has been parameter scaling: one Transformer architecture, released in several size variants, with an inference engine adapting to a single operator set and covering the entire lineup. This new generation of open-source multimodal models is clearly different. Model authors have designed on-device experience and inference efficiency directly into the architecture, spanning sizes from roughly a billion parameters to several billion, while introducing new mechanisms such as per-layer embeddings, cross-layer KV sharing, heterogeneous attention heads, and sparse experts. The result: within a single model family, the graph-structure differences between size variants can be larger than the differences between different families.
For an inference engine, this means the era of “one graph covers the whole lineup” is over. Adaptation shifts from wiring up a model to understanding its structure, and it requires answering three questions item by item:
- Where the structural differences lie: which modules are driven by multi-layer configuration and which by single-layer configuration;
- How operators must be rewritten: which nodes in the original reference graph must be split, merged, or folded to map onto the on-device operator set;
- Where the performance bottlenecks are: beyond parameter count, KV Cache, prefill, and expert loading are the real cost items on-device.
Drawing on adaptation work for a recent open-source multimodal model family on phone and desktop clients, this article focuses on the three most representative mechanisms: per-layer embeddings, cross-layer KV sharing, and multimodal fusion. Shared layer counts, expert counts, RoPE parameters, and similar figures mentioned here are illustrative; the actual model configuration file is authoritative.
2. Architecture Evolution: From Parameter Scaling to Structural Divergence
2.1 Key differences across three generations
To understand the adaptation difficulty of the current generation, you need to put the previous generation and the transitional generation alongside it. The current models did not appear out of nowhere — several key mechanisms (per-layer embeddings, KV sharing) first appeared in the transitional generation of multimodal models designed for on-device use, and the current generation extends them further. The table below compares architectural mechanisms across the three generations (illustrative values; defer to actual configuration).
| Dimension | Previous gen | Transitional gen (on-device multimodal) | Current gen |
|---|---|---|---|
| Attention pattern | Alternating local sliding window and global | Alternating local sliding window and global | Alternating local sliding window and global |
| KV Cache | Independent per layer | Partially shared (~10 layers) | More layers shared (~18–20) |
| Embedding injection | Globally shared word embedding | Per-layer embeddings, injected directly | Per-layer embeddings, lookup then projection then fusion |
| QKV normalization | Q/K Norm | Q/K/V Norm | Q/K/V Norm with an additional scaling factor |
| V projection | Separate v_proj |
Separate v_proj |
Some variants have no v_proj; K and V are identical |
| KV heads | Uniform across layers | Uniform across layers | Heterogeneous per local/global layer |
| Vision encoder | Transformer-style | Lightweight convolutional backbone | Transformer-style + pooling module |
| Audio | Not supported | Streaming speech encoder | Streaming speech encoder |
| Sparse structure | Dense | Dense | Sparse experts in some variants; each token activates only a few experts |
| Distinctive mechanisms | — | Near-identity high-frequency re-entry module, activation sparsification | No v_proj, heterogeneous KV heads, dual RoPE |
One clear line of evolution can be read from the table:
- Per-layer embeddings: from “direct addition” to “projected fusion.” The transitional generation added per-layer embeddings straight onto the hidden state; the current generation passes them through a projection matrix before fusing. This improves representational capacity and convergence quality, at the cost of extra matrix multiplications that grow linearly with the number of layers.
- KV sharing: the scope keeps expanding. The number of shared layers grows from ~10 to nearly 20, but only the original (owner) layer actually writes the cache; the rest reuse it. An engine that still allocates memory “one copy per layer” ends up with nearly double the cache overhead out of nowhere.
- The “missing” V: some variants have no
v_proj. When K and V are the same,v_projsimply does not exist in the original weights. An engine that hard-requires the weight in the conventional way will fail outright at load time. - Heterogeneous KV heads: single-layer and global configuration diverge. Local layers use fewer KV heads to shrink the cache inside the sliding window, while global layers keep more KV heads to preserve long-range retrieval. Kernels can no longer be compiled against one fixed KV head count.
- Multimodality becomes a native capability. Outputs from the vision and speech encoders must be mapped into the language-side hidden space through projection layers, then concatenated with text tokens as soft prompts. This part consumes far less compute than autoregressive decoding, yet it is the primary source of time-to-first-token.
The current generation also retains the transitional generation’s high-frequency re-entry module, QKV normalization, and activation sparsification, and adds dual RoPE: local and global layers use different rotary base frequencies to balance position sensitivity at short and long range. At a glance these are just configuration differences; on-device, every one of them maps to a chunk of graph that must be rewritten.
2.2 Four categories of engine changes
Mapping these differences onto the engine side yields four categories of work:
- Configuration-driven behavior: sharing relationships, head counts, and RoPE parameters all come from single-layer config. The engine must read them layer by layer and cannot reuse global constants.
- Graph rewriting: splitting per-layer embeddings, folding K=V, redirecting KV reads/writes, and injecting dual RoPE all have to happen at export or graph-optimization time.
- Memory planning: KV sharing changes the granularity of cache allocation, and MoE introduces expert swapping, so the memory pool needs a redesign.
- Scheduling and fusion: heterogeneous heads require multiple specialized kernel variants, while per-layer projection stresses operator fusion and front-end/back-end coordination.
3. Mechanism Breakdown: Adaptation Difficulty of the Three Signature Mechanisms
3.1 Per-layer embeddings: the small model’s “content injector”
Principle and role
Small models have a relatively fixed layer count, but the “memory capacity” available to each layer is limited. The per-layer embedding approach gives each layer its own small embedding table, typically tiled by vocabulary and hidden dimension:
- The input token first goes through the main word embedding to get a base vector;
- Then a lookup is performed on each tiled table to fetch the slice belonging to that layer;
- The slices are fused per layer and injected into that layer’s input.
This lets the model add “layer-specific knowledge” to each layer with only a small parameter increment, yielding gains beyond its parameter count on translation, long-tail knowledge, and instruction following. The transitional generation used “lookup then add directly”; the current generation uses “lookup → project → fuse,” which produces smoother fusion and higher capacity utilization.
Adaptation challenges
- Unusual weight shape: per-layer embedding tables consist of a large number of small constant tensors, and more layers means more tensors. An engine assuming “one big embedding table” will fail at load time due to a tensor count or layout mismatch.
- Fusion semantics changed: the previous generation did element-wise addition; the current generation inserts a matrix multiplication. The graph changes from “lookup + Add” to “lookup + MatMul + Add/Concat.” Keeping the additive fusion path silently produces wrong results, and such precision bugs are extremely hard to localize.
- Mismatched quantization strategy: per-layer embedding tables are small and have concentrated distributions. Applying the main embedding table’s quantization config amplifies error layer by layer, and element-wise accumulation can also trigger low-precision accumulation overflow.
- Memory and performance: the main embedding table, per-layer embedding tables, and the LM head usually share weights. Loading the full vocabulary embedding table at once is often not worthwhile on-device, and per-layer embeddings inflate the resident weight footprint further.
Engineering recommendations
- Abstract “word embedding” as a composite module containing the main table, the per-layer tables, and the fusion operator, and let graph rewriting expand it uniformly at export time.
- Assign per-layer embeddings a separate quantization bit width or keep them in high precision, and compare per-layer outputs against a reference implementation during export.
- For smaller variants, load vocabulary embedding rows on demand in tiles, and produce LM head output with a “compute row by row + accumulate” tiling scheme to avoid keeping the whole table resident in memory.
- During graph compilation, merge “lookup → project → fuse” into a single custom fused operator to reduce on-device memory traffic.
3.2 Cross-layer KV sharing: trading a little capacity for long context
Principle and role
Autoregressive decoding is memory-bandwidth bound: every generated token requires reading the entire historical KV Cache. KV sharing lets several layers reuse one cache, which is fundamentally an exchange between capacity and context length/speed:
- Cache size is approximately
2 × num_layers × num_kv_heads × head_dim × seq_len × bytes_per_element(the factor of 2 accounts for K and V). After sharing, the layer term drops from total layers to number of original layers, and global context occupancy falls substantially. - Each decode step reads a smaller cache, which — combined with a larger batch or longer context — makes the experience more stable.
- The cost is that intermediate layers lose their independent key/value memory, so expressiveness drops slightly and the model must be jointly optimized with the sharing mechanism during training.
When sharing grows from ~10 layers to nearly 20, the benefits and the risks scale together:
- Benefit: the global cache is nearly halved, and the memory pressure of long dialogues and multi-turn Q&A drops noticeably.
- Risk: the original layer and the other layers in its sharing group must have strictly identical KV head configurations, otherwise the shared semantics no longer hold. The current generation happens to use heterogeneous KV heads, and the combination makes “validate sharing relationships against configuration” a hard requirement.
Adaptation challenges and practices
| Problem | Typical symptom | Recommended practice |
|---|---|---|
| Cache allocated per layer | Shared layers each get their own cache; obvious memory waste | Allocate per original layer; build a consumer→owner mapping table |
| Read/write semantics confused | A consumer layer writes the cache, or the owner layer fails to write and dirty data is read | Owner writes, consumers read only; non-shared layers (e.g., sliding-window layers) manage their own cache |
| Missing head-count validation | KV heads differ across layers in a sharing group; results are wrong but nothing crashes | Assert equal head count, head_dim, and precision at export; fall back to independent caches on mismatch |
| Fixed graph structure | The original graph wires “per-layer read/write” and cannot be reused directly | Redirect the attention nodes’ KV inputs during the graph rewrite stage |
| Different length limits | Sliding-window and global layers have different cache length policies | Configure ring buffers or truncation per layer type |
3.3 Multimodal fusion and heterogeneous structure
Multimodality: a unified sequence of vision, speech, and text
Multimodal models typically contain two kinds of encoder:
- Vision encoder: a Transformer-style backbone (with an extra pooling module in the current configuration) that splits an image into patches and encodes them;
- Speech encoder: a convolutional/Transformer hybrid designed for streaming input that encodes audio frames into a feature sequence.
Encoder outputs are aligned to the language-side hidden space through projection layers, then concatenated with text tokens as soft prompts and fed into the backbone. Three points matter most for on-device adaptation:
- Preprocessing consistency: image resize, normalization, and audio resampling parameters must match the training side, or accuracy loss will be misdiagnosed as “the model is bad”;
- Time to first token: the encoding stage usually runs before text prefill and is the main source of first-token latency. Multimodal tasks can adopt a staged output strategy — text first, then structured output;
- Memory peak: high-resolution images produce a large number of vision tokens, and activation occupancy during prefill is far higher than during decode, so tiled prefill or activation reuse is needed.
Heterogeneous KV heads and no v_proj
- Heterogeneous KV heads: local sliding-window layers use fewer KV heads to keep the window cache small, while global layers use more KV heads to guarantee long-range retrieval. Kernels must be specialized per KV head count, or different head counts can be padded/concatenated into a uniform shape at export — the latter adds extra compute and memory traffic.
- No
v_proj: when V equals K, the weights contain nov_proj. Key adaptation points:- Detect and fold the branch at export, reusing K directly as V;
- Handle the “missing weight” explicitly at load time rather than exiting with an error;
- During quantization, share one tensor between K and V to avoid inconsistencies from quantizing twice.
Dual RoPE
Local and global layers use different rotary base frequencies. During adaptation, position indices and base frequency tables must be constructed per layer type, and the constant tables injected into the corresponding attention nodes at graph compile time. Sharing them across layers is not allowed.
4. Export and Transformation Pipeline: Graph Rewriting as the Core
Below is the skeleton of the adaptation pipeline. The key idea is “export equals transformation”: do not wait until the model is running on-device to patch things.
Original weights + single-layer config│▼① Config parsing (read per layer: layer type, KV head count, sharing flag, v_proj presence, RoPE parameters)│▼② Graph rewriting├─ Per-layer embeddings: split lookup → project → fuse into mappable subgraphs├─ KV sharing: redirect consumer-layer KV inputs, mark original layers as writers├─ K = V: fold v_proj, reuse K└─ Dual RoPE: inject position-encoding constants per layer│▼③ Quantization and operator fusion (high or mixed precision for per-layer embeddings / vision encoder; attention fusion)│▼④ Graph compilation (two sets, static shape and dynamic shape; specialization per KV head count)│▼⑤ On-device export (weight packing, on-demand loading strategy, memory pool planning)│▼⑥ Accuracy regression + performance evaluation
Illustrative code (Python pseudocode):
def build_kv_layout(layers):"""Build the KV cache layout from single-layer config.Within a sharing group, the first global layer is the owner; the otherglobal layers are consumers (readers).Sliding-window local layers and layers with a different head count areallocated independently."""layout, owner = {}, Nonefor i, layer in enumerate(layers):is_global = not layer.is_sliding_windowsame_head = (owner is None) or (layer.kv_head_num == layers[owner].kv_head_num)if is_global and same_head:if owner is None:owner = i # create the sharing grouplayout[i] = {"role": "shared", "owner": owner}else:layout[i] = {"role": "private", "owner": i}return layoutdef rewrite_for_kv_sharing(graph, layout):"""Shared layers get no dedicated cache; consumers read the owner's cache,and the original layer holds exclusive write access."""for i, layer in enumerate(graph.transformer_layers):info = layout[i]layer.kv_cache = None if info["role"] == "shared" else graph.alloc_kv(layer)if info["role"] == "shared":layer.attn.kv_input = graph.kv_cache_of(info["owner"])layer.attn.kv_write = (i == info["owner"])return graph
A few details that are easy to overlook:
- Be strict, not permissive, when defining sharing groups: if head count,
head_dim, precision, or layer type differs in any respect, split into an independent cache. - Keep sliding-window layers out of sharing groups: their cache can be overwritten as a ring over the window length, which follows different length management logic from the global cache.
- Run static validation at export time: assert that “consumer head count matches the owner,” catching errors at export rather than in production.
5. Evaluation Methodology: Tiered Matrix and Key Metrics
5.1 Evaluation matrix
A single “fluency” conclusion is meaningless. Organize evaluation as size tier × hardware tier × modality:
| Size tier | Typical hardware | Text tasks | Vision tasks | Speech tasks |
|---|---|---|---|---|
| ~1B params (on-device) | Mid-to-high-end phones | TTFT, decode speed, memory | First-token latency for single-image QA | Streaming transcription real-time factor |
| ~10B params (desktop) | Thin-and-light laptops / desktops | Long-context decode, memory | Multi-image QA, resolution sensitivity | Long-audio transcription |
| Sparse-expert variant (server) | Multi-GPU servers | Throughput, batch efficiency | Multimodal batch throughput | Batch transcription throughput |
5.2 Key metrics
- TTFT (time to first token): covers preprocessing, vision/speech encoding, and prefill. In multimodal tasks, the number of vision tokens often dominates this metric.
- Decode speed (tokens/s): strongly correlated with KV cache read bandwidth, and an area sharing directly improves.
- Memory peak: distinguish three items — resident weights, KV cache, and activation peak. On-device, the activation peak is the one most often overlooked.
- Accuracy regression: use a fixed test set and compare perplexity, task accuracy, and human readability between the reference implementation and the on-device output.
- Stability: over long multi-turn conversations, check for memory growth, decode slowdown, or output degradation.
5.3 Usage recommendations
- Prefer smaller variants on-device: selection on-device should prioritize memory and time-to-first-token rather than leaderboard scores. With per-layer embeddings and KV sharing, ~1B-class models are already capable of summarization, rewriting, and knowledge QA.
- Focus on long context on desktop: the long-context benefit of KV sharing is more pronounced on desktop.
- Consider sparse variants on the server: sparse-expert variants suit batch workloads, but pay attention to expert loading and cache strategy.
- Validate multimodality in stages: verify the text path first, then add vision/speech, localizing problems segment by segment instead of facing an unattributable “end-to-end accuracy drop.”
6. Common Problems and Tuning Checklist
| Symptom | Common root cause | Handling |
|---|---|---|
| Load fails with “missing weights” | Some variants have no v_proj |
Fold K=V at export; support missing weights at load time |
| Garbled output without errors | Wrong per-layer embedding fusion; misconfigured sharing relationship | Compare per-layer outputs against the reference implementation; validate the owner mapping |
| Memory higher than expected | Shared layers still get independent caches; full word embedding table stays resident | Allocate per owner; load the embedding table in tiles |
| High time-to-first-token | Vision/speech encoding not optimized; duplicated preprocessing work | Fuse encoding operators, cache image preprocessing results, tiled prefill |
| Long-context decode slows down | Sliding-window cache not truncated; inefficient KV cache layout | Ring buffers, contiguous memory layout, kernels specialized per layer type |
| Obvious accuracy drop after quantization | Low-bit quantization of per-layer embeddings / vision encoder | Mixed precision; keep sensitive layers at 8 bit or above |
7. Engineering Practice: A Practical Path with Cloud-Device-Edge Collaboration
On-device model adaptation is not a one-off effort. Treat it as a reusable pipeline:
- Model acquisition and verification: record model version, single-layer config, and weight checksums in a uniform way to avoid mixing “same name, different structure” builds.
- Automated export: the export script reads single-layer config and automatically generates the KV sharing layout, per-layer embedding subgraphs, K=V folding, and dual RoPE constants, minimizing manual edits.
- Accuracy regression: after each export, compare reference and on-device implementations on a fixed test set; block the release if error exceeds the threshold.
- Performance baseline: maintain a baseline table per size tier and hardware tier, and record every optimization as “baseline + improvement.”
- Continuous integration: chain export, accuracy regression, and performance evaluation into automated jobs so that any model or engine change is caught quickly.
Under a cloud-device-edge deployment model, the conversion and evaluation pipeline can rely on general-purpose capabilities such as containerized builds, object storage for archiving model artifacts, and logging and monitoring services for tracking production behavior. Baidu AI Cloud’s general-purpose cloud products can serve as the infrastructure foundation for this kind of engineering pipeline.
8. Conclusion
The value of the new generation of open-source multimodal models lies not only in parameter scale but in structural density: per-layer embeddings give small models content-level performance close to much larger models, cross-layer KV sharing makes long context genuinely viable on-device, and heterogeneous attention with sparse experts bakes efficiency into the model design itself.
For inference engines, the essence of this adaptation round is treating model structure as a first-class citizen:
- Read the config: single-layer config drives graph rewriting, not global constants.
- Transform at export time: KV sharing, K=V, dual RoPE, and per-layer embedding fusion should all land in the graph stage.
- Evaluate by tier: cross size, hardware, and modality; refine metrics down to time-to-first-token, decode speed, and memory peak.
Getting these three right is what lets open-source on-device multimodal models ship reliably on phones, PCs, and the cloud, rather than remaining stuck at the demo stage.
