Adapting Inference Engines for Multimodal LLMs: Per-Layer Embeddings and Cross-Layer KV Sharing in Practice

    This article explains how to adapt a single inference engine to cover different tiers of on-device multimodal large language models. It recommends a landing order of correctness → quantization → memory reuse → operator fusion and scheduling, then breaks down the adaptation points for per-layer embeddings (PLE), cross-layer KV cache sharing, heterogeneous KV heads, K=V, dual RoPE, sparse experts, and multimodal input channels. It also provides checkable memory accounting, cache boundaries, and an acceptance checklist organized by tier, modality, context length, and quantization bit-width, so you can validate each mechanism against concrete conditions rather than assumptions.

    Conclusion first

    To cover the different tiers of this class of on-device multimodal LLMs with one engine, the recommended landing order is: correctness → quantization → memory reuse → operator fusion and scheduling. If you move on to the next step before the previous one is closed out, the most common outcome is mistaking a precision problem for a performance problem, then repeatedly rolling back and reworking. This article walks through that order and covers the adaptation points for per-layer embeddings (PLE), cross-layer KV cache sharing, heterogeneous KV heads, K=V, dual RoPE, sparse experts, and multimodal input channels, along with a memory accounting basis, cache boundaries, and an acceptance checklist you can verify item by item.

    One note on scope: the mechanism combinations summarized below come from observing commonalities across several open-source on-device multimodal model families. Which mechanisms a specific tier actually enables should be based on that model’s official configuration (config fields and structure definitions). The three-generation comparison table is a reference, not a fixed standard.

    1. Background: the adaptation pressure of the same family with different mechanisms

    Over the past year, architectural iteration in open-source LLMs has clearly accelerated. In particular, a family of models that focuses on multimodality and on-device deployment often ships a phone tier, a desktop tier, and a server tier within the same family. On the surface the only difference is parameter count, but different tiers frequently adopt different mechanism combinations: some enable cross-layer KV sharing, some introduce per-layer embeddings, some drop the independent value projection on certain tiers, and some replace the dense feed-forward network with sparse experts.

    Traditional inference frameworks usually assume the model structure stays consistent across specs and only scales by parameter count. When different tiers have structural differences in attention, embeddings, normalization, and expert routing, the engine must support multiple computation-graph shapes within a single codebase, and that is the main source of adaptation work.

    2. Three-generation architecture evolution comparison

    Feature Previous generation Transitional version New generation
    Attention mechanism Hybrid attention (local + global) Hybrid attention Hybrid attention
    KV cache Independent storage per layer Cross-layer sharing (a few groups) Cross-layer sharing (more layers merged)
    Embedding Shared embedding Per-layer embedding (lookup-table direct injection) Per-layer embedding (lookup table + projection fusion)
    Normalization Q/K norm Q/K/V norm Q/K/V norm + query scaling
    Value projection Independent v_proj Independent v_proj K=V on some tiers (no v_proj)
    KV head Uniform across layers Uniform across layers Heterogeneous KV heads (differ per layer)
    Vision encoder Vision Transformer Lightweight convolutional encoder Vision Transformer + Pooler
    Audio support None Convolutional audio encoder Enhanced audio encoder
    Expert structure None None Sparse experts, top-k routing
    Unique mechanisms — Training-side auxiliary structures, activation sparsity K=V, heterogeneous KV heads, dual RoPE

    Two main threads are clear. Inherited from the transitional version: PLE, KV sharing, hybrid attention, QKV norm, and native multimodal support are becoming standard for on-device multimodal models. Added in the new generation: K=V, heterogeneous KV heads, dual RoPE, and sparse experts reflect further compression of memory, parameter count, and compute under tighter resource constraints. To judge whether a mechanism is a one-off experiment or a long-term configuration, this evolution line is more reliable than looking at any single version.

    3. Core mechanisms and adaptation points

    3.1 Per-layer embeddings (PLE): when it saves memory and when it costs more

    A traditional Transformer uses a single shared embedding matrix of size vocab_size × hidden_dim, which can take up a significant share of memory and parameters on small models. The idea behind PLE is to shrink the embedding dimension to a very small value and maintain a separate low-dimensional table per layer (vocab_size × d_small). At runtime, it first looks up the low-dimensional vector, then maps it back to the hidden dimension with a projection matrix.

    Don’t state broadly that “memory usage drops significantly.” With per-layer independent tables, the parameter count on the embedding side becomes:

    1. L × (vocab_size × d_small + d_small × hidden_dim)

    Only when d_small is far smaller than hidden_dim / L, and these tables are quantized to a low bit-width, will the parameter count and memory usage fall below the shared-table scheme (vocab_size × hidden_dim). Otherwise, as the number of layers grows, the per-layer table parameters can completely overtake the shared table. In other words, PLE’s benefit depends on the tier: it is significant on tiers with few layers, large hidden dimension, and tables that can be quantized to a low bit-width, while tiers with many layers need to be measured before drawing a conclusion.

    1. # PLE forward: look up per-layer low-dimensional embeddings, then project back to hidden dimension
    2. # token_ids: [B, S] ple_table[l]: [V, d_small] proj[l]: [d_small, H]
    3. def ple_forward(token_ids, layer_idx):
    4. small = ple_table[layer_idx][token_ids] # [B, S, d_small]
    5. return small @ proj[layer_idx] # [B, S, H]

    The engine-side difficulty: the independent tables and projection matrices per layer must be managed separately, projection fusion must be configured per layer, embedding tables usually carry the most aggressive low-bit scheme, and lookup is a high-frequency memory-access operation, so improper fusion turns directly into a bottleneck.

    3.2 Cross-layer KV cache sharing: under what conditions the 1/N benefit holds

    During autoregressive decoding, the KV cache is often the largest source of memory usage. Cross-layer sharing lets several consecutive layers reuse the same set of K/V; only the “owner layer” computes and writes them, while the other layers read directly.

    The boundary must be stated: the KV memory is about 1/N of the original only when all layers are merged into groups of N layers and the KV head count and head_dim are exactly consistent within each group. Sharing only some layers means the benefit scales down by the proportion of merged layers; when the KV head count or dimension within a group is inconsistent, naive reuse fails outright. For estimation, accumulate per group:

    1. KV bytes ≈ 2 × B × S × dtype_bytes × Σ(KV_h × head_dim per group)

    K and V each take one share, S is the context length, and Σ iterates over all sharing groups (unshared layers each form their own group). In the heterogeneous KV head scenario, estimating with this basis is far more accurate than the rough “total layers / N” calculation.

    1. # Minimal runnable example of cross-layer KV sharing
    2. # x: [B, S_in, H] k/v: [B, S_in, KV_h, D] state.kv[i] = {"K": [...], "V": [...]}
    3. def step_kv(layer_idx, x, state, cfg):
    4. owner = cfg.layer_to_owner[layer_idx] # which layer's K/V this layer reuses
    5. if owner != layer_idx: # non-owner layer: alias reference, no recompute or re-store
    6. kv = state.kv[owner]
    7. state.kv[layer_idx] = kv # key point: otherwise later per-layer cache lookups hit nothing
    8. q, _, _ = qkv_proj(x, kv_cache=kv)
    9. return q, kv
    10. q, k, v = qkv_proj(x) # owner layer: the sole producer within the group
    11. assert k.shape[2] == v.shape[2] == cfg.kv_heads[owner], "inconsistent KV head count within sharing group"
    12. assert k.shape[3] == v.shape[3] == cfg.head_dim[owner], "inconsistent head_dim within sharing group"
    13. kv = state.kv.get(layer_idx) or {"K": [], "V": []}
    14. if cfg.phase == "decode":
    15. kv["K"].append(k) # decode: append in place per step
    16. kv["V"].append(v)
    17. else:
    18. kv["K"] = [k] # prefill: write the whole segment at once
    19. kv["V"] = [v]
    20. state.kv[layer_idx] = kv
    21. return q, kv

    The sharing strategy also affects prefix caching and paged attention; see item 4 in Section 4.

    3.3 Native multimodal support: how to handle dynamic shapes

    On the vision side, the vision encoder (such as a Vision Transformer) typically encodes image patches first, a Pooler compresses the token count, and a projection layer aligns them to the language backbone’s hidden dimension. On the audio side, mainstream encoders are mostly Transformer / Whisper-style structures, and some models use convolution-enhanced structures like Conformer. Designing audio-encoder scheduling with a pure CNN mindset (for example, assuming a fixed receptive field and fixed time steps) will trip you up on variable-length audio; scheduling should be modeled as “variable-length sequence + optional downsampling.”

    Deployment checklist:

    • Bucket vision inputs by resolution for batching, to avoid shape jitter within the same batch triggering repeated recompilation.
    • Estimate the vision token budget in advance based on image size, reserve room for the text context, and when the budget is exceeded, reduce resolution or truncate first, rather than running halfway and then OOMing.
    • Pipeline / asynchronously schedule the encoder and language-model decode, build graphs separately for prefill and decode, and overlap image encoding with the previous batch’s text decoding.
    • Account for multimodal token embeddings separately; their memory cost is not in the KV cache and is easy to miss during capacity planning.

    3.4 Heterogeneous KV heads, K=V, and dual RoPE: what the engine must do per layer

    • Heterogeneous KV heads: different layers have different KV head counts, so the attention kernel cannot be one-size-fits-all. Configure GQA grouping per layer, or pad each layer to a uniform head count and mask the padding regions before softmax.
    • K=V (no v_proj): some tiers derive Value directly from Key, dropping the independent value projection and reducing both parameters and operators. The engine should skip v_proj based on a capability flag and prevent K and V from overwriting each other when they share the same buffer.
    • Dual RoPE: local layers and global layers use different rotary position embedding base frequencies, which must be distinguished per layer at graph-build time, not probed at runtime.

    4. Five key challenges: concrete approaches and failure symptoms

    1. Multiple computation graphs coexisting. Approach: abstract has_v_proj, kv_shared, moe, and heterogeneous kv_heads into capability flags, assemble the computation graph at build time, and push shapes and routing tables down into configuration rather than baking them into kernels. Failure symptom: adding a new tier requires changing the kernel; a tier’s q/k/v channels don’t line up, weights load misaligned, and output fluency drops sharply.
    2. Dynamic shape handling. Approach: build graphs separately for prefill and decode, bucket by vision resolution, and drive batching with a token budget table. Failure symptom: a new resolution image triggers recompilation and first-token latency jitters by several times; long image-text requests occasionally OOM.
    3. Quantization support. Approach: select schemes separately for embedding tables, expert weights, and the KV cache (KV often uses int8 per-head / per-channel scale); keep higher precision on the first/last layers and pre-norm operators, and force a precision regression after quantization. Failure symptom: short Q&A shows no issue, but long-context and multi-turn dialogue quality drops noticeably, and it is first suspected to be a model-capability problem.
    4. Memory management. Approach: have KV sharing, paged attention, and cache reuse share one allocator; map the block table to prefix caching and paged attention at sharing-group granularity, and verify that the KV head count within the group is consistent; when an owner layer’s block is evicted, define an explicit policy — recompute that group’s K/V, or roll the entire group back to per-layer independent caching. Failure symptom: after a prefix-cache hit, attention reads another group’s K/V, giving wrong but hard-to-notice results; after evicting the owner layer, a dangling reference remains, manifesting as random crashes or silent numerical errors. Long-context scenarios benefit most from sharing and most need heterogeneous KV heads and eviction boundaries written into test cases.
    5. Operator fusion and scheduling. Approach: fuse QKV normalization and attention scaling, fuse PLE projections, and asynchronously overlap the encoder and decode. Failure symptom: single operators match on precision, but values drift after fusion (most typical in the K=V scenario, where the value borrowed from the key buffer is overwritten by later writes); or throughput goes up while TPOT jitter gets worse.

    5. Evaluation methodology: acceptance criteria and a per-tier matrix

    Evaluating this class of models cannot stop at “does it run.” All four dimensions need acceptance criteria:

    • Correctness: compare layer by layer against the official reference implementation, record cosine similarity and maximum absolute error, and measure greedy-decoding top-1 agreement. As a starting example, you can use thresholds like “per-layer cosine similarity ≥ 0.999 and maximum absolute error on key layers on the order of 1e-2,” but you must calibrate per model in practice — do not apply them directly.
    • Performance: record first-token latency (prefill), per-token decode latency (TPOT), and overall throughput (tokens/s) separately, and note the batch size, context length, quantization bit-width, and software/hardware environment; otherwise the numbers are not comparable.
    • Memory: record peak GPU/host memory and actual KV cache usage, and compare against the estimation basis in Section 3.2 to verify whether cross-layer sharing is actually in effect.
    • Multimodal capability: evaluate vision and audio understanding accuracy on representative tasks separately, and state the maximum number of images, resolution, and audio duration.

    It is advisable to establish an independent baseline for each spec tier, expand the evaluation matrix over “tier × modality × context length × quantization bit-width,” and avoid running only the default combination, which misses most of the failure paths specific to each tier.

    6. Engineering practices and recommendations

    • Correctness first, optimization later: get layer-by-layer correctness comparison working before introducing quantization and operator fusion, to avoid chasing a precision problem as if it were a performance one.
    • Automated regression: put every tier and modality into regression so that any mechanism or kernel change is caught promptly.
    • Use KV sharing benefits, but cover the boundaries: focus testing on heterogeneous KV heads, inconsistent head counts within a group, and eviction of the owner layer.
    • On-device, prioritize quantization + memory reuse: small tiers are extremely sensitive to memory, and low-bit quantization combined with cache reuse often decides whether it runs smoothly; at the same time, keep mixed-precision and one-click rollback switches, because quantization may cause precision regression in long-context and multi-turn scenarios.
    • Elastic server-side deployment: when targeting servers, use general capabilities such as object storage, container services, and monitoring and alerting to handle model distribution, elastic scaling, and observability, and expose the inference service reliably.

    7. Summary

    The new generation of multimodal LLMs folds PLE, cross-layer KV cache sharing, hybrid attention, and sparse experts densely into a single family, representing the engineering trend of LLMs toward on-device and multimodal deployment. For developers, the difficulty is not “getting it to run once” but robustly covering multiple tiers, modalities, and mechanisms with one engine. Sorting out the evolution line, writing each mechanism’s applicable boundary as checkable conditions (PLE’s parameter-count formula, the 1/N precondition for KV sharing, per-layer configuration for heterogeneous KV heads), and then building a per-tier evaluation that covers correctness, performance, memory, and multimodal capability is the reliable path to landing this class of models stably.