Transformer Architecture Explained: From Attention Mechanisms to Model Training
This article explains how the Transformer architecture processes sequences, covering token embeddings, positional encoding, self-attention, multi-head attention, encoder and decoder data flow, training and inference, computational complexity, and practical engineering considerations. It also summarizes the architecture’s main strengths and limitations.
1. What Problem Does the Transformer Solve?
The Transformer is a neural network architecture built around attention mechanisms. It was originally designed mainly for sequence-to-sequence tasks such as machine translation, text summarization, and dialogue generation. Unlike recurrent networks, which process tokens one time step at a time, Transformers can process an entire sequence in parallel within the same layer while dynamically modeling dependencies between different positions.
Consider the following input sequence:
I like learning machine learning
The model must understand not only the meaning of each word, but also the relationship between “learning” and “machine” and the role of each word in context. The central idea of the Transformer is that a token representation should not depend only on the token itself. It should also be dynamically adjusted according to the content of other tokens in the sequence.
At a high level, the original Transformer consists of two components:
- Encoder: Understands the input sequence and converts it into contextualized hidden representations.
- Decoder: Uses the encoder’s information to generate the target sequence step by step.
In a translation task, the encoder receives a sentence in the source language, while the decoder generates the translation based on the source sentence’s semantic representation.
2. Overall Architecture: Encoder and Decoder
A classic Transformer is typically built by stacking multiple encoder layers and multiple decoder layers. The original paper used six layers in each stack, but the number of layers is a configurable hyperparameter that can be adjusted according to the task and available computing resources.
Each encoder layer generally contains:
- A multi-head self-attention layer;
- A residual connection and layer normalization;
- A position-wise feed-forward network;
- Another residual connection and layer normalization.
Each decoder layer generally contains three major modules:
- A self-attention layer with a causal mask;
- An encoder-decoder attention layer;
- A position-wise feed-forward network.
The overall data flow can be represented as follows:
Input tokens↓Token embeddings + positional encoding↓Encoder layers × N↓Encoder output↓Decoder layers × N↓Linear projection↓Probability distribution↓Output tokens
Different layers in the same stack generally use different parameters. In other words, although the layers share the same structure, they do not normally share weights. This allows different depths of the network to learn different levels of features. Lower layers may focus more on local lexical relationships, while deeper layers can form more abstract semantic representations.
3. From Tokens to Vectors: Embeddings and Tensor Shapes
Neural networks cannot process raw strings directly. The input text is first tokenized into an integer sequence. For example:
"Machine learning is interesting"→ [105, 287, 46, 912]
Each integer corresponds to a token in the vocabulary. The model then uses an embedding matrix to map these integers to continuous vectors.
Assume that:
- The batch size is
B; - The sequence length is
L; - The hidden dimension is
D.
The embedded input tensor typically has the following shape:
[B, L, D]
For example, if the batch size is 32, the maximum sequence length is 128, and the hidden dimension is 512, the input tensor shape is:
[32, 128, 512]
Embedding vectors represent the semantic features of tokens, but they do not tell the model where tokens appear in the sequence. The Transformer therefore also needs positional information.
4. Positional Encoding: Representing Token Order
Self-attention has a degree of permutation invariance. If the tokens in a sentence are reordered, attention alone may have difficulty distinguishing the different meanings associated with those arrangements.
To address this issue, Transformers add positional information to token embeddings:
Input representation = token embedding + positional encoding
Early Transformer architectures commonly used fixed positional encodings based on sine and cosine functions:
PE(pos, 2i) = sin(pos / 10000^(2i / D))PE(pos, 2i+1) = cos(pos / 10000^(2i / D))
Here:
posrepresents the token position;irepresents the vector-dimension index;Drepresents the hidden dimension.
This method generates a distinct vector for each position and preserves certain relative-position patterns.
In practice, models can also use learned positional embeddings, where each position is assigned a trainable vector. The two approaches have different characteristics:
- Fixed positional encoding does not require additional trainable parameters;
- Learned positional embeddings can adapt more strongly to a specific task;
- When the input length exceeds the range supported during training, both approaches require additional consideration for generalization.
5. Self-Attention: The Core Mechanism
5.1 Basic Intuition
Self-attention determines how important other tokens are when computing the representation of a particular token.
For example, in the sentence:
Alex put the book on the table because it was heavy.
The model needs to determine whether “it” is more likely to refer to “the book” or “the table.” A local context window may not be sufficient, but self-attention can directly establish connections between the current position and other positions.
5.2 Query, Key, and Value
Given an input matrix X, the model generates three different representations through linear transformations:
Q = XWQK = XWKV = XWV
They represent:
- Q, or the query vector: what information the current position is looking for;
- K, or the key vector: what information each position can provide;
- V, or the value vector: the content that will actually be aggregated.
The attention formula is:
Attention(Q, K, V)= softmax(QKᵀ / √dk)V
The computation consists of four steps:
- Calculate the similarity between the query vector and all key vectors;
- Scale the results by
√dkto prevent excessively large dot products; - Use softmax to convert the similarity scores into a probability distribution;
- Compute a weighted sum of all value vectors.
Positions that are more closely related to the current token receive higher attention weights, while less relevant positions receive lower weights.
5.3 Why Scaling Is Necessary
When the vector dimension is large, the dot products between Q and K can also become large. After these values are passed to softmax, the distribution may become too sharp, causing small gradients and unstable training.
Dividing by √dk controls the numerical range of the dot products and makes the softmax input smoother, improving optimization.
6. Multi-Head Attention: Understanding Sequences from Multiple Perspectives
A single attention mechanism usually models relationships within one representation subspace. Multi-head attention divides the hidden dimension into multiple subspaces and performs several attention computations in parallel.
The process can be summarized as:
head_i = Attention(Q_i, K_i, V_i)MultiHead(Q,K,V) = Concat(head_1,...,head_h)WO
Different attention heads may learn different types of relationships, including:
- Local word combinations;
- Subject-verb relationships;
- Coreference relationships;
- Long-range dependencies;
- Syntactic or semantic associations.
Multi-head attention is not simply a repetition of the same computation. Each head uses independent projection matrices, allowing it to focus on a different feature space. The outputs of all heads are then concatenated and passed through another linear transformation to restore the original hidden dimension.
7. Data Flow Through the Encoder
The encoder input first passes through a self-attention layer. Because the encoder needs to understand the complete input sequence, each position can generally attend to other positions in the sequence.
The attention output then goes through a residual connection and layer normalization:
X₁ = LayerNorm(X + SelfAttention(X))
Residual connections have two important functions:
- Reducing the risk of vanishing gradients in deep networks;
- Preserving the original information so that the attention layer does not destroy existing representations.
Layer normalization helps stabilize the numerical distribution between layers.
The result is then sent to a position-wise feed-forward network. This network usually applies two linear layers and a nonlinear activation function independently to each position:
FFN(x) = W₂ σ(W₁x + b₁) + b₂
The intermediate dimension is typically larger than the hidden dimension. The feed-forward network performs an additional nonlinear transformation on the information aggregated by attention.
A complete encoder layer can be written as:
H = LayerNorm(X + SelfAttention(X))Y = LayerNorm(H + FFN(H))
After passing through multiple encoder layers, each position contains richer contextual information.
8. Masking and Cross-Attention in the Decoder
The decoder generates the target sequence. When generating the token at position t, it can only access previously generated tokens and must not read future tokens. Otherwise, the model would receive information it should not have during generation, creating information leakage during training.
For this reason, decoder self-attention uses a causal mask. A typical mask matrix is:
[ 0 -∞ -∞ -∞0 0 -∞ -∞0 0 0 -∞0 0 0 0 ]
After the mask is added to the attention scores, future positions receive weights close to zero after softmax.
The second attention module in the decoder is called encoder-decoder attention, or cross-attention. Its query comes from the decoder representation, while its keys and values come from the encoder output:
Q = decoder representationK = encoder outputV = encoder output
This allows the decoder to dynamically focus on the relevant parts of the input according to its current generation state. For example, when generating a word in the target language, the model can focus on the corresponding semantic region in the source sentence.
9. Training: Predicting the Target Sequence in Parallel
Training commonly uses teacher forcing. Suppose the target sequence is:
I like programming
The decoder input can be:
start token I like
The model must predict:
I like programming end token
Because the entire target sequence is known during training, predictions for multiple positions can be computed at once. The causal mask ensures that each position only uses information from earlier positions.
The model uses a linear layer to map the hidden vectors to the vocabulary size:
logits = H W + b
Softmax then produces a probability distribution over the tokens. The training objective is typically to minimize cross-entropy loss:
Loss = -Σ log P(correct token | known context)
In practice, loss is usually ignored at padding positions. Techniques such as label smoothing, learning-rate warmup, and gradient clipping may also be used to improve training stability.
10. Inference: Generating Text Step by Step
During inference, the target sequence is not available. The model starts with a beginning-of-sequence token and generates one token at a time:
Input start token→ Predict the first token→ Append the first token to the input→ Predict the next token→ Continue repeating
Common generation strategies include:
- Greedy search: Select the token with the highest probability at each step;
- Random sampling: Select tokens according to the probability distribution;
- Temperature scaling: Control the smoothness of the probability distribution;
- Beam search: Keep multiple candidate sequences and select the one with the highest overall score.
Inference is generally slower than training because each generation step depends on the result of the previous step. In engineering implementations, key-value caching is commonly used to store previously computed keys and values, avoiding recomputation over the entire historical sequence.
11. Computational Complexity and Engineering Considerations
Self-attention calculates relationships between every pair of positions in a sequence. As a result, the space and computational cost of the attention matrix generally grows quadratically with sequence length:
O(L²D)
As the sequence becomes longer, memory consumption and computation increase rapidly. This is one of the main bottlenecks in long-context processing.
Common optimization directions include:
- Limiting the maximum input length;
- Using local attention or sparse attention;
- Caching key-value states;
- Using more efficient attention kernels;
- Splitting long documents into chunks;
- Using lower-precision computation to reduce memory usage.
The following issues also require attention:
- Padding: Sequences of different lengths are usually padded to a common length. Padding positions should be masked during attention computation.
- Training stability: Learning rate, normalization strategy, and initialization should be configured carefully.
- Overfitting: Dropout, weight decay, and data augmentation can help reduce overfitting.
- Position extrapolation: Positional representations may fail when the inference length is much longer than the training length.
- Repetitive generation: Sampling strategies or repetition penalties may be needed to improve output quality.
12. Advantages and Limitations of Transformers
The main advantages of Transformers include:
- They can process sequences in parallel, improving training efficiency;
- They are effective at capturing long-range dependencies;
- Their modular design makes them easy to scale and extend;
- They can support translation, classification, summarization, question answering, and generation;
- Multi-head attention provides strong representational capacity.
However, Transformers also have limitations:
- Standard self-attention is computationally expensive for long sequences;
- Large models require substantial data and computing resources;
- Output quality depends heavily on the quality of the training data;
- Models may produce factual errors or content that violates constraints;
- Attention weights should not be treated as strict causal explanations.
In real-world systems, Transformers therefore often need to be used together with data cleaning, task constraints, evaluation frameworks, and inference optimizations.
13. Summary
A Transformer can be understood as a deep sequence-modeling architecture composed of attention mechanisms, feed-forward networks, residual connections, layer normalization, and positional representations.
Its core workflow is:
Tokenization→ Token embeddings→ Add positional information→ Multi-head self-attention→ Feed-forward network→ Stack multiple layers→ Output prediction
The encoder builds contextual representations of the input sequence, while the decoder generates the target sequence under causal constraints. Self-attention allows the model to dynamically select relevant context, multi-head attention captures relationships from multiple perspectives, and residual connections and layer normalization help deep networks train stably.
Understanding the data flow between these modules provides a foundation for further study of text generation, long-sequence modeling, and large-scale neural network systems.
