Open-Source LLM On-Device Adaptation: Breaking Down New Architecture Mechanisms and How to Implement Them

    As the open-source LLM competition shifts from raw parameter count toward efficiency per unit of compute, a new generation of compact multimodal models has become harder to run on-device. These models introduce non-standard designs in attention structure, cache management, and embedding injection that break the assumptions behind a "standard Transformer." Using a multi-size, multimodal open-source model family—featuring KV sharing and layered embeddings—as a worked example, this article breaks down the key mechanisms (per-layer embeddings, cross-layer KV sharing, heterogeneous attention, vision/audio branches, and sparse structures), lays out a seven-step adaptation workflow with clear pass criteria, and covers quantization strategies, evaluation metrics, and a checklist of common pitfalls. It is aimed at inference-engine developers who need a reusable methodology for adapting this class of models.

    1. Background: Why the New Generation of Edge LLMs Is Harder to Adapt

    Over the past two years, the focus of the open-source LLM competition has been shifting from “parameter scale” toward “efficiency per unit of compute.” The new generation of compact multimodal models shares several traits: their parameter range extends from hundreds of millions to tens of billions, covering phones, desktops, edge boxes, and servers; they natively support text, image, and audio; and they introduce a large number of non-standard designs in areas such as attention structure, cache management, and embedding injection.

    For inference-engine developers, this means two things:

    • The operator list is no longer a “standard Transformer.” Many new mechanisms cannot be expressed directly with the existing operator graph, so the engine needs to support custom operators, dynamic graph segmentation, or graph rewriting.
    • Structural differences between sizes have grown. Different sizes within the same model family may adopt different combinations of mechanisms (for example, small sizes use K=V to drop the separate V projection, while large sizes use mixture of experts). This means that “one static graph plus one scheduling strategy” is often not enough.

    This article uses the adaptation of a “multi-size, multimodal, KV-sharing, per-layer-embedding” open-source model family as an example to summarize a reusable adaptation methodology.

    2. Architecture Evolution: Shifts in the Design Orientation of Compact Multimodal Models

    Comparing these new models with earlier dense models makes the shift in design orientation clear:

    Design dimension Common practice in traditional dense models New orientation in compact multimodal models Main impact on the inference engine
    Attention Global / sliding-window hybrid Global/local alternating, with shorter local windows Needs to distinguish mask type per layer
    KV Cache Stored independently per layer Shared across layers; a group of layers reuses one KV Cache layout and lifecycle management become more complex
    Input embedding Single-layer embedding + optional input embedding scaling Per-layer embeddings injected at each layer Adds per-layer lookup + projection/addition operators
    QKV normalization Only Q/K normalized, or none at all Q/K/V all normalized; attention scaling fixed at 1.0 Fused-operator templates must be re-matched
    V projection Independent v_proj Some sizes set K=V directly and drop v_proj Variable-argument compute graph; more weight-loading branches
    KV heads Consistent across layers Heterogeneous across layers (different KV head counts per layer) GQA assumption breaks; cache tensor shape varies per layer
    Positional encoding Single-scale RoPE Local/global layers use different rotation base frequencies Positional encoding must be configurable and selectable per layer
    Vision encoding ViT-type encoder ViT-type encoder + pooling/projection alignment module One more subgraph that can be quantized independently
    Audio encoding Not supported Convolution + attention streaming encoder Multimodal branch interacts with the prefix cache
    Sparsification Dense FFN Small sizes use activation sparsity; large sizes use MoE Needs sparse memory-access and routing operator support
    Unique mechanisms — Adaptive update blocks on the residual path; inter-layer gated fusion Some layers’ control flow depends on runtime values

    In one sentence: these models push “efficiency optimization” down from the training side into the topology of the inference graph. The essence of the adaptation work is to first identify these topological differences, then decide which ones can be handled automatically by the compiler and which require manual intervention.

    3. Key Mechanism Breakdown and Adaptation Points

    3.1 Per-Layer Embeddings

    Motivation: At very small parameter counts, the vocabulary embedding table itself can consume a considerable share of memory, yet it is used only once in the first layer, giving it extremely low capacity utilization. The idea behind per-layer embeddings is to split “one large table” into “many small tables”: each layer maintains a much smaller embedding table (indexable by token or by channel), looks up a vector at the input of each layer, and injects it into the main hidden state after projection or direct addition.

    Adaptation challenges:

    1. Many non-resident weights appear at export time. The number of per-layer tables equals the number of layers, adding dozens of small operators to the graph, which is prone to explosion during constant folding.
    2. Injection points are not uniform. Some implementations add before normalization; others add after the attention output. This directly determines whether the numerical results align.
    3. Quantization strategy conflicts. Per-layer tables are small and accessed frequently. If they are quantized like regular weights, the precision loss in the first-token stage gets amplified layer by layer.

    Recommended approach:

    • Fuse “lookup + broadcast add” into a single custom operator, with the tables resident as static weights.
    • Keep embedding tables and the final output projection (lm_head) on independent quantization strategies; higher precision usually needs to be retained.
    • Force embedding-related operators onto a high-precision execution path, excluding them from low-bit inference.
    1. # Illustration: equivalent computation of per-layer embedding injection (pseudocode)
    2. h = embed(input_ids) # Main embedding
    3. for layer in range(num_layers):
    4. if layer in ple_layers: # This layer enables per-layer embeddings
    5. table = ple_tables[layer] # Resident weight
    6. add = table[token_idx] # Indexed by token or by channel
    7. h = h + project(add) # Broadcast add / linear projection
    8. h = layer_norm(h)
    9. h = h + attention(qkv_norm(h)) # Note that Q/K/V are all normalized
    10. h = h + mlp(layer_norm(h))

    3.2 Cross-Layer KV Cache Sharing

    Motivation: During autoregressive decoding, memory usage and memory bandwidth are dominated by the KV cache. Cross-layer sharing lets several consecutive layers reuse the same KV: the first few layers write to the cache normally, and the later layers read from it directly. This effectively computes the total cache based on the “number of independent KV layers” rather than the “total number of layers.”

    Adaptation challenges:

    • Miscalculating the cache allocation size is the most common serious bug. If the engine pre-allocates by total layer count, it wastes memory; if the sharing mapping is wrong, the output looks fluent but the semantics are already garbled, and it is extremely hard to locate.
    • Inter-layer dependencies break parallel splitting. There is an implicit dependency between shared layers and the layers they are shared with; multi-threaded pipelining or operator-level parallelism must model this explicitly.
    • Prefix-cache hit determination becomes more complex. When the cache is hit, the shared group must hit as a whole; otherwise a mixed state arises in which some layers use new KV and others use old KV.

    Recommended approach: Introduce an explicit “layer → cache slot” mapping table in the engine, and treat the shared group as the minimum unit of cache management.

    1. # Illustration: shared-group partitioning and cache layout
    2. def build_kv_layout(num_layers, share_from):
    3. layout = {} # layer_id -> kv_slot_id
    4. for layer in range(num_layers):
    5. layout[layer] = layer if layer < share_from else share_from
    6. unique_slots = sorted(set(layout.values()))
    7. return layout, unique_slots # Allocate memory by the count of unique_slots

    On top of this, add sparse sliding-window layers. These layers only need to keep the KV within the window and can write via a ring buffer, which further lowers peak memory.

    3.3 Heterogeneous Attention: K=V, Heterogeneous KV Heads, and Multi-Scale Positional Encoding

    The new generation makes three “subtractions” and two “additions” inside attention:

    • Subtraction 1: K=V. Some sizes no longer compute V separately and instead reuse the projection result of K, saving an entire set of weights and one matrix multiplication. When adapting, watch for the optionality of the weight-loading branch; do not treat v_proj as a required parameter.
    • Subtraction 2: Attention scaling fixed at 1.0. This omits the division by √d, but if the engine’s fused attention template hardcodes a scaling factor, the numbers will deviate directly.
    • Heterogeneous KV heads: Different layers use different numbers of KV heads. Traditional grouped-query attention assumes consistency across all layers; once this becomes heterogeneous, the last dimension of the cache tensor varies per layer and must be allocated separately for each layer.
    • Addition 1 / 2: Dual-scale positional encoding. Local and global layers use different rotation base frequencies (and possibly different interpolation methods). For long-context extrapolation, the scaling strategies of the two encodings must be configured separately.

    Recommended approach: Make attention a “parameterized template” that describes each layer’s attributes with configuration items, rather than duplicating an operator implementation for every structure.

    1. # Illustration: describing attention structure per layer (config snippet)
    2. layers:
    3. - {type: local, window: 1024, kv_heads: 2, rope_base: 10000, scale: 1.0, kv_shared: false}
    4. - {type: global, window: 0, kv_heads: 4, rope_base: 1000000, scale: 1.0, kv_shared: true, share_from: 8}
    5. moe:
    6. enabled: false
    7. top_k: 0

    3.4 Native Multimodal: Adapting the Vision and Audio Branches

    Vision branch: The typical structure is “encoder + pooling/projection alignment.” There are three adaptation points. First, the encoder’s output resolution varies with the input image size, so a set of tiers (e.g., minimum/common/maximum) must be fixed at export time and reused by tier at runtime to avoid repeated recompilation. Second, the pooling module often contains nonlinear normalization and fixed-shape token-selection logic; this part is very quantization-sensitive, so a separate high-precision path is recommended. Third, the position at which image tokens are inserted into the text sequence determines how the mask is constructed; a wrong insertion point manifests as “the model can read images but answers off-topic.”

    Audio branch: This is mostly a “front-end convolution downsampling + encoder” structure that supports streaming chunk processing. The key adaptation point is that the cache semantics differ—the text side caches KV, while the audio side often also needs to cache the convolution’s context frames and the encoder state, so the two cannot share the same cache-management logic. In addition, the audio branch has a variable number of time steps; it is recommended to pre-allocate by the maximum chunk length at the scheduling layer and then truncate by the effective length.

    3.5 Sparse Structures: Activation Sparsity and Mixture of Experts

    • Activation sparsity: Small models use the natural sparsity from ReLU-type activations to reduce memory access. When adapting, make sure the sparse memory-access kernels are actually invoked; otherwise it is only “nominal sparsity.”
    • Mixture of Experts (MoE): The routing layer selects the Top-K experts for each token, activating only a small fraction of the parameters. The key engineering tension is this: the total expert parameter count is large (requiring ample memory), while the actual compute per token is small (requiring fast memory access).
      • On-device: Keeping expert weights resident is unrealistic, so the usual approach is “load on demand” or “tiered placement by popularity,” placing hot experts in the high-speed region of memory/flash.
      • Server-side: A more common approach is expert parallelism + grouped batch routing, aggregating tokens that hit the same expert into a single matrix multiplication and avoiding the efficiency loss caused by small matrix multiplications.

    4. The Seven-Step On-Device Adaptation Workflow

    To turn the mechanisms above into an engineering process, proceed in the order below, setting a clear “pass criterion” at each step:

    1. Weight structure analysis: Scan weight key names and shapes and produce a “mechanism list”—whether there are per-layer embedding tables, which layers share KV, whether v_proj exists, whether the KV head count is consistent per layer, and whether expert weights are present. This list determines all the downstream workload.
    2. Operator list check: Map the mechanism list onto the engine’s existing operators and mark three categories: “supported / needs custom / needs graph rewrite.” Empirically, per-layer embeddings and KV sharing almost always fall into “needs custom.”
    3. Static graph export: Freeze the dynamic dimensions, and export multimodal inputs as multiple graphs by tier. Right after export, run a constant-folding pass to confirm that no large table has been copied N times.
    4. Per-layer numerical alignment: Using the same set of inputs, compare outputs layer by layer between the reference implementation and your own engine. A cosine similarity > 0.999 per layer is recommended as the pass criterion; once a layer drops below the threshold, first suspect the normalization position, the scaling factor, and the injection order.
    5. End-to-end precision verification: Fix the random seed and sampling parameters (temperature, top-p, and repetition penalty must be fully consistent), compare the first-batch token distribution and the full output of greedy decoding, then use perplexity to assess long-text degradation.
    6. Performance profiling: Measure first-token latency (compute-bound) and decoding speed (usually memory-bound) separately, and use cache hit rate, operator proportion, and memory-bandwidth utilization to locate bottlenecks rather than looking only at total elapsed time.
    7. Quantization and regression: Rerun steps 4 and 5 after quantization, and establish a three-dimensional “precision–size–speed” regression baseline, folding it into continuous integration to prevent later engine optimizations from introducing hidden precision regressions.

    5. Key Points on Quantization and Compression Strategy

    Module Recommended strategy Risk
    Main embedding / per-layer embedding / output projection Keep higher precision, or group quantization + high-precision accumulation Small-table quantization error is amplified layer by layer
    Attention QKV projection Per-group quantization; note that K=V sizes need no handling for V Heterogeneous KV heads cause inconsistent group boundaries
    KV Cache Optional low-bit cache (e.g., 8-bit), with a unified strategy within each shared group Inconsistent strategy between the shared group and private layers causes garbling
    FFN / expert weights High-ratio compression; experts tiered by popularity No benefit if sparse access does not take effect
    Vision / audio encoder Independent calibration dataset; run these on a separate high-precision path Calibrating the multimodal branch with a text corpus performs poorly
    Normalization and residual addition Force high precision Easily truncated by the numerical range at low precision

    One detail that is often overlooked: the calibration dataset must match the deployment scenario. A multimodal model calibrated with a pure text corpus typically degrades noticeably on image and audio tasks.

    6. Evaluation Metrics and Selection Guidance

    The payoff of adapting different sizes is completely different, so it helps to reason backward from the scenario:

    • Phone / wearable: Prioritize “smallest size + per-layer embeddings + KV sharing.” The core metrics are peak memory and sustained decoding speed, not peak compute.
    • Desktop / edge device: A medium size is an option; focus on validating the KV cache compression effect under long context.
    • Server: Large size + MoE better leverages the throughput advantage; the focus is on routing efficiency and expert-parallel load balancing.
    • Multimodal scenario: Measure “image/audio end-to-end latency” and “text decoding speed” separately. The former’s bottleneck is often in the encoder and pre/post-processing, not in the language-model backbone.

    On the deployment side, model weights and gray-release versions can be distributed via object storage, inference services can be orchestrated in a containerized way, and log and monitoring/alerting systems can be connected to continuously observe first-token latency, decoding speed, and memory usage. General-purpose capabilities from cloud platforms such as Baidu AI Cloud—containers, storage, logs, and monitoring—can directly take on this infrastructure work.

    7. Common Pitfalls Checklist

    • Allocating the KV cache by total layer count, causing memory over-provisioning and rendering the sharing logic useless.
    • Placing the per-layer embedding injection point after normalization; the numbers look reasonable but the semantics drift.
    • Failing to freeze the vision input resolution tiers at export, causing repeated recompilation at runtime.
    • Ignoring that attention scaling is fixed at 1.0, noticeably degrading long-text generation quality.
    • Sharing one management logic between the audio cache and the KV cache, causing state pollution in streaming scenarios.
    • Having inconsistent sampling parameters across implementations, and misjudging an implementation difference as “poor model capability.”
    • Skipping per-layer alignment after quantization and looking at the output only at the end-to-end level, making problem localization extremely costly.

    8. Summary

    A large part of the value of the new generation of open-source LLMs is hidden in structural innovations: per-layer embeddings improve capacity utilization at small parameter counts; cross-layer KV sharing directly lowers the memory wall in the decoding stage; heterogeneous attention and multi-scale positional encoding trade limited windows for long-context capability; and sparse structures decouple parameter scale from single-token compute. For the inference engine, the adaptation threshold has shifted from “implementing standard operators” to “supporting parameterized, heterogeneous, non-resident-weight graph structures.”

    The practical path can be summed up in one sentence: first use weight structure analysis to draw the mechanism list, then replace per-structure implementation duplication with parameterized templates, and finally use per-layer alignment to keep precision problems out before integration. Once these three steps are solidified into the process, the adaptation cost will drop significantly when facing more sizes and modalities in the future.