Understanding the Transformer Architecture: Core Principles of Encoder and Decoder

    This article provides a technical breakdown of the Transformer architecture, covering the overall encoder-decoder design, the internal structure of each layer, the role of self-attention and feed-forward networks, and the flow of data from word embeddings through the network. It also highlights key engineering considerations for deploying Transformer-based models, including sequence length trade-offs, layer count, and training stability.

    Introduction: Why Understanding the Transformer Matters

    Since the publication of the 2017 paper Attention Is All You Need, the Transformer architecture has gradually replaced recurrent neural networks (RNNs) and long short-term memory networks (LSTMs) as the dominant foundation for natural language processing (NLP). Whether in machine translation, text summarization, or the construction of large language models, the underlying design ideas largely originate from the Transformer. Understanding the internal mechanisms of this architecture is essential for developers and researchers working on algorithm development, model tuning, or engineering deployment.

    This article treats the Transformer as a modular system, examining it from the outside in and from the macro to the micro level. It explains the organization of the encoder and decoder stacks, the core computational logic, and the path data follows as it flows through the network.

    1. Overall Architecture: Input–Output Relationships from a Black-Box Perspective

    At the highest level, the Transformer can be viewed as a sequence-to-sequence system: it takes a text sequence as input and produces another text sequence as output. For example, in machine translation, the model receives a sentence in the source language and generates the corresponding translation in the target language. This “black-box” view helps beginners build an overall understanding before diving into internal details.

    Peering inside the black box reveals two primary components:

    • Encoder Stack: Extracts features and produces semantic representations of the input sequence.
    • Decoder Stack: Generates the output sequence step by step, guided by the encoded representations.

    The two stacks are connected through a specific attention mechanism that allows the decoder, when generating each output token, to reference the most relevant parts of the input sequence.

    2. Stacked Structure of Encoder and Decoder

    2.1 Multi-Layer Design Philosophy

    The original paper stacked six encoder layers and six decoder layers, but this number is not a fixed rule—it is a tunable hyperparameter. More layers theoretically increase the model’s expressive capacity, but they also raise computational cost and training difficulty. In practice, engineers must balance layer count against task complexity, data size, and hardware resources.

    Two important notes:

    • The encoder layers have identical structure but do not share weight parameters. Each layer learns a different level of feature abstraction, ranging from lexical and syntactic information in lower layers to higher-level semantic relationships.
    • The decoder stack follows the same principle, with layer count typically matching the encoder, though weights remain independent across layers.

    2.2 Inside a Single Encoder Layer

    Each encoder unit can be divided into two sublayers:

    1. Self-Attention Layer: When encoding a given token, this layer weighs the relevance of that token with all other tokens in the sequence, producing a context-aware representation.
    2. Feed-Forward Neural Network: Applies a non-linear transformation to the self-attention output, further enhancing the feature representation.

    Both sublayers are typically wrapped with a residual connection and layer normalization to mitigate the vanishing gradient problem in deep networks—a common best practice in modern deep learning architectures.

    2.3 The Decoder’s Additional Attention Layer

    The decoder inherits the two-sublayer structure of the encoder but inserts an extra encoder-decoder attention layer between the self-attention layer and the feed-forward network. This layer functions similarly to the attention mechanism in traditional sequence-to-sequence (Seq2Seq) models, enabling the decoder to dynamically focus on relevant portions of the input sequence at each generation step, rather than relying solely on a fixed-length context vector.

    This design overcomes the information-compression limitation of early Seq2Seq models and allows the model to capture long-range dependencies more accurately.

    3. From Words to Vectors: Embeddings and Tensor Flow

    3.1 The Role of Word Embeddings

    Before entering the encoder, each input word is converted into a fixed-dimensional vector using an embedding algorithm. In the original paper, the embedding dimension was set to 512—another tunable hyperparameter that can be adjusted based on model size and task requirements.

    Embedding occurs only at the bottom encoder layer. Specifically:

    • The lowest encoder layer takes the word embedding vectors as input.
    • All subsequent encoder layers receive the output vectors from the layer directly below them.

    3.2 Determining the Length of the Vector List

    All encoder layers accept a list of fixed-dimensional vectors, where the list length is typically set to the maximum sentence length in the training data (i.e., the sequence length limit). This is an engineering hyperparameter that requires careful trade-off: too short may lose information for long sentences, while too long adds unnecessary computation.

    3.3 Data Flow Inside an Encoder Layer

    For a single encoder layer, the processing pipeline can be summarized as:

    1. Input vector list → Self-attention layer → Feed-forward network → Output vector list → Next encoder layer

    Notably, self-attention introduces dependencies between words (the encoding of each token depends on all other tokens), while the feed-forward network operates independently on each position. This independence enables high parallelization in the feed-forward layer, giving the Transformer a significant training efficiency advantage over RNN-based models.

    4. Self-Attention Mechanism: The Core Innovation

    The self-attention mechanism is the most groundbreaking design in the entire Transformer architecture. Its core idea is: when encoding a word, the model not only considers the word’s own vector representation but also computes attention weights for all other words in the sequence, then uses those weights to combine information in a weighted fashion.

    The immediate benefits include:

    • Capturing long-range dependencies: Self-attention can directly relate any two words regardless of their distance in the sequence, in contrast to RNNs, where information tends to decay as distance increases.
    • Enabling parallel computation: Unlike the recursive step-by-step computation of RNNs, self-attention processes the entire sequence simultaneously, greatly improving training speed.
    • Enhancing interpretability: The distribution of attention weights reveals which parts of the input the model focuses on when processing a particular token, providing a useful basis for model analysis and visualization.

    5. Key Engineering Considerations in Practice

    When deploying Transformer-based models in real-world applications, developers typically focus on the following aspects:

    1. Balancing sequence length and computational resources: Self-attention has O(n²) complexity with respect to sequence length. For long-text tasks, it is important to choose an appropriate truncation strategy or optimization approach based on available hardware.
    2. Weighing layer count and model capacity: Adding layers increases expressive capability but also raises training cost and inference latency. The decision should be based on task difficulty and deployment constraints.
    3. Choosing vector dimensions: Embedding dimensionality directly affects model representation capacity and parameter count. It should be tuned in accordance with data volume and precision requirements.
    4. Ensuring training stability: Residual connections and layer normalization are crucial for stabilizing deep network training, and they are indispensable engineering details in practice.

    In enterprise-level AI deployments, such models are often launched on container platforms with elastic scaling, and monitoring and alerting systems are used to ensure stable inference services. Cloud providers like Baidu AI Cloud offer general-purpose compute and storage infrastructure to support efficient model training and deployment workflows.

    Conclusion

    The Transformer architecture, through its stacked encoder-decoder design and the synergistic operation of self-attention and feed-forward networks, establishes an efficient sequence-modeling framework with strong expressive power. Understanding the flow of vectors and the logic of attention computation not only helps in mastering this classic architecture but also provides a solid theoretical foundation for exploring the many Transformer-based variants that have emerged since.