On-Device LLM Inference Adaptation: Per-Layer Embeddings and KV Cache Sharing

    Deploying large language models on devices requires balancing peak memory, latency, power, and multimodal inputs across multiple model variants. This article examines three common adaptation mechanisms—per-layer embeddings, KV cache sharing, and multimodal input handling—and provides implementation guidance and validation checkpoints. It also covers memory estimates, heterogeneous KV-head and projection variants, and specification-based strategies for small, medium, and large models.

    1. Background and Problem Definition

    After large models move from the cloud to endpoint devices, inference deployment faces three types of constraints. First, memory capacity is limited: model weights, activations, and KV cache jointly determine peak memory. Second, power and latency budgets are tight; phones and embedded devices cannot sustain high load for long periods. Third, input modalities are expanding: in addition to text, images and audio also need to enter the same inference pipeline.

    The same model family usually offers multiple parameter sizes. Small specifications target phones and edge devices, while large specifications target desktops or servers. Differences between specifications are not just proportional scaling of layer count and hidden dimension. Some specifications introduce new structural designs, such as per-layer embeddings, cache sharing, or different attention head configurations. This means the inference engine must separately check the computation graph, operator support, and cache strategy for each specification; replacing weight files alone is not enough.

    This article breaks down three common mechanisms: Per-Layer Embedding (PLE), KV cache sharing, and multimodal input adaptation. The content here describes general technical methods and does not rely on performance data from any specific product. Readers can apply the same review process to other models with similar structures.

    2. Core Constraints of On-Device Inference

    Before designing an adaptation plan, it is necessary to clarify the sources of constraints. On-device inference is usually limited by the following metrics.

    1. Peak memory: composed of resident weight memory, activations for a single forward pass, and KV cache that grows with sequence length. In long-context scenarios, KV cache is often the fastest-growing part.
    2. Time to first token: the time from input prompt to generation of the first output token, mainly affected by computation in the prefill stage.
    3. Generation rate: the number of output tokens per second, mainly limited by memory bandwidth. In the decoding stage, generating each token requires reading a large amount of weights and cache.
    4. Sustained performance: after device temperature rises, frequency drops, and short tests can easily overestimate actual experience.

    When optimizing, first identify the main bottleneck. When memory is tight, prioritize quantization, cache compression, and structural sharing. When latency is sensitive, prioritize operator fusion, batching strategy, and prefill optimization.

    3. Per-Layer Embedding (PLE)

    3.1 Difference Between the Traditional Approach and Per-Layer Embedding

    Most Transformer models use only one token embedding table at the input, mapping token IDs to vectors; subsequent layers process only hidden states. The idea of per-layer embedding is to provide an independent small embedding lookup table for each layer or each group of layers. The lookup result is fused with the hidden state before entering that layer’s computation.

    The benefit of this design is that the lookup operation has very low computational cost, yet it can supplement each layer with information directly related to the token. It effectively expands the model’s capacity without adding a large number of matrix multiplications.

    3.2 Memory and Computation Cost

    The main cost of per-layer embedding comes from the embedding tables themselves. Assume the vocabulary size is V, the per-layer embedding dimension is d_ple, and the number of layers is L; the additional storage is approximately V × d_ple × L parameters. These parameters do not participate in large-scale matrix multiplication, so they can be placed in slower but larger storage and read on demand. Quantization is also a common technique. Embedding tables usually tolerate low-bit quantization more than attention weights, but validation with real samples is still required.

    3.3 Fusion Methods

    There are two main fusion methods. The first is direct additive injection: the lookup result is added element-wise to the hidden state, requiring both to have the same dimension. The second is to apply a linear projection first and then fuse with the hidden state. The projection method adds one matrix multiplication, but it can handle dimension mismatch and allow the model to learn a more flexible mapping. During adaptation, follow the model configuration; do not arbitrarily replace the fusion method.

    Example code:

    1. function decoder_layer(hidden, token_ids, layer_idx, ple_table, ple_proj):
    2. ple_vec = ple_table[layer_idx][token_ids] # lookup, shape [seq_len, d_ple]
    3. ple_vec = ple_proj[layer_idx](ple_vec) # project to hidden dimension; skip if configured for direct injection
    4. hidden = hidden + ple_vec # fusion
    5. hidden = attention_block(hidden)
    6. hidden = feed_forward_block(hidden)
    7. return hidden

    3.4 Validation Points

    When implementing per-layer embedding, check three places. First, whether the lookup indices match token IDs, especially for batching and padding positions. Second, whether the offsets of each layer’s embedding table are correct, avoiding different layers reading the same segment of data. Third, whether the output difference between the quantized embedding table and the reference implementation is within an acceptable range. For validation, use fixed inputs and compare intermediate tensors layer by layer rather than comparing only the final output.

    4. KV Cache Sharing

    4.1 Basic Principle

    In autoregressive generation, each layer’s attention must store the keys (Key) and values (Value) of historical tokens, i.e., the KV cache. Cache size grows linearly with layer count, head count, head dimension, and sequence length. KV cache sharing lets multiple layers reuse the same set of cache tensors. The first layer in a group is responsible for computing and writing K and V, while the other layers in the group compute only their own queries (Query) and read the shared cache.

    This design directly reduces cache occupancy while not changing each layer’s query computation.

    4.2 Memory Estimation

    The following is a hypothetical example; the numbers are used only to illustrate the calculation method and do not represent any specific model.

    Cache bytes = 2 × number of independent cache layers × KV heads × head dimension × sequence length × bytes per element

    Assume a model has 32 layers, forms 16 groups of independent cache after sharing, has 8 KV heads, head dimension 128, sequence length 4096, and stores data in 16-bit floating point. Then:

    • Before sharing: 2 × 32 × 8 × 128 × 4096 × 2 bytes, about 512 MiB
    • After sharing: 2 × 16 × 8 × 128 × 4096 × 2 bytes, about 256 MiB

    Cache occupancy is proportional to the number of independent cache layers, so the larger the sharing group, the more obvious the savings. Actual benefits also depend on other memory overheads, such as activations and runtime buffers.

    4.3 Implementation Points

    Implementing shared cache requires solving three problems.

    First, the mapping between layers and cache. The inference engine should build a mapping table from layers to cache slots during loading and perform direct lookup at runtime, avoiding complex decisions in every forward pass.

    Second, attention masks. Layers within the same group may use different attention patterns, such as local window attention and global attention. Shared cache can only guarantee identical key/value content; it cannot replace mask logic. Each layer still needs to use its own mask configuration.

    Third, write timing. After the first layer in the group finishes writing, subsequent layers can read. If the execution order is reordered by the scheduler, incorrect results will occur, so dependencies must be fixed during graph construction.

    Example code:

    1. cache_map = build_cache_map(config) # layer index -> cache slot
    2. function attention(layer_idx, hidden):
    3. slot = cache_map[layer_idx]
    4. q = project_q(hidden, layer_idx)
    5. if layer_owns_cache(layer_idx):
    6. k, v = project_kv(hidden, layer_idx)
    7. cache.write(slot, k, v)
    8. k, v = cache.read(slot)
    9. mask = get_mask(layer_idx)
    10. return scaled_attention(q, k, v, mask)

    4.4 Validation Points

    When validating cache sharing, test both prefill and token-by-token decoding stages separately. In long-sequence scenarios, check whether out-of-bounds overwrite occurs when the cache slides or extends. It is also recommended to compare outputs under shared and non-shared configurations with the same input, confirming that differences come from expected design changes rather than implementation errors.

    5. Heterogeneous KV Heads and Projection Variants

    5.1 Heterogeneous KV Heads

    Different layers may have different numbers of KV heads or head dimensions; for example, local attention layers and global attention layers may use different configurations. If the inference engine assumes that all layers have the same cache shape, it will fail during loading or at runtime.

    There are two handling approaches. One is to allocate a cache with an independent shape for each layer and read the configuration per layer at runtime. The other is to allocate the cache according to the maximum shape and pad it, but this wastes memory. The former is more memory-efficient and more complex to implement, and it is usually the more reasonable choice.

    5.2 Optional Projection Structures

    In some models, the value projection may share parameters with the key projection, or some layers may omit independent value projection weights. The loader should determine the structure from the configuration and the actual contents of the weight file, and must not assume that every layer has two sets of projection weights. When missing, it should fall back to the correct computation path according to the configuration and output clear logs.

    5.3 Attention Scaling and Positional Encoding

    The attention scaling factor is not necessarily the inverse square root of the head dimension; some models specify other values in the configuration. Positional encoding may also use different parameters depending on layer type, such as different rotary bases. These parameters must be read from the configuration and must not be replaced by default values. Default values are one of the common causes of output mismatch with the reference implementation.

    6. Multimodal Input Adaptation

    6.1 Image Input Pipeline

    Before images enter the language model, they usually go through the following steps:

    1. Preprocessing: scaling, cropping, normalization, and splitting into patches at the configured resolution.
    2. Visual encoding: using a Vision Transformer or similar encoder to extract features.
    3. Pooling and projection: reducing the number of tokens and mapping features to the language model’s hidden dimension.
    4. Placeholder replacement: in the input sequence, replacing the corresponding placeholder positions with visual features.

    Each step affects the final result. For example, the number of image tokens and the number of placeholders must match exactly; otherwise alignment errors will occur, and the output often appears as unrelated text or repeated content.

    6.2 Audio Input Pipeline

    Audio input is generally first converted to spectral features, such as a log-Mel spectrogram, then processed by a speech encoder, and finally projected into the language model space. The audio encoder may combine convolutional and attention structures. The length of the audio segment directly affects encoding time and memory, so it is recommended to set a maximum length and segment overly long inputs for processing.

    6.3 Engineering Recommendations

    Multimodal inference usually consumes more memory than text-only inference because the visual or speech encoder itself requires additional weights and activation space. In practice, the following measures can be taken:

    • Separate the encoder and language model execution sessions to avoid stacking peak memory.
    • Cache visual features for the same image so that repeated questions do not require re-encoding.
    • When supporting dynamic resolution, limit the maximum number of patches to prevent sudden GPU memory spikes.
    • Perform numeric range checks on encoder outputs to detect preprocessing errors early.

    Example code:

    1. function multimodal_prefill(text_tokens, image):
    2. patches = preprocess_image(image, max_patches)
    3. vis_feat = vision_encoder(patches)
    4. vis_tokens = pool_and_project(vis_feat)
    5. assert len(vis_tokens) == count_placeholders(text_tokens)
    6. embeds = embed(text_tokens)
    7. embeds = replace_placeholders(embeds, vis_tokens)
    8. return language_model.prefill(embeds)

    7. Specification-Based Adaptation Strategy

    The same set of methods has different priorities across specifications.

    Specification class Typical target devices Key focus
    Small specification Phones, embedded devices Peak memory, embedding table storage location, encoder trimming, low-bit quantization
    Medium specification Laptops, lightweight workstations Time to first token, cache length limit, parallel scheduling
    Large specification Desktop workstations, servers Throughput, multi-GPU partitioning, routing load balancing for mixture-of-experts models