Choosing On-Device Multimodal Encoder-Decoder Small Models: An Engineering Guide

    This article explains why encoder-decoder architectures deserve renewed attention for on-device and multimodal workloads, and how to choose small models in the 270M-to-4B parameter range. It compares encoder-decoder against Decoder-only in terms of attention masking, KV-cache structure, and computational complexity; walks through adapting a pretrained Decoder-only model into an encoder-decoder via weight mapping and continued training; details four key design techniques that raise capability density in small models (shared word embeddings, merged self/cross attention, vision encoding with local-global alternating attention, and long-context plus multilingual coverage); and closes with three selection routes, a rough on-device memory estimation, and a practical deployment checklist. Readers will learn when an encoder-decoder beats a Decoder-only model, how to budget memory and time-to-first-token, and which factors matter more than raw parameter count.

    1. Introduction: Why On-Device Is Revisiting Encoder-Decoder

    Over the past few years, the Decoder-only architecture has become the mainstream choice for large language models, thanks to a unified training objective, simple inference implementation, and easy scaling with more data and compute. But in on-device deployment and multimodal understanding scenarios, Decoder-only is not a universal answer. When the input is long and the output is short, or when the input contains large amounts of images, documents, or call transcripts, a traditional causal decoder introduces several clear pressures:

    1. Input understanding is one-directional: each token can only see its left context, so critical information appearing later cannot influence the representation of earlier tokens in time.
    2. Input and output share parameters and attention: understanding the input and generating the output are done by the same mechanism, so a long input directly increases autoregressive cache pressure.
    3. High time-to-first-token on long inputs: a document or conversation of tens of thousands of tokens must be prefilled token by token before generation, making first-token response slow and memory usage high.
    4. Multimodal token bloat: a single high-resolution image may be encoded into hundreds or thousands of visual tokens that mix with text in a causal sequence, and early visual information is easily diluted.

    The encoder-decoder structure splits “understanding the input” and “generating the output” into two stages: the encoder reads text, images, and other inputs in parallel with bidirectional attention and forms a memory that is visible to the decoder; the decoder then autoregressively generates the result based only on that memory. This structure has advantages in on-device tasks such as long input, short output, and multimodal understanding.

    Note that 270M to 4B is only a parameter-scale range. Whether a device can support a model depends not just on parameter count but also on quantization method, device memory, runtime overhead, number of visual tokens, and caching strategy. Actual selection should be validated on real devices.

    2. Structural Principles: Key Differences from Decoder-Only

    2.1 A Formal Comparison of the Two Structures

    Let the input sequence be x = (x₁, …, xₙ) and the target output be y = (y₁, …, yₘ).

    1. # Decoder-only: input and output are concatenated into one sequence with causal masking throughout
    2. H = DecoderOnly([x; y]) # each position can only see left-side tokens
    3. # Encoder-Decoder: understanding and generation are separated
    4. M = Encoder(x) # bidirectional attention, every token sees the full input
    5. H = Decoder(y, M) # causal self-attention on the decoding side + cross-attention over M

    The core difference lies in the attention mask. Inside the encoder, every position can see the complete input, so long-range dependencies can be modeled in a single forward pass; the decoder stays causal and is only responsible for generating output. Although a causal model can also read the entire input when generating step t, later inputs cannot retroactively update the representations of earlier tokens, so the encoder lets every input token obtain global context all at once.

    2.2 Different Cache Composition During Decoding

    During inference, both structures need caching, but what they cache differs:

    • Decoder-only: must cache the self-attention K/V of every layer on the decoding side, and the cache grows with “input length + generated length.”
    • Encoder-decoder: the cache splits into two parts.
      • Encoder memory output per layer: its length is fixed at N, independent of generation progress, and in principle it can be reused across requests, but session isolation and access control must be handled properly.
      • Decoder self-attention K/V: covers only generated tokens, so the longer the generation, the larger the cache.

    For tasks where “input is far longer than output,” such as long-document extraction, long-document summarization, and long-context question answering, the cache structure of an encoder-decoder more easily saves memory and bandwidth.

    2.3 Computational Complexity

    Taking one layer as an example, with d as the model dimension, n as the input length, and m as the generated length:

    • The matrix operations of self-attention are on the order of O(n²·d).
    • The computation of cross-attention is roughly O(n·m·d) and grows linearly with the number of decoding steps.

    When the input is long and the output is short, the encoder needs only one bidirectional forward pass; the decoder’s self-attention relates only to generated content, so the per-step decoding cost is usually lower than that of a Decoder-only model. But this “lower” refers specifically to the per-step decoding view, and the total cost of the encoder’s prefill cannot be ignored. Actual end-to-end latency must account for both the encoder’s first-pass forward cost and the decoder’s subsequent generation cost.

    When the input is short and the output is long, such as in multi-turn conversations or complex reasoning chains, the decoding cost of the two structures is fairly close. In this case, an encoder-decoder must additionally solve how multi-turn history enters the encoder memory: it can re-encode the full history, or perform incremental updates or summary compression. On-device selection should be validated against actual latency, memory, and task shape.

    3. Training Route: Adapted from a Mature Decoder Model

    Training a long-context multimodal model from scratch usually requires massive data and large-scale compute. A more common route for modern encoder-decoder small models is to take a Decoder-only model already trained on a large number of tokens as a seed, map its weights into the new encoder-decoder structure, and then run continued training. This lowers training cost and inherits the original model’s language understanding, coding, and multilingual abilities.

    3.1 Key Points of Weight Mapping

    Weight mapping usually follows a few principles:

    • Word embedding reuse: the encoder and decoder share the same word embedding, reducing parameter count.
    • Encoder layer reuse: encoder layers can be copied from some decoder layers, with the causal mask changed to a bidirectional mask.
    • Decoder layer retention and extension: keep the original decoder layers, then add cross-attention to the encoder memory.
    • Cross-attention initialization: a common approach is to initialize cross-attention from the self-attention K/V projections, sometimes including the output projection as well, so the model starts learning from familiar transforms and training is more stable.

    The following is an illustrative snippet. In real engineering you must replace the specific module names and handle details such as positional encoding, grouped-query attention, and tensor-parallel sharding.

    1. def adapt_to_enc_dec(seed_sd, cfg):
    2. """Adapt a pure-decoder state_dict into an encoder-decoder structure (illustrative).
    3. Parameters:
    4. seed_sd: dict, the state_dict of a pure-decoder model.
    5. cfg: a config object containing at least enc_layers, dec_layers, and n_layers.
    6. Note:
    7. This is illustrative code and does not include real module names,
    8. positional encoding, parallel sharding, or other engineering details.
    9. """
    10. enc_sd, dec_sd = {}, {}
    11. # Both sides share one word embedding, so keep only a single copy of the weights
    12. enc_sd["embed_tokens.weight"] = seed_sd["embed_tokens.weight"]
    13. dec_sd["embed_tokens.weight"] = seed_sd["embed_tokens.weight"]
    14. # Encoder: reuse some seed layers, switch the attention mask from causal to bidirectional
    15. for i in range(cfg.enc_layers):
    16. src = f"layers.{i % cfg.n_layers}"
    17. for key in ("attn_q", "attn_k", "attn_v", "attn_o", "mlp", "norm"):
    18. enc_sd[f"layers.{i}.{key}"] = seed_sd[f"{src}.{key}"]
    19. enc_sd[f"layers.{i}.causal"] = False # bidirectional attention
    20. # Decoder: keep the original layers, and add cross-attention to each layer
    21. for i in range(cfg.dec_layers):
    22. for key in ("attn_q", "attn_k", "attn_v", "attn_o", "mlp", "norm"):
    23. dec_sd[f"layers.{i}.{key}"] = seed_sd[f"layers.{i}.{key}"]
    24. # Initialize cross-attention from self-attention K/V and the output projection, as a warm start
    25. dec_sd[f"layers.{i}.xa_k"] = seed_sd[f"layers.{i}.attn_k"]
    26. dec_sd[f"layers.{i}.xa_v"] = seed_sd[f"layers.{i}.attn_v"]
    27. dec_sd[f"layers.{i}.xa_o"] = seed_sd[f"layers.{i}.attn_o"]
    28. # The output layer is tied to the word embedding and not saved separately
    29. dec_sd["lm_head.weight"] = seed_sd["embed_tokens.weight"]
    30. return enc_sd, dec_sd

    Here, the encoder is a bidirectional copy of layers 0 through enc_layers-1; the decoder usually keeps all layers of the seed model, so dec_layers should equal n_layers. The deeper the encoder, the stronger the input representation, but the greater the parameter count and prefill overhead.

    3.2 Training Objective and Stage Division

    The training objective remains standard sequence-to-sequence conditional language modeling:

    1. L = -Σ log P(y_t | y_<t, x)

    The loss is computed mainly on the decoding side. Common stages include:

    1. Continued training stage: with a smaller learning rate, continue training on general text, code, multilingual, and interleaved image-text data, so the encoder learns bidirectional representations and the decoder learns to exploit cross-attention. Empirically, a data mix dominated by longer inputs may be more favorable for stable convergence of cross-attention, but in the absence of public ablation studies this should be treated as an empirical hypothesis and validated independently.
    2. Instruction fine-tuning stage: some small-model routes use only smaller-scale supervised fine-tuning without introducing reinforcement learning. Whether this approach is more worthwhile depends on data quality, task coverage, and evaluation goals. When data quality is high and coverage is good, “few but high-quality” instruction fine-tuning is worth trying first, but small-scale A/B testing should still be used to validate it.

    4. Four Key Designs: Raising Capability Density in Small Models

    4.1 Shared Word Embedding: Fewer Parameters and a Unified Semantic Space

    When the encoder and decoder share word embeddings instead of each maintaining their own, the main benefits are threefold:

    • Lower parameter usage: the vocabulary is usually large, and the embedding matrix has size V×d, a considerable share of total parameters. After sharing, only one copy is kept.
    • Unified semantic space: the tokens the encoder reads and the tokens the decoder outputs live in the same vector space, so cross-attention aligns more easily.
    • Greater benefit at small sizes: for a 270M-class model, embeddings may occupy a large share, so sharing frees more parameters for the attention, feed-forward, or vision encoding modules.

    Shared word embeddings also come at a cost. The token distributions on the input side and the output side are not exactly the same; the encoder needs to handle extra special tokens such as image boundaries, modality markers, and separators; and the output side may need independent control. If multimodal tokens enter the word embedding, the scale alignment between visual tokens and text tokens must also be considered. At the 4B level, sharing is still effective, but relative to a 270M model its share of the benefit declines.

    4.2 Merging Self-Attention and Cross-Attention: Reducing Module Redundancy

    Within a decoder layer, self-attention models generated content while cross-attention reads the encoder memory. To lower parameter count and implementation complexity for small models, some engineering approaches try to merge or reuse the projections, normalization, or gating of the two attention types. For example:

    • sharing some of the Q/K/V projections;
    • using a unified attention module and distinguishing self-attention from cross-attention via masking;
    • adding a gate to the cross-attention output to control how much memory contributes to generation.

    This kind of design reduces parameters and inference branches but increases training complexity. If cross-attention capacity is insufficient, it may affect long-input understanding or multimodal alignment. When landing on-device, focus on validating the accuracy loss after sharing and whether every decoder layer needs cross-attention.

    4.3 Vision Encoding and Local-Global Alternating Attention: Controlling Visual-Token Cost

    The core challenge for multimodal on-device models is the number of visual tokens. After a high-resolution image is split into patches, it produces a large number of patch tokens, and if they all enter the encoder, memory and latency increase significantly. Common strategies include:

    • Lightweight vision encoder: use a smaller vision backbone or share the first few layers to reduce on-device computation.
    • Multi-resolution input: a low-resolution global view plus high-resolution local patches, balancing global semantics and fine detail.
    • Visual token compression: reduce token count via pooling, convolution, token merging, and similar methods.
    • Local-global alternating attention: local window attention focuses on image regions and text neighbors, while global attention handles cross-modal alignment; alternating between them lowers computation.

    For on-device models, the visual-token budget is critical. If one image produces a thousand tokens, memory and prefill overhead rise noticeably even if the text encoder is not large. So a multimodal small model must optimize not only parameter count but also visual-token count and time-to-first-token.

    4.4 Long Context and Multilingual Ability: On-Device Must Balance Coverage and Cost

    Encoder-decoder small models have a natural advantage in long-context tasks: the encoder can read the long input all at once, and the decoder only needs to generate a short output. But to fit on-device constraints, this must be combined with strategies such as positional-encoding extrapolation, chunked encoding, sliding windows, and memory compression. For multilingual support, shared word embeddings and continued training can inherit multilingual and coding abilities, but on-device hardware must also consider vocabulary size, quantization error, and token efficiency for low-resource languages.

    5. Selection and Engineering Implementation Advice

    5.1 How to Choose Among the Three Routes?

    Route Suitable scenarios On-device advantage Main risk
    Decoder-only Short input, long output, multi-turn dialogue, complex reasoning chains Simple implementation, mature ecosystem High KV-cache pressure on long inputs
    Encoder-decoder Long input, short output, document understanding, summarization, long-document QA Fixed input memory, decoding cache grows only with generation Extra design needed for multi-turn history in memory
    Multimodal encoder + Decoder-only Mixed image and text, open-ended generation, visual question answering Flexible modality extension Visual tokens enter a long sequence, cache and latency may be high

    If the task centers on long-document understanding, short-answer extraction, or table question answering, an encoder-decoder small model is more worth evaluating first. If the task centers on multi-turn dialogue and long-answer generation, a Decoder-only model is usually more direct. If multimodality is core but output is short and there are many input images, an encoder-decoder or a multimodal structure with memory compression can also be considered first.

    5.2 On-Device Memory Estimation

    Total on-device memory can be roughly broken down as:

    1. Total memory ≈ model weights + encoder memory + decoder KV cache + runtime overhead

    Where:

    • Model weights ≈ parameter count × bytes per parameter. INT8 is roughly 1GB/1B, INT4 is roughly 0.5GB/1B, plus runtime and fragmentation on top.
    • Encoder memory depends on input length, number of encoder layers, and hidden dimension.
    • Decoder KV cache depends on number of generated tokens, number of decoding layers, and KV precision.
    • Multimodal scenarios must additionally account for the vision encoder and visual tokens.

    For example, a 270M model at INT8 has weights of about 0.27GB; with runtime and cache added, it is usually more suited to mid-range devices, but real-device validation is still needed. A 4B model at INT4 has weights on the order of 2GB; adding cache and system usage, it usually requires a higher-memory device. If long images produce thousands of visual tokens, memory overhead may rise significantly.

    5.3 Deployment Checklist

    1. Measure task shape first: the ratio of input length to output length affects the on-device experience more than parameter scale does.
    2. Quantize end to end: quantize not only the language model but also evaluate the quantization error of the vision encoder and the embedding.
    3. Control visual tokens: apply multi-resolution, pooling, or compression to images so visual tokens do not eat up on-device memory.
    4. Design multi-turn history: when using an encoder-decoder for multi-turn dialogue, be explicit about whether you re-encode, do incremental updates, or use summary compression.
    5. Isolate the cache: reusing encoder memory across requests must include session isolation to avoid data leakage.
    6. Watch time-to-first-token: in long-input tasks, encoder prefill may dominate latency, so do not look only at decoding speed.
    7. Build an evaluation set: cover short input, long input, multimodal, multi-turn, and long output, to avoid misjudging on a single metric.

    Overall, encoder-decoder small models are not meant to replace Decoder-only, but to offer another more suitable path in on-device multimodal, long-input, short-output scenarios. Selection should revolve around input-output ratio, multi-turn needs, the visual-token budget, and real-device memory, rather than focusing only on parameter scale.