Transformer Architecture Explained: From Token Embeddings to Multi-Layer Encoders

    This article walks through the internal structure of the Transformer encoder, starting from raw input vectors and ending with context-aware representations. It covers token embeddings, sequence length and padding, positional encoding, the encoder's core components, self-attention and multi-head attention, residual connections and layer normalization, the position-wise feed-forward network, layer-by-layer representations, key hyperparameters, the complete data flow, and practical engineering considerations. Readers will gain a clear, structured understanding of how information moves through each layer of a Transformer encoder.

    Transformer Architecture Explained: From Input Vectors to Contextual Representations

    The Transformer is a class of deep learning architectures built around the attention mechanism. It is widely applied to text understanding, sequence generation, information extraction, machine translation, speech processing, and multimodal tasks. Unlike sequence models that rely on recurrent computation, the Transformer can process input sequences with a high degree of parallelism and establish relationships between different positions in a sequence through self-attention.

    At a high level, a typical Transformer model consists of an encoder, a decoder, or only one of the two. The encoder is responsible for converting an input sequence into vector representations that carry contextual information. The decoder usually generates the target sequence step by step based on the existing input and the encoder output. This article focuses on the internal structure of the encoder, starting from the input data and explaining how information is passed from layer to layer.

    1. Input Sequences and Token Embeddings

    Neural networks cannot directly understand text, punctuation, or words themselves, so text must first be split into discrete tokens. A token can be a complete word, a character, a subword, or another basic unit. For example, after tokenization, a sentence can be represented as:

    1. [token1, token2, token3, ..., tokenn]

    Here, n denotes the length of the current input sequence. To enable the network to process these tokens, the model maps each token to a continuous vector of fixed dimension through an embedding matrix. Assuming the model’s hidden dimension is 512, each token is represented as a 512-dimensional vector:

    1. token1 -> x1 ∈ R^512
    2. token2 -> x2 ∈ R^512
    3. ...
    4. tokenn -> xn ∈ R^512

    Arranging these vectors in their original order yields the input matrix of the encoder:

    1. X ∈ R^(n × 512)

    Each row here corresponds to the token representation at a given position. Note that token embeddings only express the basic semantic information of a token; a standalone embedding usually cannot fully represent context. For instance, the same token appearing in different sentences may carry different meanings. The Transformer dynamically adjusts the representation of each position based on the entire sequence during the subsequent self-attention computation.

    2. Sequence Length and Padding

    Sequence length is an important configuration in the Transformer. The length of actual input text is usually inconsistent, while batch training requires data within the same batch to have a uniform tensor shape, so a maximum length must be set.

    Common approaches include:

    1. Padding short sequences to a uniform length;
    2. Truncating sequences that exceed the maximum length;
    3. Using an attention mask to prevent the model from attending to padding positions;
    4. Setting a reasonable maximum sequence length according to the task.

    For example, if the maximum length in a batch is set to 128, each input can ultimately be represented as:

    1. [batch_size, 128, hidden_size]

    Here, hidden_size is the dimension of the hidden vector, for example 512. The larger the sequence length, the wider the range of context the model can handle, but the computational and memory overhead of self-attention also increases significantly. Therefore, a larger maximum length is not always better; it should be determined based on task requirements, data distribution, and hardware resources.

    3. Positional Encoding: Adding Order Information

    Token embeddings themselves only express “what” a token is, not “where” it is located. If the same set of tokens is arranged in a different order, the model may struggle to distinguish their sequence based on token embeddings alone.

    To address this, the Transformer introduces positional encoding for each sequence position and adds it to the token embedding:

    1. input representation = token embedding + positional encoding

    Let the token embedding be E and the positional encoding be P; then the input actually received by the encoder is:

    1. H0 = E + P

    Positional encoding can be generated by a fixed function or learned through training. Regardless of the approach, the goal is to let the model recognize:

    • Which position in the sequence the current token occupies;
    • The approximate distance between two tokens;
    • The relative or absolute relationship between different positions.

    After adding positional encoding, the encoder’s input contains not only token semantics but also sequence structure information.

    4. Basic Components of the Encoder

    A standard Transformer encoder is typically formed by stacking multiple encoder layers with the same structure. Each layer mainly contains two core submodules:

    1. A multi-head self-attention layer;
    2. A position-wise feed-forward neural network.

    Around each submodule, residual connections and layer normalization are usually added. The overall data flow can be summarized as:

    1. input vector
    2. ↓
    3. multi-head self-attention
    4. ↓
    5. residual connection and layer normalization
    6. ↓
    7. feed-forward neural network
    8. ↓
    9. residual connection and layer normalization
    10. ↓
    11. output to the next encoder layer

    The bottom encoder layer receives the vectors formed by combining token embeddings and positional encoding. Higher encoder layers receive the contextual representations output by the encoder layers below. Therefore, only the bottom layer needs to connect directly to the token embedding module; other encoder layers do not repeat the token mapping.

    5. Self-Attention Mechanism

    Self-attention is the most core mechanism of the Transformer. It allows each position in the sequence to look at other positions and decide which content to focus on based on relevance.

    For the input matrix X, the model generates three sets of vectors through different linear transformations:

    1. Q = XWQ
    2. K = XWK
    3. V = XWV

    where:

    • Q represents the query vector, used to express what information the current token is looking for;
    • K represents the key vector, used to describe what information each position can provide;
    • V represents the value vector, containing the content that actually needs to be aggregated;
    • WQ, WK, WV are trainable parameter matrices.

    Next, the model computes the similarity between the query vectors and the key vectors:

    1. Attention(Q, K, V) =
    2. softmax(QKᵀ / √dk)V

    Here, dk is the dimension of the key vector. Dividing by √dk prevents the dot-product results from becoming too large, which would push the Softmax function into regions with overly extreme gradients and affect training stability.

    After Softmax, each position obtains a set of attention weights. A higher weight indicates that the current token needs to reference the information at the corresponding position more. Finally, the model performs a weighted sum over all value vectors according to these weights to obtain a new contextual representation.

    For example, when processing a pronoun, self-attention may assign a higher weight to a certain noun in the preceding text, helping the model determine what the pronoun specifically refers to. Compared with fixed-window methods, self-attention can directly establish long-distance dependencies.

    6. Multi-Head Attention

    A single attention module may only observe relationships between tokens from one representation space. To capture multiple types of dependencies simultaneously, the Transformer typically uses multi-head attention.

    Specifically, the model divides the hidden vector into multiple smaller subspaces, and each attention head independently performs one self-attention computation:

    1. head_i = Attention(Q_i, K_i, V_i)

    Then the results of the multiple attention heads are concatenated and passed through a linear transformation:

    1. MultiHead(Q, K, V) =
    2. Concat(head_1, ..., head_h)WO

    Different attention heads may learn different relationships, such as:

    • Local collocations between words;
    • The relationship between subject and predicate;
    • Coreference relationships;
    • Modification relationships;
    • Long-distance semantic dependencies;
    • Syntactic structure and semantic topics.

    Note that the number of attention heads, the hidden dimension, and the dimension of each head usually need to satisfy compatibility constraints. For example, the hidden dimension is generally divisible by the number of attention heads. Increasing the number of heads does not necessarily improve performance; it must be chosen in combination with data scale, task complexity, and computational resources.

    7. Residual Connections and Layer Normalization

    Deep networks are prone to difficulties in gradient propagation and unstable training. The Transformer adds a residual connection around each major sublayer, adding the sublayer output to the original input:

    1. Y = X + Sublayer(X)

    The residual connection allows the network to preserve original information and makes it easier for a newly added sublayer to learn “the part that needs correction” rather than constructing a complete representation from scratch.

    Layer normalization is used to stabilize the numerical distribution across different feature dimensions. It usually normalizes over the hidden dimension of a single sample, helping reduce numerical fluctuations during training.

    In practice, residual connections and normalization can be arranged in different orders. Common forms include:

    1. output = LayerNorm(X + Sublayer(X))

    or:

    1. output = X + Sublayer(LayerNorm(X))

    The two structures may differ in training stability and deep-scaling capability, and the actual choice should follow the specific architecture design.

    8. Position-Wise Feed-Forward Network

    After the self-attention computation, the vector at each position is independently passed through a feed-forward network. A typical structure consists of two linear transformations and one nonlinear activation function:

    1. FFN(x) = W2 · Activation(W1 · x + b1) + b2

    The feed-forward network usually first maps the hidden dimension to a higher-dimensional space, then compresses it back to the original dimension. For example:

    1. 512 dims → higher dims → 512 dims

    Self-attention handles information exchange between different positions, while the feed-forward network is mainly responsible for performing more complex nonlinear feature transformations on each position. Although it operates independently on each position, the input has already been fused by self-attention, so the vector at each position actually already contains contextual information.

    This is also the division of labor between the “interaction” and “processing” stages in the encoder:

    • Self-attention: lets different positions communicate with each other;
    • Feed-forward network: performs deep transformations on the fused representation.

    9. Layer-by-Layer Representations in a Multi-Layer Encoder

    A complete encoder is usually formed by stacking multiple encoder layers. Let the input to layer l be Hl-1; after passing through attention and the feed-forward network, this layer produces:

    1. Hl = EncoderLayer(Hl-1)

    The bottom-layer input is:

    1. H0 = TokenEmbedding + PositionEncoding

    Then:

    1. H1 = EncoderLayer(H0)
    2. H2 = EncoderLayer(H1)
    3. ...
    4. HL = EncoderLayer(HL-1)

    As the number of layers increases, the vector representations typically shift gradually from shallow features to more abstract contextual features. Lower layers may focus more on local lexical and syntactic information, while higher layers may contain richer semantic relationships. However, this division is not absolute; the actual representations are affected by the training objective, data scale, and model structure.

    In the end, the encoder outputs a list of vectors with the same length as the input sequence:

    1. HL ∈ R^(n × hidden_size)

    Each position here still corresponds to a position in the original sequence, but its vector is no longer an isolated token embedding; it is a representation that has fused the context of the entire input.

    10. Key Hyperparameters and Their Impact

    The behavior of a Transformer encoder is influenced by several hyperparameters, including:

    1. Hidden Dimension

    The hidden dimension determines how many values are used to describe each position. A larger dimension usually means stronger model expressiveness, but it also increases the number of parameters, memory usage, and computational cost.

    2. Number of Encoder Layers

    The number of layers determines how many times information can be repeatedly processed. Too few layers may limit the model’s ability to express complex relationships, while too many layers may increase training difficulty and inference cost.

    3. Number of Attention Heads

    The number of heads affects how many subspaces the model uses to observe sequence relationships. It must match the hidden dimension and be set reasonably according to the task scale.

    4. Maximum Sequence Length

    The maximum length determines the range of context the model can directly handle. Too short causes information truncation, while too long increases the overhead of attention computation.

    5. Feed-Forward Network Intermediate Dimension

    The intermediate dimension determines the capacity of the nonlinear transformation. It is usually larger than the hidden dimension, but a balance must be struck between effectiveness and resources.

    11. Complete Data Flow Summary

    From text to encoder output, the complete process can be summarized as:

    1. raw text
    2. ↓
    3. tokenization
    4. ↓
    5. token numbering
    6. ↓
    7. token embedding
    8. ↓
    9. add positional encoding
    10. ↓
    11. layer 1 multi-head self-attention
    12. ↓
    13. residual connection and layer normalization
    14. ↓
    15. layer 1 feed-forward network
    16. ↓
    17. residual connection and layer normalization
    18. ↓
    19. repeat through subsequent encoder layers
    20. ↓
    21. obtain context-aware sequence representations

    It can be expressed in pseudocode as:

    1. x = token_embedding(tokens)
    2. x = x + position_encoding(length=len(tokens))
    3. for layer in encoder_layers:
    4. attention_out = multi_head_attention(x, mask=attention_mask)
    5. x = layer_norm(x + attention_out)
    6. ffn_out = feed_forward_network(x)
    7. x = layer_norm(x + ffn_out)
    8. encoder_output = x

    This code is used to illustrate the structural logic; an actual implementation must also account for details such as the batch dimension, padding masks, parameter initialization, training mode, regularization, and device computation.

    12. Practical Engineering Considerations

    In real applications, the following issues also deserve attention:

    1. Handle padding positions properly: Without masking, the model may treat meaningless padding symbols as valid content.
    2. Control sequence length: Overly long sequences significantly increase computational cost; when necessary, truncation, chunking, or hierarchical processing can be used.
    3. Keep dimensions consistent: Residual addition requires the input and sublayer output to have the same shape.
    4. Pay attention to training stability: Normalization placement, learning rate, initialization method, and regularization all affect the training of deep models.
    5. Distinguish training from inference: The training stage usually requires computing the full sequence, while the inference stage may adopt step-by-step processing or cache intermediate results.
    6. Choose the output method based on the task: Classification tasks may use the representation at a specific position, sequence labeling tasks usually use the representations at all positions, and retrieval or matching tasks may require further aggregation.

    Conclusion

    The core idea of the Transformer encoder can be summarized as: first map discrete tokens to vectors, then add positional encoding to supply order information, then achieve global information exchange through multi-head self-attention, and finally refine representations layer by layer with the help of the feed-forward network, residual connections, and layer normalization.

    The bottom encoder layer directly receives the sequence of vectors formed by token embeddings and positional encoding, while subsequent encoder layers receive the output of the previous layer. After multiple layers of transformation, the vector at each position carries richer contextual information. This structure both preserves the correspondence between each position in the sequence and flexibly models long-distance dependencies, making it an important foundational architecture in modern natural language processing and a variety of sequence modeling tasks.