On-Device LLM Architecture Explained: Layer-wise Embedding and Cross-Layer KV Sharing in Practice

    This article breaks down the architecture of on-device large language models, focusing on the two mechanisms that matter most for fitting long context onto phones and edge devices: layer-wise embedding and cross-layer KV cache sharing. It compares three generations of model design, explains what each mechanism solves and what it costs an inference engine to support (heterogeneous KV heads, K=V binding, attention scaling fixed at 1.0), then covers native multimodal support and the tradeoffs of MoE sparse activation on-device. It closes with a practical adaptation checklist spanning export, operator alignment, layered quantization, and a regression evaluation set.

    1. Where the Problem Starts: “Same Generation, Different Architectures”

    Over the past couple of years, open-source lightweight models aimed at phones, edge boxes, and desktop workstations are typically released in four size tiers at once, scaling from roughly 2 billion parameters up to 30 billion. The most common trap in engineering practice is treating these four tiers as different-width versions of a single architecture and covering all of them with one export script and one operator configuration. In reality:

    • The smallest tier is constrained by memory bandwidth, so it introduces more “bandwidth-saving” special mechanisms;
    • The middle tier pursues on-device multimodality, so the way its encoder merges with the backbone differs;
    • The largest tier starts introducing sparse activation and heterogeneous attention heads.

    What the three share is a design philosophy, not a computation graph.

    So when evaluating or adapting such a model family, the correct order of attack is: first read the attention and caching strategy in the config, then the embedding injection path, and only last the vision/audio branches. This article follows that order.

    2. Architecture Evolution at a Glance (Neutral Comparison)

    Placing three typical generations side by side reveals a clear path of capability migration:

    Feature First-gen entry architecture On-device transitional architecture New-gen hybrid architecture
    Attention pattern Local window + global mix Local window + global mix Local window + global mix
    KV cache Each layer holds its own Shared across adjacent layers (~10 layers per group) Wider-span sharing (18–20 layers)
    Token embedding One shared copy in the backbone Layer-wise embedding, injected directly after lookup Layer-wise embedding, projected and fused after lookup
    QKV normalization Q/K normalization Q/K/V normalization Q/K/V normalization + attention scaling fixed at 1.0
    V projection Independent V projection matrix Independent V projection matrix Some tiers set K=V, dropping the V projection
    Number of KV heads Uniform across layers Uniform across layers Heterogeneous across layers (different head counts per layer)
    Positional encoding Single-band rotary Single-band rotary Dual-band rotary (separate params for local + global)
    Vision encoder ViT structure + pooling Lightweight conv backbone (mobile-first) ViT structure + explicit pooler
    Audio support None Conv-enhanced Conformer-like encoder Unified speech encoding branch
    Sparse activation None None Middle tier uses MoE, 128 experts Top-8

    Three takeaways:

    1. Layer-wise embedding and KV sharing are the core gains of on-device deployment — they directly determine whether long context fits into an 8GB phone.
    2. Heterogeneous KV heads and K=V binding are the main source of engine adaptation work, because they break the implicit assumption that “all layers are structurally identical,” an assumption that much operator fusion and batched inference rely on.
    3. Multimodality is “native,” not “bolted-on” — the encoders share the tokenization and positional-encoding space with the backbone, which demands tighter coupling in the pre/post-processing pipeline.

    3. Mechanism 1: Layer-wise Embedding

    3.1 What problem it solves

    A traditional decoder looks up the vocabulary once at the input layer, then passes the resulting vectors up layer by layer. For on-device models this creates two conflicts: the vocabulary is huge (100k+ entries), so a shared embedding matrix alone eats a sizable chunk of resident memory; and the deep network’s ability to distinguish fine-grained semantics is capped by a representation that has been “compressed once.”

    Layer-wise embedding maintains a smaller lookup table for several layers. Each of these layers receives an extra vector — looked up directly from the token — in addition to its regular input, and adds it (in the newer design, the vector also goes through a linear projection for dimension alignment and mixing). The gain: with almost no added matrix multiplication, “surface word information” is delivered more directly to the deep layers, improving the factuality and instruction-following of small models.

    3.2 The cost the inference engine pays

    • Input goes from 1 to N: besides each layer’s hidden_states input, you must also feed the token ids or the already-looked-up embeddings; the graph shifts from single-entry to multi-entry.
    • Vocabulary lookups go from 1 to many: if the engine treats the lookup as an operator, it must build resources per sharing group; a better approach is cross-layer reuse caching on the engine side, where one gather serves multiple layers.
    • The shape of the projection fusion: a concat-then-fuse form like [lookup ‖ hidden] × W introduces concat + large matmul. During quantization, pay special attention to scale alignment along the concat dimension, or the precision loss gets amplified layer by layer.

    Illustration (pseudo-code, to show the shape of the computation graph):

    1. # Each layer's input is no longer just the hidden state
    2. for layer_idx, layer in enumerate(layers):
    3. x = x + layer.embedding_proj(
    4. embed_table[layer_idx][token_ids] # layer-wise lookup
    5. )
    6. x = layer.attn(layer.norm(x), kv_cache)
    7. x = layer.ffn(layer.norm(x))

    3.3 Engineering advice

    Layer-wise embedding tables are usually the most underestimated part of model size. Before shipping, compute: num_layers × group_size × vocab_size_per_layer × hidden_dim × quantization_bytes. If VRAM/memory is tight, consider low-bit quantization (4-bit) for the lower tiers’ layer-wise tables, or even sparsification by access frequency, while keeping the first and last layers at high precision.

    4. Mechanism 2: Cross-Layer KV Cache Sharing

    4.1 Principle and gains

    Multiple attention layers within the same group reuse one K/V cache instead of each holding its own. When the sharing span grows from ~10 layers to 18–20 layers, the memory savings in long-context scenarios are substantial — KV cache usage is roughly proportional to “independent layer count × sequence length × num KV heads × head dim,” so halving the independent layer count roughly halves the cache.

    The cost is reduced expressiveness: shared layers can’t maintain their own context summary. Vendors usually mitigate this with a hybrid arrangement of “local window attention + sparse global layers,” keeping the few layers that genuinely need long-range information on independent caches.

    4.2 Three error-prone details

    1. Heterogeneous KV heads: the newer design allows different layers (groups) to use different KV head counts. Every assumption in the engine that “pre-allocates VRAM by a uniform num_kv_heads“ must change to per-layer config-table allocation.
    2. K=V binding: some tiers drop the independent V projection and use K directly as V. On this path, V’s memory can be reused from K; but if the engine expands along the standard MHA/GQA template, it will look for a weight that doesn’t exist and error out. Also note that some fused attention kernels don’t allow K and V to point to the same memory (in-place write pollution), so you need an explicit copy or an alias-read-only implementation.
    3. Scaling factor: attention score scaling fixed at 1.0 means the implementation must no longer divide by sqrt(head_dim) by default. On long sequences this small constant is enough to cause a noticeable distribution shift — a classic cause of “it runs but quality collapses.”

    4.3 Memory estimation template

    1. def kv_bytes(layers, group_span, seq_len, kv_heads, head_dim, bytes_per_elem=2):
    2. independent = math.ceil(layers / group_span) # layers that actually hold a cache
    3. per_token = independent * kv_heads * head_dim * 2 # K and V
    4. return per_token * seq_len * bytes_per_elem

    When using it for capacity planning, be sure to itemize layer-wise embedding tables, vision/audio encoder activations, and system reserve separately, otherwise it’s easy to hit an OOM in long context and misdiagnose it as an “engine bug.”

    5. Mechanism 3: Native Multimodal Support

    Unlike the “backbone + bolted-on adapter” approach, these models treat vision and audio as first-class citizens:

    • Vision branch: ViT-style encoding + an explicit pooler compresses patch tokens to fewer tokens, then projects them into the backbone’s embedding space. What really affects experience is dynamic resolution and the tiling strategy: doubling the tile count doubles the image tokens, and first-token latency rises almost linearly.
    • Audio branch: a conv front-end + enhanced Transformer encoder, with the output downsampled by frame rate before injection. On-device, watch its interaction with KV cache sharing — the cache write boundary must be strictly aligned by position before and after multimodal tokens enter, otherwise you get “later text loses earlier text” in interleaved image-text.
    • Dual-band rotary positional encoding: local and global layers use positional-encoding params with different frequency bases. If the engine treats RoPE as a single global config, long-text extrapolation degrades markedly.

    Engineering-wise, make multimodal preprocessing a pluggable, independent service decoupled from the decode core, passing images and intermediate tensors via a standard message queue or object storage, so the encoder’s peak memory doesn’t eat into the decode process’s budget.

    6. MoE Sparse Activation: On-Device Tradeoffs

    The middle tier introduces a 128-expert Top-8 sparse structure — total parameters are large, but per-token activation is low. On the cloud this is a good trade of memory for compute; on-device, be cautious:

    • Expert weights usually need on-demand swap-in/swap-out; frequent I/O eats the sparse gains, so pair it with weight prefetching and an LRU cache;
    • Routing is data-dependent, so the compute graph can’t be statically laid out, which reduces operator-fusion opportunities;
    • During batching, different tokens hit different experts, and in single-request on-device scenarios this is actually harder to saturate compute than a dense model.

    Conclusion: prefer the dense tiers on-device; the sparse tier is better suited to edge servers or the cloud with ample memory and good storage bandwidth.

    7. Adaptation Checklist and Evaluation

    Export & operator alignment

    1. Export each tier separately, don’t share config templates; use a structural comparison script to check layer count, KV head count, sharing groups, and positional-encoding params.
    2. Prioritize numerical consistency for the four “precision-sensitive” items: QKV normalization, attention scaling, K=V aliasing, and dynamic image token count.
    3. Layered quantization: keep attention and embedding projection at 8-bit and above, let FFN go down to 4-bit, and differentiate layer-wise embedding tables by access frequency.

    Evaluation dimensions (fix as a regression set)

    • First-token latency (measured separately at 1K / 8K / 32K context);
    • Decode throughput (tokens/s) and memory peak;
    • Long-context “middle recall” tasks, specifically to expose info loss from KV sharing;
    • Multi-turn interleaved image-text dialogue, to verify cache write boundaries;
    • Score delta before/after quantization on the same business eval set; roll back the quantization tier if it exceeds the acceptable threshold.

    Deployment forms
    On-device is mainly offline inference, with sensitive data never leaving the device. When a larger tier or complex multimodal task is needed, use device-cloud collaboration: the device does lightweight discrimination and truncation, heavy work goes to a cloud-hosted inference service, with logging, monitoring/alerting, and canary model rollout. On platforms like Baidu AI Cloud, these capabilities are typically offered as generic categories — containerized inference services, object storage for model weights, and monitoring/alerting to track latency and error rate — with specific parameters per the official documentation.

    8. Conclusion

    For these “heterogeneous-within-a-series” lightweight models, the most practical evaluation method isn’t leaderboard scores but treating the architecture config as a contract and checking it item by item: the embedding injection path, the KV cache sharing span, the KV head and V projection form, attention scaling, positional-encoding bands, and the multimodal token budget. Keep these six under control and all four tiers can be handled by one maintainable engineering system, instead of hitting the same pit once per tier.