Deep Dive into the Transformer Architecture: From Attention to Training and Inference

    This article provides a comprehensive breakdown of the Transformer architecture, exploring its core components from input representation to training and inference workflows. It covers the mechanics of self-attention, multi-head attention, positional encoding, and the roles of the encoder and decoder. Additionally, it highlights engineering optimization strategies for handling computational complexity and includes a practical checklist for implementing and debugging Transformer models.

    1. Understanding the Transformer: The Problem It Solves

    When processing text, a model must understand not only the meaning of individual words but also the relationships between them. For example, in the sentence “The engineer fixed the bug in the service because it affected order processing,” the word “it” requires contextual understanding to determine its referent.

    Traditional recurrent sequence models update their states position by position, where the computation of a later position depends on the previous one. While this structure naturally embodies sequence, it limits the parallelization of computations within the sequence. Long-distance information must pass through multiple state transitions, making it more difficult to learn long-range dependencies.

    The core idea of the Transformer is to allow each position to directly access information from other positions via the attention mechanism. Within the permitted access range, a word can establish a connection with a distant word without step-by-step transmission.

    It is important to note that “not relying on recurrent structures” does not mean “all processes can be fully parallelized.” During training, computations across multiple positions can typically be parallelized; however, during autoregressive generation, the next word depends on the already generated content, meaning the generation steps remain sequential.

    2. Overall Architecture: From Input to Output Sequences

    The classic Transformer adopts an encoder-decoder structure, suitable for sequence-to-sequence tasks like translation. The overall workflow can be represented as:

    Input sequence → Token representation & positional information → Stacked Encoders → Contextual representation

    Generated target sequence → Token representation & positional information → Stacked Decoders → Vocabulary prediction

    The encoder is responsible for understanding the input. Each layer typically contains a multi-head self-attention mechanism and a feed-forward network, utilizing residual connections and layer normalization to maintain information flow.

    The decoder is responsible for generating the output. Each layer typically contains three types of sub-layers:

    1. Masked self-attention: Reads the already generated target content.
    2. Cross-attention: Reads input information from the encoder’s output.
    3. Feed-forward network: Further transforms the features of each position.

    In practical applications, encoder-only and decoder-only architectures also exist. The former is suited for tasks requiring a deep understanding of the input, while the latter is commonly used for autoregressive generation. Both retain the core design of attention and feed-forward networks, but it should be noted that not all components of the classic encoder-decoder structure are mandatory.

    3. Input Representation: How Models Receive Text

    1. Tokenization and Embeddings

    Raw text must first be converted into a sequence of tokens. Tokens can be characters, words, or subword fragments, depending on the vocabulary design and task requirements.

    Each token corresponds to an integer ID, which is then mapped to a continuous vector via an embedding matrix. If the sequence length is n and the model dimension is d_model, ignoring the batch dimension, the input representation can be written as:

    X ∈ R^(n×d_model)

    These vectors are not manually defined semantic labels but parameters continuously adjusted during training. After sufficient training, the model can learn task-relevant semantic features in the vector space.

    2. Why Positional Information is Necessary

    Pure self-attention has no built-in concept of order. If only token vectors are provided without positional information, the model struggles to accurately distinguish semantic differences caused by word order changes.

    The classic approach uses sinusoidal and cosine positional encodings:

    PE(pos, 2i) = sin(pos / 10000^(2i/d_model))

    PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))

    Here, pos is the position index, and i corresponds to the frequency index of different dimensions. The positional encoding is added to the token embedding so that the input carries both content and positional information.

    Other common approaches include learnable positional embeddings, relative positional representations, and methods that inject positional relationships through rotational transformations (e.g., RoPE). Different methods perform differently regarding length variation and distance modeling, but simply using a particular positional encoding does not guarantee that the model can reliably handle inputs significantly longer than its training length.

    4. Self-Attention: Selecting Relevant Information for Each Position

    1. What are Queries, Keys, and Values?

    Self-attention first performs three sets of linear mappings on the same input X:

    Q = XW_Q
    K = XW_K
    V = XW_V

    Q stands for Query, K for Key, and V for Value.

    You can think of the Query as “what information the current position is looking for,” the Key as “the features each position uses for matching,” and the Value as “the actual information aggregated after matching.” This is an intuitive analogy; in essence, all three are learnable vector representations.

    For each query, the model calculates matching scores between it and all accessible keys, then aggregates the value vectors based on these scores.

    2. Scaled Dot-Product Attention

    The standard computation is:

    Attention(Q, K, V) = softmax(QKᵀ / √d_k + M)V

    Here, d_k is the dimension of the query and key in a single attention head, and M is the mask.

    The computation can be broken down into four steps:

    • QKᵀ: Obtains the matching scores between query positions and key positions.
    • Divide by √d_k: Controls the score scale, reducing the risk of the softmax distribution becoming too sharp due to large dot products in high dimensions.
    • Add mask and apply softmax: Generates weights along the key position dimension.
    • Multiply by V: Obtains the weighted information representation for each position.

    After softmax, the sum of weights in each row is 1. At this stage, the output can be understood as a weighted combination of the value vectors. However, attention weights are not strictly causal explanations; you cannot simply assume that “the word with the highest weight is the sole reason for the prediction.”

    3. Tensor Dimension Checks

    Assuming the shapes of Q and K are both n×d_k, and the shape of V is n×d_v:

    • The shape of QKᵀ is n×n.
    • The shape of the attention weights is n×n.
    • The shape of the final output is n×d_v.

    These dimension relationships are critical for troubleshooting implementation issues. For cross-attention, the query length and key-value length can differ, meaning the weight matrix may not be a square matrix.

    4. Distinguishing Between Two Types of Masks

    Padding masks are used to mask padded positions, preventing the model from reading placeholder tokens with no actual content.

    Causal masks are used to prevent the current position from accessing future positions. In autoregressive training, even if the complete target text exists, future content must be masked; otherwise, it causes information leakage, leading to training results that cannot correspond to the actual generation process.

    Typically, allowed positions add 0, while disallowed positions add negative infinity, making their weights 0 after softmax. During implementation, pay special attention to the broadcast dimensions of the mask and avoid situations where all positions in a query row are masked, which can cause numerical anomalies.

    5. Multi-Head Attention: Learning Different Relationships in Parallel

    A single attention head can only compute relationships within one projection space. Multi-head attention uses multiple independent projections, allowing the model to model associations in different representation subspaces simultaneously:

    head_i = Attention(XW_Q_i, XW_K_i, XW_V_i)

    MultiHead(X) = Concat(head_1, …, head_h)W_O

    The outputs of each head are first concatenated and then mapped back to the model dimension through an output matrix W_O.

    In common implementations, if the number of heads is h, the dimension of each head is set to d_model/h, so d_model must be divisible by h.

    Different heads might learn local relationships, long-range relationships, or other features, but this division of labor emerges from training; it is not manually specified, nor is it guaranteed that every head has a clearly interpretable role.

    Increasing the number of heads does not necessarily improve performance. With a fixed total model dimension, increasing the head count reduces the dimension of each head, requiring a comprehensive consideration of representational capacity, task characteristics, and computational overhead.

    6. Feed-Forward Networks, Residual Connections, and Layer Normalization

    1. Feed-Forward Networks for Feature Transformation

    Attention primarily facilitates information exchange between different positions, while the feed-forward network (FFN) performs non-linear transformations on the representation of each position:

    FFN(x) = σ(xW_1 + b_1)W_2 + b_2

    Here, σ is a non-linear activation function. A common structure first expands the intermediate dimension and then projects it back to the model dimension to enhance feature representation capabilities.

    All positions within the same layer share the FFN parameters, but each position is computed independently. Therefore, the FFN itself does not directly exchange positional information.

    2. Residual Connections Aid Information and Gradient Flow

    Residual connections add the sublayer input to the sublayer output:

    y = x + Sublayer(x)

    This preserves the existing representation while allowing the sublayer to learn necessary adjustments. For deep networks, the residual path also helps mitigate optimization difficulties.

    The two tensors being added must have the same shape, so the attention output and FFN output are typically mapped back to the d_model dimension.

    3. Layer Normalization Stabilizes Training

    Layer normalization typically computes statistics along the feature dimension of a single position, normalizes the features, and uses learnable parameters to adjust the output.

    Normalization can be placed after the sublayer (Post-LN):

    y = LayerNorm(x + Sublayer(x))

    Or before the sublayer (Pre-LN):

    y = x + Sublayer(LayerNorm(x))

    Both approaches affect gradient flow and training behavior. Pre-LN tends to achieve more stable training in many deep models, but it shouldn’t be assumed that different arrangements are equivalent under all conditions.

    7. Encoder-Decoder Collaboration

    Encoder self-attention typically allows reading all valid input positions, so each position’s representation can incorporate the entire input context. After stacking multiple layers, the output is no longer just the initial token embeddings but representations containing contextual relationships.

    The decoder first uses causal self-attention to understand the generated content on the target side, and then uses cross-attention to read the encoder’s output.

    The source relationships in cross-attention are:

    • Q comes from the decoder’s current hidden state.
    • K comes from the projection of the encoder’s output.
    • V also comes from the projection of the encoder’s output.

    For example, when generating a specific position in the target sequence, the decoder can assign higher weights to relevant positions in the input sequence based on the current generation state, thereby extracting the required information.

    Finally, the decoder output is passed through a linear mapping to obtain scores for each token in the vocabulary, which are then converted into a probability distribution for the next token.

    8. Training and Inference: Same Network, Different Workflows

    1. Right-Shifted Target Sequences in Training

    For autoregressive tasks, the training objective can be written as:

    P(y₁, …, y_T | x) = ∏ P(y_t | y_<t, x)

    During training, the decoder receives the start token and the right-shifted true target sequence, predicting the correct token at the current position. Due to the causal mask, each position can only read previous target content.

    This maintains the conditional dependency of the generation task while allowing multiple positions to be predicted in a single forward pass.

    A common loss function is cross-entropy. When computing the loss, padding positions should be ignored, and it should be clear whether the loss is averaged by valid tokens or by samples; otherwise, batches of different lengths may produce inconsistent loss scales.

    2. Step-by-Step Generation During Inference

    Inference starts from the initial content, predicting a new token each time, adding it to the context, and continuing to the next step until an end condition is met or a length limit is reached.

    Token selection can use the highest probability candidate or sample according to an adjusted distribution. The former is more deterministic but does not guarantee finding the globally optimal sequence; the latter adds diversity but requires controlling randomness and output constraints.

    3. KV Cache to Reduce Redundant Computation

    In standard causal self-attention, the keys and values of already generated positions can be cached. When generating the next token, only the relevant representations of the newly added position are computed, and the historical cache is read, avoiding the need to recompute the entire prefix.

    Caching does not eliminate the attention computation between the new query and historical positions, and its memory footprint grows with sequence length, number of layers, and concurrent requests. Therefore, inference optimization must consider both computational load and cache capacity.

    9. Complexity and Engineering Optimization Focuses

    For standard global self-attention with length n, the matching score matrix contains n² elements. The core computational load of attention for a single head is typically O(n²d_k), and directly storing the full attention weights also requires quadratically growing space.

    This means that as the input length increases, computational and memory pressure can rise rapidly.

    In engineering, optimization can be approached from the following directions:

    • Reduce invalid padding: Group samples of similar lengths in the same batch to avoid spending computation on placeholder positions.
    • Optimize computation organization: Use techniques like tiling and operator fusion to reduce intermediate tensor writes and memory read/writes.
    • Control numerical precision: When using lower precision to improve throughput, still pay attention to the stability of normalization, reduction computations, and gradients.
    • Adjust attention scope: Local or sparse connections can reduce some long-sequence overhead, but they alter the information transmission path.
    • Manage inference cache: Plan capacity based on context length and concurrency requirements to prevent the cache from becoming a service bottleneck.

    It is important to distinguish between computational optimization and structural modification. Some optimizations only change the execution method while keeping the mathematical result identical; approaches like local attention change the accessible context range and should not be unconditionally treated as equivalent replacements for global attention.

    Furthermore, actual latency may be determined by the feed-forward network, parameter reads, data loading, or communication, so the bottleneck of the entire system cannot be judged solely by the complexity formula of attention.

    10. Implementation Checklist and Core Summary

    When implementing or reviewing Transformer code, prioritize checking the following:

    1. Whether the input contains reasonable positional information.
    2. Whether the dimensions are correct after multi-head splitting, transposing, and concatenating.
    3. Whether softmax is computed along the key position dimension.
    4. Whether padding masks and causal masks cover the correct positions.
    5. Whether the tensor shapes match for residual addition.
    6. Whether the target sequence is correctly right-shifted and the loss ignores padding positions.
    7. Whether cached generation and uncached generation yield consistent predictions under the same context.
    8. Whether training throughput, generation latency, and memory usage are measured separately on the target hardware.

    The Transformer can be summarized as a structure with a clear division of labor: embeddings and positional representations describe the input, self-attention establishes connections between positions, the multi-head mechanism expands how relationships are modeled, the feed-forward network performs non-linear feature transformations, residual connections and normalization support deep training, and masks determine the boundaries of information access.

    Truly understanding this architecture is not just about memorizing formulas, but being able to explain what information is read and what tensors are output at each step, and why training and inference adopt different workflows. By following the main thread of “representation — interaction — transformation — prediction,” you can gradually translate abstract principles into verifiable, debuggable engineering capabilities.