Transformer - How translator be possible
Published on 2026-04-12
•5510 wordsThis article is the first in a series unpacking the Transformer architecture. It is a personal visualization breakdown of the classic Encoder-Decoder architecture.
Transformer as a Translation Machine
The Transformer architecture made its debut in Google's paper Attention Is All You Need, marking a milestone in the field of machine learning. It was originally created to solve the Seq2seq (Sequence to Sequence) machine translation problem more efficiently.
So, I treat the Transformer as a translation machine.
Here is the mini architecture diagram:
In the diagram, the original sentence is first processed by the Encoder into an intermediate semantic context, and then the Decoder generates the resulting sentence token by token (autoregressively) based on that context.
The whole process is an act of translation. To understand the classic Transformer, we first need to understand the act of translation itself.
The Difficulty of Translation
In the physical world, translation can be broken into two steps:
- The translator receives the original message, understands the context using their own knowledge, and temporarily stores the digested context.
- The translator expresses the message based on that context.
The Transformer does the same. The Encoder corresponds to the first step; the Decoder corresponds to the second.
However, the machine process is not as complex as human logic. Since we are already used to translation, let's boldly sort out the machine process.
It seems like only two steps, but the difficulty lies in: how do we implement them?
Encoder: How Understanding is Implemented
This is how the Encoder works. For example, if the source sentence is :
Embedding
Embedding consists of several steps:
- Tokenization
- Embedding
- Position Embedding
The original Sequence is broken into multiple fragments through Tokenization, becoming a Token sequence (different algorithms split differently; to keep the example simple, all tokens below are split as whole words). Let the number of fragments be , represented as:
In the process above, is first split into .
Then, each token is mathematically modeled. For example, the first token can be written as:
Stacking the whole sentence gives the input matrix:
Assume our model dimension is 6. Each token is then converted into a 6-dimensional vector representation:
From a geometric perspective, these are 4 points floating in a 6-dimensional space. They are currently "isolated": only word meanings exist, no sentence meaning. is just I, is just love, and is still just the dictionary definition of dog.
How do we make these 4 words share information with each other, causing each to be influenced and corrected (as vector updates)? This is what Attention will do next.
(Note: the embedding step above only completes the word-meaning vectorization. A third step also needs to carry each token's position information within the source sentence. This is done by Positional Encoding; with positional information, the sentence-level context for Self-Attention can be effective. We won't expand on it here.)
1) Self-Attention: The Self-Attention Mechanism
Attention solves the following problem: each row of the representation matrix should complete its own semantic enrichment. The flow is as follows:
Mathematically:
Although the formula has many variables, from a functional perspective it is very clear.
Let's unpack it step by step.
The Attention process involves a lot of matrix operations. If you are not familiar with them, I recommend reading The Geometric Intuition of Matrices first.
Q, K, V
Our input is , and inside the Attention function we see . So what is the relationship between and ?
In fact, are the result of projecting the source sentence matrix from three different angles using the learned weights — these are the weight matrices.
The weight matrices are usually denoted as , like a repeatedly refined "stage script":
The sentence is a play; each token is an actor. At first, each actor only knows their own role. Whether the whole play is perfect (i.e., whether the semantics are perfect) depends on whether the actors can fully rehearse with (Attention) each other.
In Self-Attention, this script is split into three parts: . They are not part of the input sentence; they are model parameters. Every time the input representation matrix enters a layer, these three groups of parameters generate the corresponding matrices.
At the beginning of training, the entries of are just random numbers. This initial matrix is unlikely to produce good Seq2seq output, but through training the random weights are gradually optimized into more effective matrices.
Implementation-wise, the current representation matrix is first projected into three matrices:
If we only look at the -th row of each matrix, they represent:
- : "What am I looking for?" (which other actors should I rehearse with)
- : "How am I matched?" (what role am I playing)
- : "What content can I contribute?" (what is my part in the scene)
is multiplied by all at once. This is equivalent to each row generating its own :
Note: Although the weight matrix is split into , in engineering it is usually represented as one large matrix, and the Q, K, V matrices are obtained by slicing during computation. This is done to leverage the efficiency of large matrix multiplication on GPUs.
Q, K, V Generation Example
Assume the current input matrix is , and we have the corresponding . Note: these numbers are only for demonstrating the matrix pipeline; they are not real trained parameters.
The training of the weight matrices is a topic large enough for its own article; we won't expand on it here.
The three weight matrices can be written as:
Multiplying the whole sentence at once gives three result matrices:
The same is projected into three different weight matrices; these three matrices form the logical core of Attention.
Note 1: are matrices representing the whole sentence, not temporary vectors. Later, when we extract or , it is simply because they are particular rows of the and matrices.
Note 2: Here we let output 6 dimensions so that the final result can return directly to the main model dimension . In real engineering, it is common to output a shorter first, and then use an additional to project back to .
(Dot Product)
After obtaining the three matrices, the first step of the Attention (rehearsing) process is the matrix operation. Specifically, it is , transposing , because the dimensions and are valid for matrix multiplication. We temporarily call the result :
Here, the -th row means:
- "Which token is the -th token row looking at?"
- The -th column means "the score it assigns to the -th token row."
Let's do a full expansion for looking at . To avoid skipping, we first put the complete and again:
Thus:
Their relevance score (how much they need to rehearse together) is:
This is a dot product of two vectors, resulting in a single number. This number reflects how relevant word is to the word ; it indicates how much the word should draw supplementary information from when it is finally translated. In our stage-play metaphor, it represents how much the actor should rehearse with actor in order to perform the script perfectly:
Since our model dimension is very small, this dot product can be visualized as the radar chart below, where overlap reflects relevance.
Don't forget, we only took one pair of tokens as an example; the actual computation is performed on the whole matrix in one go. This is the first step of Attention. The product of this step can be said to be: every actor now knows how much they need to rehearse with every other actor in the script.
Scaled - and Softmax
After obtaining the scores, each row is first divided by for scaling, and then passed through softmax:
To explain these two steps clearly, we first need to understand how softmax works:
After softmax, each value in the similarity matrix changes from a score to a proportion (score rate). For token , it means the proportion of its total attention that is allocated to token .
The classic mathematical form is:
At this point, for any row held by token , every value becomes a proportion; higher scores get larger proportions, and the sum is 1. This process can be seen as attention allocation.
In the softmax formula, it depends on , which means that if there are extreme values, all the weight will focus on the largest region.
This is where comes in. It is called the scaling factor. Its purpose is to control the range of , keeping the variance of the resulting matrix within a certain interval to avoid extreme polarization.
Why is the scaling factor and not something else? In the original Transformer paper, this value comes from an assumption: the vectors and inside and have mean 0 and variance 1. Their dot product then has variance . Softmax wants data with variance around 1, so the scaling factor that makes the scaled result have variance 1 is . This assumption is a common convention in the machine learning field, not the only solution. If interested, see these two articles: 苏剑林 - On Transformer Initialization, Parameterization, and Standardization and 苏剑林 - Entropy Invariance of Attention Scale.
V
Through the previous step, we obtain a proportion matrix. It means every token knows the weight of semantic supplementation it should get from other tokens when the final source sentence meaning is generated.
In the stage-play metaphor, this means every actor knows, under the script , with which other colleagues and to what degree they should rehearse in order to perform perfectly.
But knowing how much to rehearse is not enough; we also need to know the other actor's part. This is where the weight matrix comes in.
The overall process is:
This is the -th row of the output matrix , i.e., the new representation of the -th token after absorbing information from the whole scene.
For example, in a certain layer, the attention weights of over the whole sentence might be:
Then its new representation is:
This step is the "vector correction". The coordinate point originally occupied by absorbs information from tokens such as . It is no longer an isolated verb from the dictionary; it becomes a "love emitted by I and directed toward some object." Here, participates in the semantic correction of . This process is called "Attend To" in terminology. It also matches our stage-play metaphor: the actor "Attends To" the scene of the actor .
Summary
Reviewing the whole process, Self-Attention can be divided into four steps:
- Project the representation matrix into three perspectives using .
- Use to get the rehearsal strength between token rows.
- Use softmax to turn strength into attention weights.
- Use these weights to mix , completing the vector correction for each token.
In other words, each layer of Attention moves the word vectors once in space. As layers stack up, each token's vector gradually carries the shadow of the whole sentence.
Readers can once again imagine our stage-play metaphor here.
Multi-Head Attention
Multi-Head Attention is not complicated. It is the same group of actors switching rehearsal methods, from one angle to multiple angles (Heads):
- Some heads focus on grammatical dependencies.
- Some heads focus on anaphoric (referential) relations.
- Some heads focus on semantic collocations.
If the input is still denoted as , the -th head has its own set of projection matrices:
So the output of the -th head is:
The results of multiple heads are concatenated and then projected back to the main model dimension by to be passed to subsequent layers:
Here, ; each head only looks at a small subspace; after heads are concatenated, the dimension returns to . Readers can derive the relationship between the matrix sizes and the model dimension themselves.
Using our example above, the process diagram is:
Note: Multi-head means there are multiple attention weight matrices, and each head has its own independent parameters.
2) Add & Norm
Self-Attention has already corrected each token's vector once. But if we directly pass this corrected result down, deep training can easily become unstable: the values may drift larger and larger, and the original word meaning may gradually be lost.
So every layer of the Transformer structure adds a stability component:
This has two steps:
- Add: Add the output of Self-Attention to the original input to preserve the original signal.
- LayerNorm: Normalize the summed result to push the values back into a stable range.
After FFN, it is done again:
In other words, there is an Add & Norm both before and after Attention and FFN. Together they ensure the stable flow of information.
Add — Residual Connection
Assume after Self-Attention, the vector of token love changes from:
to:
Without the residual connection, the next layer would receive [2.1, -1.0, 0.3]. This vector is already quite different from the original love vector [0.4, 0.5, 0.6]. If each layer does this, after 6 layers (the number of Encoder Layers in the original paper) the model may completely forget what love originally meant.
With the residual connection:
Although the numbers have changed, the vector [2.5, -0.5, 0.9] still contains the original [0.4, 0.5, 0.6] component. The original signal is not discarded; it is preserved as a "base."
In the stage-play metaphor: Attention lets every actor reinterpret their role, but Add lets the actor not forget "who they originally were."
In addition to preserving information, Add has another important role:
Deep learning adjusts model parameters through the backpropagation mechanism, which depends directly on gradients. Gradient computation is a chain multiplication from deep layers (near the output) to shallow layers (near the input). Without any treatment, the gradient can become close to zero early on (vanishing gradient), so the parameters of shallow layers cannot be trained effectively. With , the gradient can stably reach the shallow layers during computation.
The core lies in the mathematical form of the residual connection: the derivative of naturally contains a +1 (identity matrix). Let's expand this:
- Without Add
Suppose a layer is:
where may contain Attention, FFN, LayerNorm, etc.
Backpropagation computes the gradient:
If the network is very deep (still taking 6 layers as an example):
Then the gradient from Loss back to requires successive multiplication:
If the norm of each is less than 1 (for example, 0.6), then after 6 layers:
The closer to the shallow layers, the smaller the gradient, and the slower the parameter updates. This is the vanishing gradient problem.
- With Add
The residual connection becomes:
The derivative becomes:
where is the identity matrix.
Backpropagation:
Even if is small, the gradient still retains a full term.
Layer Normalization
Without Norm, the residual-added values would accumulate layer by layer. For example, assume each layer's correction is similar:
Continuing to add in the second layer:
By the sixth layer, the vector might become:
The values become larger and larger, and the distribution becomes more and more unstable. Later layers receiving this input will find training very difficult.
This is where LayerNorm comes in: for each token vector, normalize it so that the mean is pushed to 0 and the variance to 1, then fine-tune with learnable and :
In the original Transformer paper, Add and Norm use the Post-Norm form: add first, then normalize. Many modern large models (such as GPT and LLaMA) use Pre-Norm:
3) FFN: MLP is Still What You Need
The title of the paper Attention Is All You Need only emphasizes Attention, but the real core of Transformer is Attention + FFN.
- Attention solves "how tokens exchange information with each other."
- FFN solves "after each token receives information, how does it reprocess it internally."
If each token is an actor, then Attention is the actors rehearsing with each other, while FFN is the actor digesting their own script after rehearsal to perform better.
The FFN formula is:
where is the ReLU activation; modern models also commonly use GELU.
Attention + FFN?
The output of Attention is essentially:
That is, the new vector at each position is a weighted average of the Value vectors of other positions. It is still a linear combination in the input space, only with different weights.
If there were only Attention, no matter how many layers are stacked, what the model could learn would be limited: it can only redistribute existing information, not create new, more abstract features.
FFN's role is to give the model non-linear transformation capability, allowing it to learn patterns such as "if a feature exists, enhance it; if not, suppress it."
FFN is shared within a single layer: For the -th token: For the -th token: Both use the same set of parameters .
Up-Project, Activate, Down-Project
The FFN process is up-project → activate → down-project:
In the original paper, . For example, if , the FFN intermediate dimension is 2048.
The benefits are:
- Up-project: Expand semantics into a higher-dimensional space, making originally entangled features easier to separate.
- Activate: Use a non-linear function to turn linearly non-separable problems into separable ones.
- Down-project: Compress the result back to , so the next Encoder layer can continue.
Key-Value Memory
In addition to non-linear transformation, FFN also plays an important role: storing knowledge.
In recent years, many interpretability studies have suggested that FFN can be understood as a kind of Key-Value memory.
- is responsible for matching the input vector to certain "keys" (specific neurons).
- is responsible for outputting the corresponding "values" (semantic supplements).
Each hidden-layer neuron is like a knowledge entry. When the input vector matches an entry, that neuron is activated, and then through it writes the relevant knowledge into the residual stream.
For example, when Michael Jordan appears in the input:
- Its vector is projected by .
- Certain neurons are activated; these neurons have learned the "Michael Jordan pattern" during training.
- The activated neurons output a direction through , corresponding to semantics such as "basketball player," "NBA," and "Chicago Bulls."
- This output is added to the original vector through the residual connection.
So, the fact that Michael Jordan is a basketball player is not in the input token, but in the FFN weights.
Because FFN layers carry so much information, the main parameters of a Transformer model are not in Attention, but in FFN:
If , then the FFN parameters are several times the Attention parameters.
So "making the model bigger" largely means expanding the hidden dimension of FFN. The larger the FFN, the more knowledge entries it can store and process, and the stronger the model usually is.
Just like after Attention, the output of FFN also goes through an Add & Norm:
At this point, the flow within one layer is complete. The output is passed to the next layer. If this is already the last layer of the Encoder stack, the Encoder outputs the final context representation:
Let's call the memory (the paper Attention Is All You Need does not name it, but most code implementations call it memory). It can be understood as the model's "semantic memory after understanding," and is then handed over to the Decoder to complete expression and generation.
Decoder: Expression
After the Encoder reads the source sentence into memory , the Decoder is responsible for generating the target sentence word by word based on this memory.
It does not output the whole sentence at once, but generates it autoregressively one token at a time:
<BOS>is begin of sentence.<EOS>is end of sentence.
When<EOS>is generated, the whole sentence translation is complete.
The input to the Decoder is not the source sentence , but the part already generated on the target side. After Embedding and Position Embedding, it becomes matrix . Its processing flow is as follows:
In the Decoder, there are notably two Attention layers.
Masked Self-Attention
The first Attention layer in the Decoder is very similar to the Encoder's, but with an additional mask: when generating the -th word, it cannot see positions and beyond. Otherwise, during training it would directly copy the answer.
The Decoder has two Attention layers, each with its own different weight matrix .
Formula-wise, a mask matrix is simply added before softmax:
Allowed positions are filled with , and future positions are filled with . After softmax, the probability of future positions becomes 0.
When the target side has 4 positions, the mask looks like this: By inserting extremely small values, subsequent positions are blocked.
Cross-Attention
The Cross in Cross-Attention comes from the fact that it crosses two sequences: the Decoder's current sequence and the Encoder's source sequence.
Its key difference from Self-Attention is that comes through the Masked layer, while come from the Encoder memory:
Here is the output of Masked Self-Attention, and is the final memory output by the Encoder.
The meaning is: the Decoder's current position uses the Query to ask, "Which positions in the original sentence are relevant to what I am translating now?" and then takes away the semantics from the corresponding Value.
For example, when generating "狗", the Decoder's Cross-Attention will strongly focus on the row corresponding to dog in the Encoder memory; when generating "你的", it will focus more on your. This is the "alignment" in translation.
Example: Two Moments
We use the source sentence I love your dog and pick two autoregressive moments to demonstrate:
Moment 1: Generating "我"
The Decoder input is only <BOS>. After Masked Self-Attention, it knows "the sentence has just begun." The Cross-Attention Query takes this state and asks the original memory:
"What is the beginning of the source sentence? What should be translated first?"
The row corresponding to I in the original memory responds most strongly, so the Decoder outputs "我".
Moment 2: Generating "狗"
By now the Decoder has already generated <BOS> 我 爱 你的. The Masked Self-Attention sees this prefix and forms the state : next, a noun is needed. The Cross-Attention Query takes this state and asks the original sentence:
"I have already said '我 爱 你的'. Next I need a noun. Which word in the original sentence should be translated?"
The row corresponding to dog in the original memory responds most strongly, so the Decoder outputs "狗".
Each generated token is appended back to the target sequence, and the next round continues.
Add & Norm
Within a Decoder layer, there are two Attention layers, each followed by Add & Norm, and finally FFN:
We won't expand on this here.
After this step, the current Decoder layer's task is complete. The next step is the same as in the Encoder: if the current layer is not the last layer, it continues to be passed to the next Encoder layer; otherwise, the output of the last layer goes to the next step.
Linear + Softmax
The Decoder's last layer outputs a matrix. In autoregressive generation, we only need the last position vector to decide the next word. But is still in the internal semantic space ; to turn it into a probability over the vocabulary, two steps are needed.
Step 1: Linear Projection
Through a linear layer, is mapped to the vocabulary dimension:
Each row of corresponds to a word in the vocabulary. After projection, each dimension represents a "score" for a word; the higher the score, the more suitable that word is as the next token.
For example, if the vocabulary has 50,000 words, logits is a 50,000-dimensional vector. Suppose the score for "狗" is 4.2, "猫" is 1.5, and "人" is 0.3; the model is currently most inclined to generate "狗".
Step 2: Softmax
Softmax turns logits into a valid probability distribution, with all word probabilities summing to 1:
Continuing the example:
Finally, the model selects the next token based on this probability distribution. There are multiple selection strategies; the paper uses
beam search, which we won't expand on here. The selected token is appended back to the target sequence and sent into the Decoder for the next round. This continues until<EOS>is generated, and the whole sentence translation ends. At this point, the main line of the classic Encoder-Decoder Transformer is closed: the Encoder is responsible for reading the source sentence into memory, and the Decoder is responsible for saying the target sentence step by step based on that memory.
Conclusion
To this point, we have walked through the entire classic Transformer architecture. This typical structure was proposed to solve the machine translation seq2seq problem. From the start, we likened it to a translation machine, then dissected it layer by layer from encoder-decoder to the inner layers, from the initial tokenization to the full-sentence semantic construction of memory, and then to the Decoder's word-by-word output of the translation, completely explaining the working mechanism and purpose of each layer and component.
After mastering the structure of the translation machine, we can move toward the currently hot field of large model knowledge.