On-Device Multimodal LLM Adaptation: PLE, KV Sharing, and Heterogeneous Attention
This article explains how to adapt on-device multimodal large language models that combine layered embeddings (PLE), cross-layer KV sharing, and heterogeneous attention. It walks through a simplified comparison of three architecture generations, details how PLE is injected and exported, how KV sharing and heterogeneous attention are configured, and how vision and audio encoders join a unified sequence. It also proposes a three-layer adaptation framework for inference engines, along with an export/conversion/validation checklist, empirical-testing guidance, low-bit KV cautions, and common pitfalls. Engine teams will learn which mechanisms to parameterize, which require numerical cross-checking, and which should be trimmed per model variant.
Introduction: Why PLE, KV Sharing, and Heterogeneous Attention Need Unified Adaptation
On-device multimodal large models are moving from “can run” to “run well, run stably.” What truly drives up adaptation cost is usually not a single operator, but a combination of architectural mechanisms: How are hierarchical embeddings injected? How is cross-layer KV sharing configured? How is heterogeneous attention parameterized? How do vision and audio encoders join a unified sequence? If these are not abstracted into configuration and assertions upfront, you easily end up with a model that runs but produces unstable metrics.
To avoid misunderstanding: the names “Xiaojing 4,” “XL4,” and “Xiaojing4” used in this article are labels chosen for readability. They summarize a category of open-source on-device multimodal models and their mechanism combinations. They do not point to any specific product, nor do they imply any official alias or official derivative relationship with any external model.
From an adaptation standpoint, structural differences can exist even within the same series: different variants may use a different number of KV-sharing layers, different embedding forms, different vision encoders, or even change whether an independent v_proj is retained. Therefore, an inference engine should not rely on “one hand-written graph per model,” but should turn each mechanism into a general capability that is configurable, verifiable, and cross-checkable.
1. Three-Generation Architecture Evolution: Structure First, Then Adaptation Strategy
The table below is a simplified comparison of three architecture generations, with an added column on “impact on engine adaptation” so you can quickly judge which capabilities must be supported:
| Feature | XL3 | XL3n (edge transitional) | XL4 | Impact on engine adaptation |
|---|---|---|---|---|
| Attention mechanism | Hybrid attention | Hybrid attention | Hybrid attention | Must support composing multiple attention subgraphs |
| KV Cache | Independent per layer | Partial layers share | More layers share, larger sharing ratio | Must map KV source and cache slots per layer |
| Embedding | Shared input/output | PLE (direct injection via lookup) | PLE (lookup + projection fusion) | Must register the main embedding table and PLE sub-tables; support injection position and projection operators |
| QKV Norm | Q/K Norm | Q/K/V Norm | Q/K/V Norm, with attn_scale=1.0 | Must align normalization position and attention-scaling semantics |
| V projection | Independent v_proj | Independent v_proj | Some variants use K=V, no v_proj | Weight sizes and operator branches change; add load-time assertions |
| KV heads | Uniform across layers | Uniform across layers | Heterogeneous across layers | Kernel templates must be parameterized; cannot assume one KV head count for the whole model |
| Vision encoder | ViT | Lightweight CNN | ViT + Pooler | Must adapt the vision operator set, dynamic shapes, and pooling layers |
| Audio support | None | Conv-attention hybrid | Enhanced conv-attention hybrid | Audio frame length varies dynamically; needs separate preprocessing and projection validation |
| MoE | None | None | Large variants use fine-grained expert mixing (Top-k routing) | Needs routing, expert loading, and load statistics |
| Unique mechanisms | — | Cross-layer residual enhancement, per-layer decoding residual | K=V, heterogeneous KV heads, dual positional encodings | Must be configurable, not hard-coded |
The most important takeaway from this table: the key to on-device adaptation is not “memorizing one model’s structure,” but identifying which mechanisms can be parameterized, which require numerical cross-checking, and which need to be trimmed per variant. Inherited mechanisms can serve as a stable foundation; deeper mechanisms increase configuration complexity; and new experiments usually come with export and precision risks.
2. PLE: How Hierarchical Embeddings Are Injected and Exported
2.1 What Problem Does PLE Solve?
In large models, the input embedding table is often one of the larger parameter components. The vocabulary is large, the embedding dimension is close to the hidden-layer dimension, and the embedding table can occupy a considerable share of total parameters. If the output layer directly reuses the input embedding and that table participates in low-bit quantization, both the input and output sides may be affected by quantization noise at once, which can hurt first-token perplexity and long-text stability.
The core idea of PLE is to maintain a smaller embedding table for each layer or each group of layers of the Transformer. It looks up the current token in each table, applies the necessary transforms, and injects the result into each layer, thereby increasing model capacity with almost no significant increase in compute. Note that PLE is not simply “concatenating the input vector layer by layer.” Hidden states of adjacent layers are already highly similar, so ordinary concatenation offers limited capacity gains.
2.2 Two Forms: Direct Injection and Projection Fusion
From an engine-implementation perspective, PLE commonly has two forms:
- Direct injection: looks up per layer, then injects into the hidden state additively, with no extra linear layer.
- Projection fusion: first applies a linear projection to the looked-up vector (some implementations may also include normalization), then fuses it with the hidden state.
The two forms place different demands on the inference engine. Direct injection is simple to implement; projection fusion requires registering an extra linear operator and handling the scheduling of a “layer count × sub-table count” matrix during graph optimization.
2.3 Engine Adaptation Points
Keep weight layouts independent. The main embedding table and the PLE sub-tables should be stored and quantized independently. A sub-table’s shape is typically (number of layers or layer groups, vocabulary size, reduced dimension). The reduced dimension is often far smaller than the hidden-layer dimension, so you cannot infer the sub-table shape solely from the main embedding table.
Keep the injection order fixed. Injection usually happens before each layer’s input normalization. Direct-injection example:
# Direct-injection form (illustrative)h = main_embedding_lookup(token_ids) # [B, S, D_model]for l in range(num_layers):ple_vec = ple_table[l][token_ids] # per-layer table lookuph = h + ple_vec # element-wise additive injectionh = transformer_layer[l](rms_norm(h))
Projection-fusion example:
# Projection-fusion form (illustrative)h = main_embedding_lookup(token_ids)for l in range(num_layers):ple_vec = ple_table[l // layers_per_ple_group][token_ids]h = h + project_l(ple_vec) # extra linear projectionh = transformer_layer[l](rms_norm(h))
Read the position mapping from config. Which sub-table corresponds to layer l is usually determined by
layers_per_ple_groupor an equivalent setting. The engine must not assume “one table per layer” or “one shared table for the whole model.”Coordinate with prefix caching. PLE injection happens inside the inter-layer loop. As long as the token sequence and model weights stay unchanged, the injection result can be folded into the prefix cache; there is no need to repeatedly do lookups just for injection.
3. KV Sharing and Heterogeneous Attention: How to Adapt Them
3.1 What Problem Does KV Sharing Solve?
KV Cache memory or VRAM usage can be estimated by the following formula:
KV_bytes ≈ 2 × L × H_kv × D_head × S × B × dtype_bytes
Here L is the number of layers, H_kv is the number of KV heads, D_head is the per-head dimension, S is sequence length, B is batch size, and the coefficient 2 accounts for the two caches of K and V.
On edge devices, a KV footprint of several hundred MB directly squeezes the available runtime memory. GQA/MQA cut KV along the “head dimension,” while KV sharing compresses further along the “layer dimension.” The approach: the first several layers each compute their own K and V; the subsequent layers no longer compute their own K and V, but reuse the K and V from a specified source layer, projecting only Q.
3.2 Configuration-Driven Implementation
If the mapping is defined as {target layer: source layer}, then to determine whether a layer reuses KV you should check whether the current layer index is in the mapping’s keys(), not its values(). You also need to initialize self.layer_idx to avoid referencing an undefined field later in layer_states[self.layer_idx].
class AttentionLayer:def __init__(self, cfg, kv_sources):self.layer_idx = cfg["layer_idx"] # initialize the current layer indexself.kv_source_layers = kv_sources # {target layer: source layer}self.share_kv = self.layer_idx in kv_sources.keys()self.reuse_from = kv_sources.get(self.layer_idx)self.num_kv_heads = cfg["num_key_value_heads"] # may differ per layerself.use_v_proj = cfg.get("use_v_proj", True)self.attn_scale = cfg.get("attn_scale", None)def forward(self, x, layer_states):if self.share_kv and self.reuse_from is not None:k, v = layer_states[self.reuse_from]["kv"] # directly reuse source-layer K/Velse:k = self.k_proj(x)v = self.v_proj(x) if self.use_v_proj else klayer_states[self.layer_idx] = {"kv": (k, v)}q = self.q_proj(x)default_scale = q.shape[-1] ** -0.5scale = default_scale if self.attn_scale is None else float(self.attn_scale)attn = sdpa(q, k, v, scale=scale)return self.o_proj(attn)
Three points to watch during implementation:
Save state per layer. The source layer and the reusing layer must not share the same cache object; you must ensure that the reusing layer reads the correct K/V after the source layer has finished computing.
Heterogeneous KV heads. The
num_key_value_headspassed to each layer may differ, so the engine can no longer assume “one uniform KV head count for the whole model”; operator templates need to support parameterization.Some models use K=V. In this case the V projection weights disappear, and the layer must handle both “with-weights branch / without-weights branch” forms. If
use_v_proj=False, assert that thev_projweights do not exist, and thatvcomes directly fromk, with matching shape and dtype.
3.3 Correctly Understanding attn_scale=1.0: Final Scaling or a Q Multiplier?
When a config explicitly sets attn_scale to 1.0, it usually means “no longer apply the 1/√d scaling to the attention dot product.” This is not a typo but a deliberate design paired with QKV normalization: once Q and K have been normalized and their value ranges constrained, multiplying by 1/√d may unnecessarily compress the logits magnitude and affect softmax sharpness.
For implementation, it is recommended to define attn_scale as the final attention scaling factor rather than multiplying it only onto Q:
- When
attn_scaleis unset: use the defaultscale = q.shape[-1] ** -0.5. - When
attn_scaleis explicitly set: use the config value directly, and do not stack the default scaling on top. - If the engine interface only offers a Q multiplier while the backend still uses the default 1/√d, the Q multiplier should be converted to
attn_scale / default_scaleto avoid double scaling.
Suggested configuration assertions and reference implementation:
Assertion 1: if attn_scale is None, then scale = head_dim ** -0.5.Assertion 2: if attn_scale is explicitly present, then scale = float(attn_scale), and the default scaling is not stacked on top.Assertion 3: if reuse_from is not None, the target layer and source layer must have identical num_key_value_heads, head_dim, and dtype.Assertion 4: if use_v_proj is False, the v_proj weights do not exist, and v = k.
The reference implementation can be verified layer by layer in a CPU or FP32 environment:
for layer_idx in layers:if layer_idx in kv_sharing_map:source = kv_sharing_map[layer_idx]k, v = layer_states[source]["kv"]else:k = k_proj(x)v = v_proj(x) if use_v_proj else klayer_states[layer_idx] = (k, v)q = q_proj(x)scale = default_scale if attn_scale is None else attn_scalelogits = q @ k.transpose(-1, -2) * scaleattn = softmax(logits)y = attn @ v
If the graph-conversion stage uniformly injects the default scaling, it may overwrite an explicit attn_scale=1.0 into “double scaling.” Numerically, this often shows up as an overall shift in the output distribution; the decoding may still read fluently, but task metrics degrade noticeably.
4. Engineering Multimodal Capabilities: How Vision and Audio Join In
The multimodal path is essentially about embedding non-text tokens into a unified sequence space. For the engine, the difficulty concentrates in three areas.
Heterogeneous encoders. The vision side may switch from a lightweight CNN to ViT plus a learnable Pooler, while the audio side may use a hybrid structure of convolutional downsampling plus attention. The two encoder sets have different operator sets and different quantization-sensitive layers, so they must be registered and calibrated separately.
Dynamic resolution and frame length. Image sizes and audio durations are only known at runtime, so the number of vision tokens and audio frames fluctuates accordingly. The engine needs to support dynamic shapes and reserve positional-encoding resources for modality tokens.
Projection-layer mapping. Modality features ultimately pass through a projection layer to align with the language model’s dimension. For ViT, a common practice is to first compress the patch count, for example via pooling or pixel-shuffle-like operations, then apply a linear projection. In this case, the input dimension of the projection matrix is computed based on the “compressed token count,” which must be specified explicitly at export time.
In addition, the benefits of multimodality show up mainly in interaction forms, such as looking at images and listening to audio; it does not automatically improve pure-text task quality. Edge devices have tighter memory and power budgets, so whether to enable multimodality, and which path to enable, should be a configurable option rather than hard-wired into the weights.
5. A General Adaptation Framework for Inference Engines
Faced with the reality of “one series, many mechanism combinations,” it is recommended to split adaptation work into three layers, avoiding scattering model differences across hard-coded code:
① Architecture description layer: consolidate layer count, KV-sharing map, per-layer KV head count, PLE form and granularity,attention scaling policy, whether K=V, and modality encoder types into the configuration.② Graph construction layer: generate subgraphs from configuration and reuse operator templates instead of copy-pasting structures.③ Execution and caching layer: allocate KV slots and PLE lookups by layer index, ensuring correct inter-layer dependency order.
Suggested configuration fields include:
kv_sharing_map: {target layer: source layer}num_kv_heads_per_layer: [8, 8, 4, 4, ...]use_v_proj: falseattn_scaling: {mode: explicit, value: 1.0}ple_groups: {layers_per_ple_group: 4, ple_dim: 128}multimodal: {vision_encoder: vit_pooler, audio_encoder: conv_attn, max_pixels: ...}
Two supporting engineering habits:
- Bind “mechanism switches” to “weight layouts” for validation. When loading weights, immediately check whether the config matches tensor shapes, for example whether
v_projweights exist, whether the PLE sub-table count matches, and whether each layer’s KV head count conforms to the config, exposing problems at load time rather than at decode time. - Cover each mechanism combination with a minimal reproducible case. Each variant should have at least one short-prompt greedy-decoding cross-check, compared against a high-precision reference implementation’s logits.
6. Export, Conversion, and Empirical Validation Checklist
Whether a model lands smoothly often hinges on the details of the conversion pipeline. You can check in the following order:
Weight inventory check. Confirm whether
v_projexists; the count and dimensions of PLE sub-tables; the input dimensions of the vision/audio projection layers; the MoE expert weight layout.Configuration consistency. Check
attn_scale, the per-layer values ofnum_key_value_heads, the KV-sharing map, whether there are two sets of positional encodings,layers_per_ple_group, anduse_v_proj.Quantization strategy. Quantize the main embedding table and the PLE sub-tables separately; keep sensitive layers of the vision and audio encoders at higher precision; assess whether KV Cache should use low-bit storage separately.
Numerical cross-check. Under a fixed prompt, compare the per-token greedy output of the reference implementation against the engine implementation; then compare the Top-k overlap of the first-token logits.
Resource measurement. Record peak memory (weights + KV + activations), first-token latency, decode throughput, and behavior across different resolutions and audio durations.
Low-bit KV special check. Using low-bit storage for the KV Cache is not a purely engineering optimization; it can change the numerical distribution. Before enabling it, record the device, inference engine version, model variant, KV quantization bit-width, calibration set, sequence length, batch, and attention implementation. Recommended: run precision cross-checks, compatibility verification, numerical-drift observation, and rollback verification:
Reference implementation: CPU/FP32 or a high-precision GPU/FP16/BF16 pathValidation cases: short text, long context, multimodal input, long decodingMetrics: Top-1 agreement rate, Top-5 overlap, perplexity deviation, mean and variance of first-token logitsSuggested thresholds: greedy output identical for a fixed prompt; Top-1 agreement ≥ 99.9%, Top-5 overlap ≥ 99.5%, long-context drop within 0.5 percentage points; if business allows, perplexity deviation ≤ 1%Rollback strategy: first FP16/BF16, then INT8, and finally low-bit on only some layers; if repetition, truncation, or a sharp metric drop appears, stop using low-bit KV
- Minimal reproducible case. It is recommended to include at least the following information:
prompt: Explain KV sharing in on-device inference in three sentences.max_new_tokens: 64batch: 1greedy: trueengine version: fill in the actual versionquantization format: fill in W8A16, W4A16, KV-FP16, KV-INT8, etc.reference implementation: CPU-FP32 or a high-precision inference path
From the architectural features, you can give directional expectations, but these must be confirmed by empirical testing:
- More KV-sharing layers: in long-sequence scenarios, KV footprint and bandwidth pressure may drop noticeably, but whether it is obvious depends on sequence length, batch, KV quantization strategy, bandwidth, and device thermal conditions.
- Heterogeneous KV heads: the number of kernel templates and tuning cost will rise; implementations must be generated or selected separately for each layer’s KV head count.
- Dual positional encodings: local windows and global ranges may use positional encodings with different frequencies; the implementation should allow switching positional-encoding instances per layer.
- PLE projection fusion: compared with direct injection, it adds a linear operation, so on-device deployments should assess whether the compute cost is acceptable.
- Multimodal: first-token latency is affected by vision/audio preprocessing and encoder forward passes and must be measured separately; you cannot look only at pure-text decoding speed.
7. Practical Advice and Common Pitfalls
Pitfall 1: treating new mechanisms as “model details” and skipping them. Once KV-sharing maps, attn_scale, or K=V are misunderstood, the decoding may look normal while metrics decline, and the debugging cost far exceeds the effort of aligning them upfront.
Pitfall 2: assuming the whole series is structurally homogeneous. Mechanism combinations may differ across variants within the same series, so the adaptation framework must support trimming structure by configuration.
Pitfall 3: only doing end-to-end validation. It is recommended to add layer-level assertions, such as whether a reusing layer reads the correct K/V source, whether the PLE sub-table index is correct, and whether an explicit scaling overrides the default scaling, localizing errors at the mechanism level rather than as “model voodoo.”
Pitfall 4: ignoring on-device power constraints. Multimodal and large-variant models are limited by heat dissipation and battery during sustained inference on terminals, so long-run stability tests should be done on the target hardware before deployment.
In summary, the value of on-device multimodal model adaptation lies not just in “having one more open-source model that runs,” but in demonstrating a clear path for on-device evolution: compress the cache through sharing, improve parameter efficiency through layered embeddings, control numerical stability through normalization and attention scaling, and extend interaction boundaries through multimodality. For inference-engine teams, turning these mechanisms into general capabilities that are configurable, verifiable, and rollback-able yields more long-term value than custom optimization for a single model.
