On-Device Small Model Inference: A Guide to Layer-Wise Embedding Injection and KV Cache Sharing
When a single model family ships across multiple parameter sizes—from sub-billion-parameter models that fit in a phone's memory to tens-of-billions models that need a desktop-class GPU—the assumptions that once described model structure no longer hold. This article shows how to move those on-device differences out of hard-coded special cases and into a configuration-driven, per-layer capability description, so that one inference engine can cover an entire spec family. It walks through four evolution lines (layer-wise embedding injection, cross-layer KV cache sharing, heterogeneous attention with K=V simplification, and native multimodal scheduling), then covers the engine-side requirements, a five-step adaptation workflow, how to report benchmark numbers, selection advice, and a checklist of common pitfalls. Readers will learn how to represent heterogeneous layers, manage producer/consumer relationships in shared caches, and validate accuracy layer by layer instead of relying on a single final-output check.
1. Why Multiple Specs Are Harder to Adapt Than a Single Large Model
Over the past two years, on-device model evolution has shown a clear pattern: a single model family often ships several parameter sizes at once—from sub-billion-parameter models that fit in a phone’s memory, to tens-of-billions models that need a desktop-class discrete GPU or unified memory. Simply scaling parameters is widely seen as the lowest-cost approach, yet in practice vendors combine different architectural mechanisms across sizes. The reason is that the three on-device constraints conflict with one another:
- Memory capacity: embedded and mobile devices typically have only a few GB of usable memory, and weights, cache, and activations must all share that limited space;
- Memory bandwidth: during autoregressive decoding, every step streams the entire set of weights, so bandwidth usually becomes the bottleneck before compute does;
- Scheduling and power: multimodal encoders, the language model backbone, and the audio front-end are often handled by different execution units, so under a fixed power budget you need fine-grained temporal scheduling.
Because of this, smaller specs pursue “save memory, save bandwidth,” while larger specs pursue “quality and context capability,” which naturally leads to different combinations of mechanisms. For an inference engine, this directly means you can no longer describe model structure with global assumptions—implicit conventions like “every layer has its own K/V projection,” “every layer’s KV cache is the same size,” and “the embedding table is looked up only once” are broken one by one.
This article’s goal is to converge these differences from “special cases scattered in the code” into a configuration-driven, per-layer capability description, so that a single engine can cover the entire spec family.
2. Four Evolution Lines of On-Device Models
Summarizing currently public compact-model designs yields four mainlines. None is unique to a single vendor; all are general-purpose techniques for on-device optimization.
Line 1: Embedding representation moves from “single shared” to “layer-wise injection.” The traditional approach has all layers share one input embedding table, with the top layer reusing an output projection bound to it. The improved approach splits the embedding into a “base embedding + a separate low-rank correction term per layer,” injected at inference time directly into the corresponding layer’s input position. The benefit is eliminating repeated representation computation at each layer; the cost is that the engine must support “taking a different embedding tensor per layer.”
Line 2: KV cache moves from “independent per layer” to “shared across layers.” A group of adjacent decode layers reuses the same key/value tensors, and only a few layers hold their own cache. The higher the sharing ratio, the more the cache size drops under long context, but the engine must correctly express “which layers are producers and which are consumers.”
Line 3: Attention head structure becomes heterogeneous. Different layers can use different numbers of KV heads, and some layers even drop the independent V projection, using K directly for value aggregation. Such designs can significantly reduce cache width, but they invalidate the assumption that “all layers share the same head_dim.”
Line 4: From text models to native multimodal. The vision encoder, audio front-end, and language backbone are defined within the same model, so the input side no longer needs external pre-processing to assemble pieces. This requires the engine to have unified multimodal input description and cross-modal scheduling.
In addition, larger specs may introduce sparse mixture-of-experts (MoE): a large total parameter count with only a few experts activated per token, trading capacity for quality. This structure is not friendly to on-device settings (expert weights must either be fully resident or swapped in frequently); it is better suited to memory-rich desktop scenarios, and the engine should treat it as an independent “optional module” rather than the default path.
3. Layer-Wise Embedding Injection: What Is Actually Saved
3.1 Quantifying the motivation
Take a model with a large vocabulary. Embedding table parameters ≈ vocab size × hidden dimension. When the hidden dimension is only one or two thousand but the vocabulary reaches the hundreds-of-thousands scale, the embedding table can occupy a considerable share of total parameters. More importantly, if the input embedding is bound to the output projection, this weight still needs to be fully resident after quantization and cannot be reused the way activations are.
The core idea of layer-wise embedding: represent each layer’s input embedding as a low-rank linear transform of a lookup result, with the lookup contents precomputed offline. At runtime, the layer input no longer goes through a full “lookup + large matmul” but instead “lookup + small matmul/fusion,” which both reduces compute and lets different layers express different input views.
3.2 Three things the engine must support
from dataclasses import dataclass, field@dataclassclass LayerSpec:index: int# Attention structure (the key to heterogeneity)q_heads: intkv_heads: inthead_dim: inthas_v_proj: bool # False means K directly serves as Vkv_shared_from: int | None # None means this layer is a KV producersliding_window: int | None # None means global attention# Embedding injectionple_rank: int = 0 # 0 means this layer does no layer-wise injectionple_proj_out: int = 0 # Fusion dimension# Normalization and scalingqk_norm: bool = Truev_norm: bool = Falseattn_scale: float = 1.0@dataclassclass ModelSpec:layers: list[LayerSpec]hidden_size: intvocab_size: intmoe: dict = field(default_factory=dict) # Only populated for large specs
The key point: capability description must exist per layer, not as one global copy. The graph build and graph optimization phases iterate this table to decide operator selection, cache allocation, and graph partition points.
3.3 Two typical fusion implementations
- Lookup-direct injection:
h_l = lookup(table, token_ids). Each layer has its own correction table; simple and direct, suited to the tightest-memory specs. - Lookup + projection fusion:
h_l = lookup(...) @ P_l + base_embed. A low-rank projection mixes the base embedding with the layer-specialized embedding; stronger expressiveness, but requires an extra small matmul and precision alignment.
In engineering terms, unify both under the same operator interface and take a fast path when ple_rank == 0, so you avoid maintaining two code paths at model load time.
4. Cross-Layer KV Cache Sharing: Save Memory, but Keep Producers and Consumers in Order
4.1 A general estimate of cache size
During decoding, KV cache bytes can be estimated as:
bytes = 2 (K and V) × layers_with_own_cache × kv_heads × head_dim × seq_len × bytes_per_elem
The sharing mechanism does not change per-token compute, but it directly compresses the layers_with_own_cache term. If a layer group shares one cache, the higher the sharing ratio, the greater the gain under long context—which aligns exactly with the “longer context eats more memory” pressure.
4.2 Three error-prone points
- Index mapping errors. When a consumer layer writes to the cache, it corrupts the producer’s data. The symptom is usually not a crash but a slow degradation of output quality in the latter half of long sequences, which is easy to miss. Recommendation: assert on cache writes—only producer layers may write.
- Prefix sharing conflicts with incremental appends. If the engine supports cross-request prefix-cache reuse, shared caches must be keyed by “layer group” rather than “layer,” otherwise hit rates behave abnormally.
- Error accumulation in quantized caches. Shared-layer caches are read by more layers, amplifying the effect of quantization error. In practice, use one quantization scheme uniformly within a sharing group, and allow producer layers to use a higher bit width if needed.
4.3 Coupling with hybrid attention
When a model has both local-window attention and global attention, window layers only need cache for the window length (a ring buffer works), while global layers need the full history. Sharing must be established between layers of the “same type”; mixing window and global layers in one group is wrong. The engine should include sliding_window in the cache grouping key.
5. Heterogeneous Attention and the K=V Simplified Projection
When a layer keeps no independent V projection, its compute path becomes: K participates both in attention scoring and as the value in weighted summation. Key points on the engine side:
- Operator fusion cannot be assumed. K serves as both the right operand of the QK matmul and the left operand of the PV matmul; reuse the same tensor view to avoid redundant quantization/dequantization.
- The output projection weight shape must be read per layer, not described by a global weight.
- Different normalization positions (Q/K normalization vs. normalizing all of Q/K/V) affect numerical stability. Recommendation: write these differences into the layer description and let a unified operator implement them, rather than copying multiple variant operators.
Under heterogeneous structures, profiling must be done per layer rather than reporting only a model-level average. Arithmetic intensity can differ by several times across layers in a heterogeneous model, and the average hides the true bottleneck layer.
6. Native Multimodal: Scheduling Matters More Than Operators
Compact multimodal models usually export the vision encoder and audio front-end together. Key judgments during adaptation:
- Evaluate prefill and decode separately. Multimodal input introduces a large encoder cost before the first token, so first-token latency is mainly determined by the encoder and the visual token projection, while subsequent per-token latency is mainly determined by the language backbone. Measuring them together distorts the conclusion.
- Make the visual-token compression strategy explicit. The pooling/downsampling module determines the length that enters the language tower and is the most effective knob for controlling multimodal cost; expose it as a configurable option.
- The encoder and the backbone can be deployed heterogeneously. The encoder suits high-compute, low-frequency calls, while the backbone suits low-latency, continuous calls. Running them separately on devices with different compute units is often more robust than forcing them into a single graph.
- Batching strategies differ. The encoder favors large batches over the image dimension, while decode favors a single sequence with recurrence over the time dimension. The engine needs to support both batch semantics coexisting.
7. Turning Adaptation into a Process: The Five-Step Method
- Capability discovery: after the model loads, generate
ModelSpecfirst and validate that each layer’s parameters are self-consistent (for example, whether KV sharing groups form cycles, and whether layers missing V have an alternate path). Fail fast if validation does not pass, rather than crashing at runtime. - Operator coverage check: iterate the layer descriptions and build a support matrix for each operator across different shapes and quantizations. Emit a “not supported” list up front to avoid failing halfway through graph construction.
- Graph partitioning and memory planning: allocate weights, cache, and activations on a shared arena. Put the layer-wise embedding tables and KV caches in reusable pools; use ring buffers for window-layer caches; allocate shared-layer caches once per group.
- Numerical consistency regression: build a layer-wise comparison—first compare each layer’s max absolute error and cosine similarity, then compare final logits and top-k consistency, then compare generated text. Layer-wise comparison can localize a vague problem like “the whole output degrades” to a specific layer.
- Profiling and tuning: separately record first-token latency, steady-state per-token latency, memory peak, and decode arithmetic intensity; tune bottleneck layers individually (operator replacement, quantization bit width, batch size).
A schematic scheduling skeleton:
def decode_step(spec: ModelSpec, token_ids, cache_pool, ple_table):hidden = embed_base(token_ids)for layer in spec.layers:if layer.ple_rank:hidden = fuse_ple(hidden, lookup(ple_table, layer.index, token_ids),proj=layer.ple_proj_out)k, v = attn_qkv(hidden, layer, reuse_v=not layer.has_v_proj)if layer.kv_shared_from is None:kv = cache_pool.write(layer.index, k, v) # Producerelse:kv = cache_pool.read(layer.kv_shared_from, layer.sliding_window)hidden = attn_core(hidden, k, kv, layer) + ffn(hidden, layer)hidden = norm_out(hidden, layer)return lm_head(hidden)
8. How to Report Evaluation Numbers
Recommend a fixed reporting format: device and memory bandwidth, quantization scheme (per-layer bit width), context length, batch size, first-token latency, steady-state per-token latency, memory peak, and accuracy metrics. Any latency number that omits the quantization scheme and context length is not comparable. All structural conclusions above should be reproduced and verified through your own export pipeline; numerical and performance results will vary across implementations.
9. Selection and Usage Advice
- On-device: prefer the “minimum sufficient” spec. First work backward from available memory to the weight and cache budget, then decide the context length. Better to shorten the context than to let the cache spill into swap.
- Match quantization to structure: use a uniform scheme within shared-cache groups; keep embeddings and output projections moderately conservative; be more aggressive with attention projections; and localize with layer-wise error.
- Do not carry over on-device assumptions to large specs: sparse expert structures yield limited benefit on memory-constrained devices and only make sense when expert weights can be fully resident.
- Choose the encoder tier by actual workload: if the business is mainly document or chart understanding, the marginal benefit of visual-token compression over encoding precision is higher.
- Use general-purpose cloud capabilities for support: model files and evaluation data can go in object storage, builds and batch evaluations can run on a container platform, task orchestration and async callbacks can use a message queue, and run logs and metrics can connect to log and monitoring/alerting services. For example, on Baidu AI Cloud these general categories can be combined as needed to form a closed-loop “export–regression–evaluation–canary” pipeline without binding to specific implementation details.
10. Common Pitfalls Checklist
- Layer-wise embedding tables not precision-aligned, which amplifies error at the top layer;
- KV sharing groups mixed with window layers, causing long-sequence outputs to gradually break down;
- Layers missing a V projection incorrectly fused, so the PV stage reads the wrong tensor view;
- Regression run only on the final output with no layer-wise comparison, making problem localization take several times longer;
- Computing first-token and steady-state latency together, misattributing encoder cost to backbone performance;
- Layer specs hard-coded in the code, so adding a new spec requires modifying core operators and adaptation cost rises linearly.
Conclusion: The hard part of adapting multi-spec compact models is not any single operator, but whether the engine has the capabilities of “per-layer description, configuration-driven design, and layer-wise validation.” By abstracting the four items—embedding injection, KV sharing, heterogeneous attention, and multimodal scheduling—into a unified layer-spec description, and completing capability discovery and memory planning at export time, a single engine can cover the full family from small specs to desktop specs. Combined with layer-wise accuracy regression and per-item performance profiling, adaptation can shift from “special-casing one by one” to “configuration rollout + regression gating,” significantly lowering long-term maintenance cost.
