[!NOTE] Title
This article is sourced from Illustrated Transformer
Overview
Let's take a high-level overview: what is a Transformer?

image.png
If we dive deeper, the structure is actually quite simple.

image.png
It's just a stack of encoders and a stack of decoders.
image.png
Diving into the Encoder, there are two sub-layers.
image.png
- The encoder's input first passes through a self-attention layer—this layer helps the encoder look at other words in the input sentence while encoding a specific word.
- The output of the self-attention layer is fed into a feed-forward neural network. The exact same network is applied independently to each position.
Let's also look at the Decoder's internal structure.
image.png
The decoder also has these two layers, but between them there is an attention layer that helps the decoder focus on relevant parts of the input sentence.
Tensor Input
Now that we've seen the main components of the model, let's start examining the various vectors/tensors and how they flow between these components, transforming the input of a trained model into output.
In natural language processing applications, we first use an embedding algorithm to convert each input word into a vector.

Each word is embedded into a vector of size 512. We'll use these simple boxes to represent these vectors.
Embeddings only occur in the bottom-most encoder. The abstraction that all encoders share is that they receive a list of vectors of size 512—in the bottom-most encoder, this will be the word embeddings, but in other encoders, it will be the output of the encoder directly below it. The size of this list is a hyperparameter we can set—basically, it will be the length of the longest sentence in our training dataset.
Let's see what happens to the tensor input into the Encoder.

image.png
Here we start to see a key characteristic of the Transformer: the word at each position flows through its own path in the encoder. There are dependencies between these paths in the self-attention layer. However, the feed-forward layer does not have these dependencies, so various paths can be executed in parallel while passing through the feed-forward layer.
Let's use a simpler sentence to demonstrate this process.
The word at each position passes through a self-attention process. Then, they each pass through a feed-forward neural network -- the exact same network with each vector flowing through it separately.
Self-Attention Overview
Let's distill how Self-Attention works.
The following sentence is what we want to translate: "The animal didn't cross the street because it was too tired, The animal didn't cross the street because it was too tired
What does 'it' in this sentence refer to? The street or the animal? This is an easy question for humans, but not simple for an algorithm.
When the model processes the word 'it', self-attention allows it to associate 'it' with 'animal'.
If we visualize it, we can see that under the current attention mechanism, 'it' has the highest association with 'the animal'.

As we encode the word 'it' in encoder #5 (the top-most encoder in the stack), part of the attention mechanism focuses on 'The Animal' and encodes part of its representation into the encoding of 'it'.
Self-Attention in Detail
First, let's understand how to compute self-attention using vectors, and then move on to its actual implementation—using matrix calculations.
Step 1: Query, Key, and Value Vectors
The first step in calculating self-attention is to create three vectors from each of the encoder's input vectors (in this case, the embedding of each word). So for each word, we create a Query vector, a Key vector, and a Value vector. These vectors are created by multiplying the embedding by three matrices that we trained during the training process.
Note that these new vectors are smaller in dimension than the embedding vectors. They have a dimension of 64, while the embedding and encoder input/output vectors have a dimension of 512. They don't have to be smaller; this is an architectural choice to make the computation of multi-head attention (mostly) constant.

Multiplying x1 by the WQ weight matrix produces q1, the 'Query' vector associated with that word. We ultimately create a 'Query', 'Key', and 'Value' projection for each word in the input sentence.
What are the 'Query', 'Key', and 'Value' vectors?
These are abstract concepts used for calculating and thinking about attention. Once you read the following content on how attention is calculated, you will roughly understand the role each of these vectors plays.
Step 2: Calculating the Score
The second step in calculating self-attention is to compute a score. For example, let's say we're computing self-attention for the first word 'Thinking' in this example. We need to score each word in the input sentence against this word. The score determines how much focus to place on other parts of the input sentence as we encode a word at a certain position.
The score is calculated by taking the dot product of the query vector with the key vector of the word we're scoring. So if we're processing the self-attention for the word at position #1, the first score would be the dot product of q1 and k1. The second score would be the dot product of q1 and k2.

image.png
Steps 3 and 4: Normalization
Divide the score by 8 (the square root of the dimension of the key vector used in the paper—64. This leads to more stable gradients. There may be other possible values, but this is the default), and then pass the result through a softmax operation. Softmax normalizes the scores so that they are all positive and sum to 1.

image.png
This softmax score determines how much each word will be expressed at this position. Obviously, the word at this position will have the highest softmax score, but sometimes it's useful to pay attention to another word that is relevant to the current word.
Step 5: Vector Processing
Multiply each Value vector by the softmax score (preparing for summation). The intuition here is to keep intact the values of the word we want to focus on, and drown out irrelevant words by multiplying them by tiny numbers (e.g., 0.001).
Step 6: Summing the Weighted Value Vectors
The sixth step is to sum the weighted value vectors. This produces the output of the self-attention layer at this position (for the first word).

image.png
This marks the end of the self-attention calculation. The resulting vector is one that we can send to the feed-forward neural network. However, in actual implementation, this calculation is done in matrix form for faster processing. Now that we've seen the intuition at the word level, let's look at that.
Self-Attention Matrix Calculation
Step 1: Mapping Matrices
The first step is to calculate the Query, Key, and Value matrices. We do this by packing the embeddings into a matrix X, and then multiplying it by the weight matrices we trained (WQ, WK, WV).

Each row in the X matrix corresponds to a word in the input sentence. We again see the size difference between the embedding vectors (512, or 4 boxes in the figure) and the q/k/v vectors (64, or 3 boxes in the figure).
Step 2: Calculation
Since we're dealing with matrices, we can combine steps 2 through 6 into a single formula to calculate the output of the self-attention layer.
image.png
Multi-head Attention
Multi-head attention is designed to optimize the performance of the self-attention mechanism.
- It expands the model's ability to focus on different positions.
In the above example, z1 contains some encoding of other words, but it might be dominated by the actual word itself. If we were translating a sentence like 'The animal didn't cross the street because it was too tired', it would be useful to know which word 'it' refers to.
- It gives the attention layer multiple 'representation subspaces'.
As we'll see next, in multi-head attention we don't have just a single set of query/key/value weight matrices, but multiple sets (the Transformer uses eight attention heads, so each encoder/decoder ends up with eight sets). Each of these sets is randomly initialized. Then, after training, each set is used to project the input embeddings (or vectors from lower encoders/decoders) into a different representation subspace.

With multi-head attention, we maintain separate Q/K/V weight matrices for each head, resulting in different Q/K/V matrices. As we did before, we multiply X by the WQ/WK/WV matrices to produce Q/K/V matrices.
If we perform the same self-attention calculation described above, but this time using different weight matrices, eight times in total, we end up with eight different Z matrices.
image.png
Feed-forward Layer Challenge
This presents a challenge. The feed-forward layer doesn't expect eight matrices—it expects a single matrix (one vector per word). So we need a way to condense these eight matrices into a single matrix.
We concatenate the matrices and then multiply by an additional weight matrix WO.

image.png
That's basically all there is to multi-head self-attention. I realize this involves a lot of matrices. Let me try to put them all in one visual diagram so we can see them in one place.
All steps

image.png
Let's revisit the previous example with a diagram. See where different attention heads focus when encoding the word 'it' in our example?
As we encode the word 'it', one attention head focuses mainly on 'the animal', while another focuses on 'tired'—in a sense, the model's representation of the word 'it' incorporates some of the representations of 'animal' and 'tired'.
If we add all the attention heads to the picture, however, things might become harder to explain.

image.png
Representing The Order of The Sequence Using Positional Encoding
What's missing from the model as described so far is a way to account for the order of words in the input sequence.
To solve this, the Transformer adds a vector to each input embedding. These vectors follow a specific pattern that the model learns, which helps determine the position of each word, or the distance between different words in the sequence.
The intuition here is that adding these values to the embeddings provides meaningful distances between the embedding vectors once they are projected into Q/K/V vectors and during dot-product attention.

To give the model a sense of word order, we add positional encoding vectors—whose values follow a specific pattern.
The input vector X1 is added to the positional encoding t1 to produce a vector with positional information.
If we assume the embedding dimension is 4, the actual positional encoding would look like this.

An example of actual positional encoding with a toy-embedding size of 4.
What might this pattern look like?
In the following figure, each row corresponds to the positional encoding of a vector. So the first row would be the vector we add to the first word embedding in the input sequence.
Each row contains 512 values—each value between 1 and -1. We've color-coded them so the pattern is visible.

A real example of positional encoding for 20 words (rows) with an embedding size of 512 (columns). You can see it split in the middle. This is because the left half's values are generated by one function (using sine), and the right half's values are generated by another function (using cosine). They are then concatenated to form each positional encoding vector.
Positional encoding is not the only method. The current diagram is based on the positional encoding formula described in the paper (Section 3.5). You can see the code for generating positional encodings in get_timing_signal_1d(). It has the advantage of being able to scale to unseen sequence lengths (for example, if our trained model is asked to translate a sentence longer than any sentence in our training set).
The Residuals
One detail in the encoder architecture that needs mentioning before we continue is that each sub-layer (self-attention, feed-forward neural network) in each encoder has a residual connection around it, followed by a layer normalization step.
The following points can help understand the role of residual connections in the Transformer.
- The mechanism of skip connections
In each sub-layer of the Transformer (such as the self-attention layer and the feed-forward neural network layer), the input is added to the original input after being processed by the layer. This addition operation allows the model to 'skip' certain non-linear transformations during learning, thereby preserving the information from the initial input and ensuring more stable information flow through the network.
- Mitigating vanishing gradients and accelerating convergence
Deep networks are often prone to vanishing or exploding gradients, and residual connections help gradients propagate more smoothly during backpropagation by directly passing the input to deeper layers. This not only reduces the risk of vanishing gradients but also makes model training faster and more stable.
- Model's expressive power
Residual connections allow each layer to learn a 'correction' or 'residual' to the input signal, rather than completely reconstructing the entire signal. This approach simplifies the learning task for each layer by focusing only on the difference between input and output, thereby improving the model's expressive power.
- Combination with normalization
In the Transformer, residual connections are usually combined with layer normalization. Performing the residual connection first and then normalization can further stabilize the training process and improve model performance.
If we visualize the vectors and layer normalization operations associated with self-attention, it looks like this:
image.png

image.png
The same applies to the decoder's sub-layers. If we consider a Transformer composed of 2 stacked encoders and decoders, it looks like this.
image.png
Decoder
Now that we've covered most of the concepts on the encoder side, we basically also know how the decoder components work. But let's see how they work together.
The encoder first processes the input sequence. Then, the output of the top encoder is transformed into a set of attention vectors Key and Value. These vectors are used by each decoder in its 'encoder-decoder attention' layer, which helps the decoder focus on appropriate places in the input sequence:

After the encoding stage is complete, we begin the decoding stage. Each step in the decoding stage outputs one element from the output sequence (the English translation sentence in this example).
The following steps are repeated until a special symbol is reached, indicating that the transformer decoder has completed its output.
The output of each step is fed to the bottom decoder at the next time step, and the decoder bubbles up its decoding results like the encoder. Just as we did with the encoder inputs, we embed and add positional encoding to these decoder inputs to indicate the position of each word.

Diagram
The self-attention layer in the decoder operates slightly differently from that in the encoder.
In the decoder, the self-attention layer only allows attention to earlier positions in the output sequence. This is achieved by masking future positions (setting them to -inf) before the softmax step in the self-attention calculation.
The Final Linear and Softmax Layer
The decoder stack outputs a vector of floats. How do we turn that into words? That's the job of the final linear layer, which is followed by a softmax layer.
The linear layer is a simple fully connected neural network that projects the vector produced by the decoder stack into a much larger vector called a logits vector.
Let's assume our model knows 10,000 unique English words (our model's 'output vocabulary') that it learned from its training dataset.
This would make the logits vector 10,000 cells wide—each cell corresponding to the score of a unique word. That's how we interpret the output of the model followed by the linear layer.
The softmax layer then turns those scores into probabilities (all positive, summing to 1.0). The cell with the highest probability is chosen, and the word associated with it is output as the current output.

This figure starts from the bottom, using the output vector of the decoder stack as the starting point. Then it is converted into the output word.
The Loss Function
Let's assume we're training our model. Suppose this is the first step of training, and we're training it on a simple example—translating 'merci' into 'thanks'.
This means we want the output to be a probability distribution representing the word 'thanks'. But since this model is not yet trained, this is unlikely to happen anytime soon.

The model parameters (weights) are all randomly initialized, so the (untrained) model produces a probability distribution with arbitrary values for each cell/word. We can compare this with the actual output and then adjust all model weights through backpropagation to make the output closer to the desired output.
How do we compare two probability distributions? We simply subtract one from the other. For more details, check out cross-entropy and Kullback–Leibler divergence.
But note that this is an oversimplified example. More realistically, we would use a sentence with more than one word. For example—input: 'je suis étudiant' and expected output: 'I am a student'. This actually means we want our model to successively output probability distributions, where:
- Each probability distribution is represented by a vector of width vocab_size (6 in our example, but more realistically a number like 30,000 or 50,000).
- The first probability distribution has the highest probability at the cell corresponding to the word 'i'.
- The second probability distribution has the highest probability at the cell associated with the word 'am'.
- And so on, until the fifth output distribution indicates the '
<end of sentence>' symbol, which is also associated with a cell from the 10,000-element vocabulary.
image.png
After training the model for a long enough time on a sufficiently large dataset, we hope the produced probability distribution will look like this:
image.png
Now, since the model generates one output at a time, we can assume the model is selecting the word with the highest probability from that probability distribution and discarding the rest. This is one approach (called greedy decoding).
Another approach is to hold on to, say, the top two words (for example, 'I' and 'a'), and then run the model twice in the next step: once assuming the first output position is the word 'I', and once assuming the first output position is the word 'a', and then keep the version that produces fewer errors considering positions #1 and #2. We repeat this for positions #2 and #3, etc. This method is called 'beam search', and in our example, the beam size is two (meaning two partial hypotheses (unfinished translations) are kept in memory at all times), and top_beams is also two (meaning we will return two translations).