Transformer Model
The transformer model represents another significant leap in the NLP field after the Seq2Seq model and the attention mechanism. The main idea behind the transformer model is to remove the RNN structure from the Seq2Seq + attention model. Hence, the transformer is a model that exclusively uses attention operations (and FC operations) without relying on RNNs.
Why Remove RNNs?
Sequential data not only depends on the values of each item but also their order. For instance, "John loves Sarah" and "Sarah loves John" both contain the same words, but their order results in different meanings. Thus, a model that can handle sequential data must also be able to process this order information.
RNNs were suitable for handling sequential data since they accept inputs sequentially and update their hidden states. Models like Seq2Seq leveraged RNNs mainly because there weren't many alternatives at the time.
However, RNNs have several disadvantages:
-
Parallelization Issue: Due to its inherent sequential nature, RNNs cannot be parallelized. This makes training on large datasets impractical due to extended training times.
-
Long Distance Dependency Problem: Relationships between distant items in a sequence don't learn well due to the gradient vanishing/exploding problem.
The attention operation provides a solution to both of these issues. It allows for parallelization and directly compares each query with all keys, addressing the long-distance dependency issue. Theoretically, a model using only attention operations should learn faster than an RNN-based model, allowing for training on larger datasets and producing better performance.
How RNNs were Eliminated: Positional Encoding
While RNN structures naturally incorporated order information, attention operations do not consider it. Therefore, in the transformer model, a vector containing positional information, termed 'positional encoding,' of the same dimension as the input embedding is added.

To incorporate order information, the transformer model adds positional encoding to the input embedding.
The positional encoding ensures that even the same word will have different embedding vectors based on its position, successfully conveying positional information.
However, the method mentioned above isn't the only way to generate vectors with positional information.
Structure of the Transformer Model

Like the Seq2Seq model, the transformer model comprises an encoder and a decoder.

The transformer encoder consists of multiple stacked encoder layers. The output of a previous encoder layer serves as the input to the next encoder layer.
Each encoder layer is divided into a multi-head self-attention sub-layer (orange block) and a position-wise fully connected feed-forward sub-layer (blue block). The output of each sub-layer is passed through a residual connection, added to its input, and then normalized (yellow block) before being fed to the next sub-layer.

The transformer decoder consists of multiple stacked decoder layers. The output of a previous decoder layer serves as the input to the next decoder layer.
Each decoder layer comprises a masked multi-head self-attention sub-layer (first orange block), a multi-head cross-attention sub-layer (second orange block), and a position-wise fully connected feed-forward sub-layer (blue block). Similar to the encoder, the output of each sub-layer in the decoder undergoes a residual connection, is added to its input, and then normalized (yellow block) before being fed to the subsequent sub-layer.
Let's delve deeper into each operation.
Multi-head Attention Operation
Multi-head attention operation is a technique designed to execute the attention operation in parallel multiple times. Here, "head" refers to the entity executing the attention operation. Thus, "multi-head" signifies performing attention operations multiple times (on the same sequence). Performing attention operations times on the same source indicates the ability to focus with different "focus methods", or in more layman's terms, viewing the sequence from different "perspectives".
To be specific, when the sequence length is and the dimension of the input embedding is , a multi-head attention operation with heads works as follows:
-
Inputs , , and are given.
-
In the encoder layer and decoder layer using multi-head self attention, (the output from the previous layer).
-
In the decoder layer using multi-head cross attention, (the output from the previous layer) and (the output from the encoder).
-
, , and are matrices of size.
-
-
Creating Query, Key, Value for Each Head:
-
If all heads use the same query, key, and value, it won't provide a multi-perspective multi-head attention operation. Thus, weight matrices , , and are multiplied with , , and respectively to generate the query, key, and value for the head: , , and .
-
These matrices are of dimensions: , , and respectively. The resulting matrices , , and are of dimensions, , and respectively.
-
is the dimension of the query and key for each head, while is the dimension of the value.
-
During actual implementation, rather than multiplying matrices , , and individually, matrices , , and of size are used. After multiplication, the result is split into the desired sizes.
-
-
Calculate Attention:
- Each head performs the scaled dot-product attention operation using , , and .
-
The resultant attention value is a matrix of size .
-
Typically, during implementation, vector operations are used to calculate all at once rather than separately for each head.
-
Concatenate Each Head's Attention Value:
- All attention values from each head are concatenated, then multiplied with the weight matrix . The result is the final output of the multi-head attention.
- is a matrix of size .
It should be noted that the original Transformer paper used .
Thanks to extensive vector operations, the cost of the multi-head attention operation is roughly similar to the cost of a single-head attention operation
Masked Attention Operation
In the decoder, a specialized form of attention operation called the masked multi-head self attention operation is used. This masking ensures that during attention calculations, the model cannot refer to future tokens in the sequence, thus mimicking the real-time generation of sequences.
Several methods can implement masking, but in the Transformer model, a mask matrix is utilized. The mask matrix is an matrix of s and negative infinity , where is the length of the input sequence. The values in the matrix are defined as:
-
if the word (query) should not attend to the jth word (key). Specifically, if the ith word (from the query) comes after the jth word (from the key) in the sequence.
-
otherwise.
Given this mask matrix, the procedure for masked attention is:
- Compute Attention Scores: For the provided query , key , and value , compute the scaled dot product attention scores :
Where is the dimension of the query and key vectors.
-
Apply Mask: To the attention scores, add the mask matrix :
-
Compute Attention Distribution: Calculate the softmax of the masked attention scores to obtain the attention distribution .
-
Calculate Attention Value: Multiply the attention distribution with the value matrix to obtain the attention value .
Position-wise Fully Connected Feed-Forward Operation
The position-wise fully connected feed-forward operation in the Transformer model can be defined using linear operations followed by a ReLU activation. Specifically:
Where:
-
and are weight matrices.
-
and are bias vectors.
-
is the dimension of the input embedding.
-
is the dimension of the feed-forward operation's hidden layer.
Layer Normalization Operation
In both the Transformer's encoder and decoder layers, the output of each sub-layer undergoes a residual connection followed by layer normalization. Mathematically, if is the input to a sublayer with output , then the output of the layer normalization is:
Layer normalization is a type of normalization that operates across the features (as opposed to batch normalization, which operates across batches) and is commonly used in NLP tasks and the Transformer architecture. It helps in stabilizing the activations in the network and speeds up training.