Encoder-Decoder Small Models: Architectural Practices for Multimodality and Long Context
While Decoder-only models dominate the current large language model landscape, the Encoder-Decoder architecture is regaining attention due to its advantages in handling input-dependent tasks like translation, summarization, and image-based question answering. This article explores the architectural practices of Encoder-Decoder small models, detailing core design concepts such as reusing pre-trained decoder weights, sharing token embeddings, merging self-attention and cross-attention layers, and supporting multimodal inputs and long contexts. It also covers engineering implementation essentials, including parameter sizing and the two-step inference workflow.
1. Why the Encoder-Decoder Architecture is Regaining Attention
Current mainstream large language models predominantly adopt the Decoder-only structure. The model generates tokens one by one in an autoregressive manner, where each step can only see the previously generated context. This structure is unified, features straightforward training and inference workflows, and offers excellent scalability.
However, it has notable limitations. Input and output share the same set of parameters and context window, intertwining source comprehension with answer formulation. For tasks heavily reliant on the original input—such as translation, summarization, or image-based question answering—the model must repeatedly retrieve the original text within a long context, leading to increased computational and memory overhead.
The Encoder-Decoder architecture decouples these two processes. The encoder performs bidirectional understanding of the input to generate a set of context representations, while the decoder solely focuses on generating output on demand and reads the encoder’s results via cross-attention. This division of labor is more natural for input understanding and conditional generation tasks, and it is easier to adapt to the resource constraints of edge devices.
2. Core Design Concepts
2.1 Reusing Pre-trained Decoder Weights
Training an Encoder-Decoder model from scratch requires massive computational power. A pragmatic approach is “adaptation”: select a pre-trained decoder model, map its weights to both the encoder and decoder parts, and continue training with a smaller dataset. This reduces training costs while retaining the linguistic knowledge the original model has already learned.
Several issues must be addressed during mapping: whether the number of layers matches, whether the number of attention heads and hidden dimensions align, which parameters can be directly copied, and which need re-initialization. Below is a conceptual pseudo-code snippet illustrating the basic mapping workflow:
def adapt_decoder_to_seq2seq(decoder_ckpt, config):enc_state, dec_state = {}, {}for name, tensor in decoder_ckpt.items():if name.startswith("embed"):enc_state[name] = tensor # Embeddings are copied directly and shared laterdec_state[name] = tensorelif name.startswith("layers."):enc_state[name] = tensor # Encoder retains original layer weightsdec_state[name] = map_to_decoder_layer(tensor, config)return enc_state, dec_state
This code only represents the concept. Actual implementation requires checking tensor shapes layer by layer and conducting a forward pass verification after mapping to ensure there is no obvious degradation.
2.2 Shared Token Embeddings
Both the encoder and decoder need to convert token IDs into vectors. Assuming a vocabulary size of V and a hidden dimension of d, a single embedding matrix contains approximately V×d parameters. If both parts store their own matrices independently, the embedding parameters are duplicated. Sharing the same embedding matrix between the encoder and decoder directly saves one V×d parameter block.
In small-scale models, the embedding matrix accounts for a high proportion of total parameters, making this saving particularly significant. The freed-up memory can be used to increase the number of layers or hidden dimensions, enhancing effective capabilities under the same hardware constraints.
2.3 Merging Self-Attention and Cross-Attention
A standard Encoder-Decoder decoding layer contains two attention sub-layers: self-attention over already generated tokens, followed by cross-attention over the encoder’s output. Each sub-layer comes with its own projection matrices and normalization steps, making the structure cumbersome.
A common simplification approach is to merge them into a unified attention layer. The decoder simultaneously attends to the previously generated context and the encoder’s output within the same layer. For example, the encoder’s output and the decoder-side keys/values can be concatenated for unified attention computation, and masks are used to limit the accessible range for each position. This reduces parameters and intra-layer computational steps, facilitating unified parallelization and caching optimizations in inference frameworks.
The mask design must be strict. Encoder positions should be bidirectionally accessible, while the already generated decoder parts must maintain causality. Otherwise, information leakage will occur during training, causing a discrepancy between training and inference performance.
2.4 Multimodal Input and Long Context
Image inputs are typically split into patches by a visual encoder, mapped into the same vector space as text, and then concatenated with text tokens before being fed into the encoder. This allows the model to process image and text inputs simultaneously using a single encoding and decoding pipeline.
The primary cost of long contexts comes from attention computation. The computational complexity of global attention grows quadratically with sequence length. Alternating local-global attention is a common mitigation strategy: most layers only attend to neighboring tokens within a fixed window, while a few layers perform global attention to aggregate cross-segment information. As a result, the attention computational complexity for most layers becomes approximately linear with sequence length, while still preserving necessary global information exchange.
3. Engineering Implementation Essentials
3.1 Parameter Size and Model Selection
Selection depends primarily on the deployment environment. Weight memory can be estimated by “parameter count multiplied by bytes per parameter.” Taking 1 billion (1B) parameters as an example:
- FP16 (2 bytes/parameter): approx. 2 GB
- INT8 (1 byte/parameter): approx. 1 GB
- INT4 (0.5 bytes/parameter): approx. 0.5 GB
Actual usage must also account for activation values, KV cache, and runtime overhead, so a margin should be reserved. Quantization significantly reduces memory usage but introduces accuracy loss; the quantization scheme should be tested on the target task before deployment.
3.2 Inference Workflow
Inference in an Encoder-Decoder model usually consists of two steps. First, the input is encoded once to obtain the context representations. Then, the decoder autoregressively generates the output. The encoded result remains unchanged throughout the generation process, so it can be cached and reused. The conceptual workflow is as follows:
def encoder_decoder_inference(input_ids, model):# Step 1: Encode the input to get context representations (cached for reuse)encoder_outputs = model.encode(input_ids)# Step 2: Decoder generates output autoregressively using cross-attentiondecoder_input_ids = [BOS_TOKEN]while True:next_token_logits = model.decode(decoder_input_ids, encoder_outputs)next_token = sample(next_token_logits)if next_token == EOS_TOKEN:breakdecoder_input_ids.append(next_token)return decoder_input_ids[1:] # Exclude BOS token
